1 //===- InferAddressSpace.cpp - --------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // CUDA C/C++ includes memory space designation as variable type qualifers (such 10 // as __global__ and __shared__). Knowing the space of a memory access allows 11 // CUDA compilers to emit faster PTX loads and stores. For example, a load from 12 // shared memory can be translated to `ld.shared` which is roughly 10% faster 13 // than a generic `ld` on an NVIDIA Tesla K40c. 14 // 15 // Unfortunately, type qualifiers only apply to variable declarations, so CUDA 16 // compilers must infer the memory space of an address expression from 17 // type-qualified variables. 18 // 19 // LLVM IR uses non-zero (so-called) specific address spaces to represent memory 20 // spaces (e.g. addrspace(3) means shared memory). The Clang frontend 21 // places only type-qualified variables in specific address spaces, and then 22 // conservatively `addrspacecast`s each type-qualified variable to addrspace(0) 23 // (so-called the generic address space) for other instructions to use. 24 // 25 // For example, the Clang translates the following CUDA code 26 // __shared__ float a[10]; 27 // float v = a[i]; 28 // to 29 // %0 = addrspacecast [10 x float] addrspace(3)* @a to [10 x float]* 30 // %1 = gep [10 x float], [10 x float]* %0, i64 0, i64 %i 31 // %v = load float, float* %1 ; emits ld.f32 32 // @a is in addrspace(3) since it's type-qualified, but its use from %1 is 33 // redirected to %0 (the generic version of @a). 34 // 35 // The optimization implemented in this file propagates specific address spaces 36 // from type-qualified variable declarations to its users. For example, it 37 // optimizes the above IR to 38 // %1 = gep [10 x float] addrspace(3)* @a, i64 0, i64 %i 39 // %v = load float addrspace(3)* %1 ; emits ld.shared.f32 40 // propagating the addrspace(3) from @a to %1. As the result, the NVPTX 41 // codegen is able to emit ld.shared.f32 for %v. 42 // 43 // Address space inference works in two steps. First, it uses a data-flow 44 // analysis to infer as many generic pointers as possible to point to only one 45 // specific address space. In the above example, it can prove that %1 only 46 // points to addrspace(3). This algorithm was published in 47 // CUDA: Compiling and optimizing for a GPU platform 48 // Chakrabarti, Grover, Aarts, Kong, Kudlur, Lin, Marathe, Murphy, Wang 49 // ICCS 2012 50 // 51 // Then, address space inference replaces all refinable generic pointers with 52 // equivalent specific pointers. 53 // 54 // The major challenge of implementing this optimization is handling PHINodes, 55 // which may create loops in the data flow graph. This brings two complications. 56 // 57 // First, the data flow analysis in Step 1 needs to be circular. For example, 58 // %generic.input = addrspacecast float addrspace(3)* %input to float* 59 // loop: 60 // %y = phi [ %generic.input, %y2 ] 61 // %y2 = getelementptr %y, 1 62 // %v = load %y2 63 // br ..., label %loop, ... 64 // proving %y specific requires proving both %generic.input and %y2 specific, 65 // but proving %y2 specific circles back to %y. To address this complication, 66 // the data flow analysis operates on a lattice: 67 // uninitialized > specific address spaces > generic. 68 // All address expressions (our implementation only considers phi, bitcast, 69 // addrspacecast, and getelementptr) start with the uninitialized address space. 70 // The monotone transfer function moves the address space of a pointer down a 71 // lattice path from uninitialized to specific and then to generic. A join 72 // operation of two different specific address spaces pushes the expression down 73 // to the generic address space. The analysis completes once it reaches a fixed 74 // point. 75 // 76 // Second, IR rewriting in Step 2 also needs to be circular. For example, 77 // converting %y to addrspace(3) requires the compiler to know the converted 78 // %y2, but converting %y2 needs the converted %y. To address this complication, 79 // we break these cycles using "undef" placeholders. When converting an 80 // instruction `I` to a new address space, if its operand `Op` is not converted 81 // yet, we let `I` temporarily use `undef` and fix all the uses of undef later. 82 // For instance, our algorithm first converts %y to 83 // %y' = phi float addrspace(3)* [ %input, undef ] 84 // Then, it converts %y2 to 85 // %y2' = getelementptr %y', 1 86 // Finally, it fixes the undef in %y' so that 87 // %y' = phi float addrspace(3)* [ %input, %y2' ] 88 // 89 //===----------------------------------------------------------------------===// 90 91 #include "llvm/Transforms/Scalar/InferAddressSpaces.h" 92 #include "llvm/ADT/ArrayRef.h" 93 #include "llvm/ADT/DenseMap.h" 94 #include "llvm/ADT/DenseSet.h" 95 #include "llvm/ADT/None.h" 96 #include "llvm/ADT/Optional.h" 97 #include "llvm/ADT/SetVector.h" 98 #include "llvm/ADT/SmallVector.h" 99 #include "llvm/Analysis/AssumptionCache.h" 100 #include "llvm/Analysis/TargetTransformInfo.h" 101 #include "llvm/Analysis/ValueTracking.h" 102 #include "llvm/IR/BasicBlock.h" 103 #include "llvm/IR/Constant.h" 104 #include "llvm/IR/Constants.h" 105 #include "llvm/IR/Dominators.h" 106 #include "llvm/IR/Function.h" 107 #include "llvm/IR/IRBuilder.h" 108 #include "llvm/IR/InstIterator.h" 109 #include "llvm/IR/Instruction.h" 110 #include "llvm/IR/Instructions.h" 111 #include "llvm/IR/IntrinsicInst.h" 112 #include "llvm/IR/Intrinsics.h" 113 #include "llvm/IR/LLVMContext.h" 114 #include "llvm/IR/Operator.h" 115 #include "llvm/IR/PassManager.h" 116 #include "llvm/IR/Type.h" 117 #include "llvm/IR/Use.h" 118 #include "llvm/IR/User.h" 119 #include "llvm/IR/Value.h" 120 #include "llvm/IR/ValueHandle.h" 121 #include "llvm/InitializePasses.h" 122 #include "llvm/Pass.h" 123 #include "llvm/Support/Casting.h" 124 #include "llvm/Support/CommandLine.h" 125 #include "llvm/Support/Compiler.h" 126 #include "llvm/Support/Debug.h" 127 #include "llvm/Support/ErrorHandling.h" 128 #include "llvm/Support/raw_ostream.h" 129 #include "llvm/Transforms/Scalar.h" 130 #include "llvm/Transforms/Utils/Local.h" 131 #include "llvm/Transforms/Utils/ValueMapper.h" 132 #include <cassert> 133 #include <iterator> 134 #include <limits> 135 #include <utility> 136 #include <vector> 137 138 #define DEBUG_TYPE "infer-address-spaces" 139 140 using namespace llvm; 141 142 static cl::opt<bool> AssumeDefaultIsFlatAddressSpace( 143 "assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden, 144 cl::desc("The default address space is assumed as the flat address space. " 145 "This is mainly for test purpose.")); 146 147 static const unsigned UninitializedAddressSpace = 148 std::numeric_limits<unsigned>::max(); 149 150 namespace { 151 152 using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>; 153 // Different from ValueToAddrSpaceMapTy, where a new addrspace is inferred on 154 // the *def* of a value, PredicatedAddrSpaceMapTy is map where a new 155 // addrspace is inferred on the *use* of a pointer. This map is introduced to 156 // infer addrspace from the addrspace predicate assumption built from assume 157 // intrinsic. In that scenario, only specific uses (under valid assumption 158 // context) could be inferred with a new addrspace. 159 using PredicatedAddrSpaceMapTy = 160 DenseMap<std::pair<const Value *, const Value *>, unsigned>; 161 using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>; 162 163 class InferAddressSpaces : public FunctionPass { 164 unsigned FlatAddrSpace = 0; 165 166 public: 167 static char ID; 168 169 InferAddressSpaces() : 170 FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {} 171 InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {} 172 173 void getAnalysisUsage(AnalysisUsage &AU) const override { 174 AU.setPreservesCFG(); 175 AU.addPreserved<DominatorTreeWrapperPass>(); 176 AU.addRequired<AssumptionCacheTracker>(); 177 AU.addRequired<TargetTransformInfoWrapperPass>(); 178 } 179 180 bool runOnFunction(Function &F) override; 181 }; 182 183 class InferAddressSpacesImpl { 184 AssumptionCache &AC; 185 DominatorTree *DT = nullptr; 186 const TargetTransformInfo *TTI = nullptr; 187 const DataLayout *DL = nullptr; 188 189 /// Target specific address space which uses of should be replaced if 190 /// possible. 191 unsigned FlatAddrSpace = 0; 192 193 // Try to update the address space of V. If V is updated, returns true and 194 // false otherwise. 195 bool updateAddressSpace(const Value &V, 196 ValueToAddrSpaceMapTy &InferredAddrSpace, 197 PredicatedAddrSpaceMapTy &PredicatedAS) const; 198 199 // Tries to infer the specific address space of each address expression in 200 // Postorder. 201 void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder, 202 ValueToAddrSpaceMapTy &InferredAddrSpace, 203 PredicatedAddrSpaceMapTy &PredicatedAS) const; 204 205 bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const; 206 207 Value *cloneInstructionWithNewAddressSpace( 208 Instruction *I, unsigned NewAddrSpace, 209 const ValueToValueMapTy &ValueWithNewAddrSpace, 210 const PredicatedAddrSpaceMapTy &PredicatedAS, 211 SmallVectorImpl<const Use *> *UndefUsesToFix) const; 212 213 // Changes the flat address expressions in function F to point to specific 214 // address spaces if InferredAddrSpace says so. Postorder is the postorder of 215 // all flat expressions in the use-def graph of function F. 216 bool rewriteWithNewAddressSpaces( 217 const TargetTransformInfo &TTI, ArrayRef<WeakTrackingVH> Postorder, 218 const ValueToAddrSpaceMapTy &InferredAddrSpace, 219 const PredicatedAddrSpaceMapTy &PredicatedAS, Function *F) const; 220 221 void appendsFlatAddressExpressionToPostorderStack( 222 Value *V, PostorderStackTy &PostorderStack, 223 DenseSet<Value *> &Visited) const; 224 225 bool rewriteIntrinsicOperands(IntrinsicInst *II, 226 Value *OldV, Value *NewV) const; 227 void collectRewritableIntrinsicOperands(IntrinsicInst *II, 228 PostorderStackTy &PostorderStack, 229 DenseSet<Value *> &Visited) const; 230 231 std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const; 232 233 Value *cloneValueWithNewAddressSpace( 234 Value *V, unsigned NewAddrSpace, 235 const ValueToValueMapTy &ValueWithNewAddrSpace, 236 const PredicatedAddrSpaceMapTy &PredicatedAS, 237 SmallVectorImpl<const Use *> *UndefUsesToFix) const; 238 unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const; 239 240 unsigned getPredicatedAddrSpace(const Value &V, Value *Opnd) const; 241 242 public: 243 InferAddressSpacesImpl(AssumptionCache &AC, DominatorTree *DT, 244 const TargetTransformInfo *TTI, unsigned FlatAddrSpace) 245 : AC(AC), DT(DT), TTI(TTI), FlatAddrSpace(FlatAddrSpace) {} 246 bool run(Function &F); 247 }; 248 249 } // end anonymous namespace 250 251 char InferAddressSpaces::ID = 0; 252 253 INITIALIZE_PASS_BEGIN(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces", 254 false, false) 255 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 256 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 257 INITIALIZE_PASS_END(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces", 258 false, false) 259 260 // Check whether that's no-op pointer bicast using a pair of 261 // `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over 262 // different address spaces. 263 static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL, 264 const TargetTransformInfo *TTI) { 265 assert(I2P->getOpcode() == Instruction::IntToPtr); 266 auto *P2I = dyn_cast<Operator>(I2P->getOperand(0)); 267 if (!P2I || P2I->getOpcode() != Instruction::PtrToInt) 268 return false; 269 // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a 270 // no-op cast. Besides checking both of them are no-op casts, as the 271 // reinterpreted pointer may be used in other pointer arithmetic, we also 272 // need to double-check that through the target-specific hook. That ensures 273 // the underlying target also agrees that's a no-op address space cast and 274 // pointer bits are preserved. 275 // The current IR spec doesn't have clear rules on address space casts, 276 // especially a clear definition for pointer bits in non-default address 277 // spaces. It would be undefined if that pointer is dereferenced after an 278 // invalid reinterpret cast. Also, due to the unclearness for the meaning of 279 // bits in non-default address spaces in the current spec, the pointer 280 // arithmetic may also be undefined after invalid pointer reinterpret cast. 281 // However, as we confirm through the target hooks that it's a no-op 282 // addrspacecast, it doesn't matter since the bits should be the same. 283 return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()), 284 I2P->getOperand(0)->getType(), I2P->getType(), 285 DL) && 286 CastInst::isNoopCast(Instruction::CastOps(P2I->getOpcode()), 287 P2I->getOperand(0)->getType(), P2I->getType(), 288 DL) && 289 TTI->isNoopAddrSpaceCast( 290 P2I->getOperand(0)->getType()->getPointerAddressSpace(), 291 I2P->getType()->getPointerAddressSpace()); 292 } 293 294 // Returns true if V is an address expression. 295 // TODO: Currently, we consider only phi, bitcast, addrspacecast, and 296 // getelementptr operators. 297 static bool isAddressExpression(const Value &V, const DataLayout &DL, 298 const TargetTransformInfo *TTI) { 299 const Operator *Op = dyn_cast<Operator>(&V); 300 if (!Op) 301 return false; 302 303 switch (Op->getOpcode()) { 304 case Instruction::PHI: 305 assert(Op->getType()->isPointerTy()); 306 return true; 307 case Instruction::BitCast: 308 case Instruction::AddrSpaceCast: 309 case Instruction::GetElementPtr: 310 return true; 311 case Instruction::Select: 312 return Op->getType()->isPointerTy(); 313 case Instruction::Call: { 314 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V); 315 return II && II->getIntrinsicID() == Intrinsic::ptrmask; 316 } 317 case Instruction::IntToPtr: 318 return isNoopPtrIntCastPair(Op, DL, TTI); 319 default: 320 // That value is an address expression if it has an assumed address space. 321 return TTI->getAssumedAddrSpace(&V) != UninitializedAddressSpace; 322 } 323 } 324 325 // Returns the pointer operands of V. 326 // 327 // Precondition: V is an address expression. 328 static SmallVector<Value *, 2> 329 getPointerOperands(const Value &V, const DataLayout &DL, 330 const TargetTransformInfo *TTI) { 331 const Operator &Op = cast<Operator>(V); 332 switch (Op.getOpcode()) { 333 case Instruction::PHI: { 334 auto IncomingValues = cast<PHINode>(Op).incoming_values(); 335 return SmallVector<Value *, 2>(IncomingValues.begin(), 336 IncomingValues.end()); 337 } 338 case Instruction::BitCast: 339 case Instruction::AddrSpaceCast: 340 case Instruction::GetElementPtr: 341 return {Op.getOperand(0)}; 342 case Instruction::Select: 343 return {Op.getOperand(1), Op.getOperand(2)}; 344 case Instruction::Call: { 345 const IntrinsicInst &II = cast<IntrinsicInst>(Op); 346 assert(II.getIntrinsicID() == Intrinsic::ptrmask && 347 "unexpected intrinsic call"); 348 return {II.getArgOperand(0)}; 349 } 350 case Instruction::IntToPtr: { 351 assert(isNoopPtrIntCastPair(&Op, DL, TTI)); 352 auto *P2I = cast<Operator>(Op.getOperand(0)); 353 return {P2I->getOperand(0)}; 354 } 355 default: 356 llvm_unreachable("Unexpected instruction type."); 357 } 358 } 359 360 bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II, 361 Value *OldV, 362 Value *NewV) const { 363 Module *M = II->getParent()->getParent()->getParent(); 364 365 switch (II->getIntrinsicID()) { 366 case Intrinsic::objectsize: { 367 Type *DestTy = II->getType(); 368 Type *SrcTy = NewV->getType(); 369 Function *NewDecl = 370 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy}); 371 II->setArgOperand(0, NewV); 372 II->setCalledFunction(NewDecl); 373 return true; 374 } 375 case Intrinsic::ptrmask: 376 // This is handled as an address expression, not as a use memory operation. 377 return false; 378 default: { 379 Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV); 380 if (!Rewrite) 381 return false; 382 if (Rewrite != II) 383 II->replaceAllUsesWith(Rewrite); 384 return true; 385 } 386 } 387 } 388 389 void InferAddressSpacesImpl::collectRewritableIntrinsicOperands( 390 IntrinsicInst *II, PostorderStackTy &PostorderStack, 391 DenseSet<Value *> &Visited) const { 392 auto IID = II->getIntrinsicID(); 393 switch (IID) { 394 case Intrinsic::ptrmask: 395 case Intrinsic::objectsize: 396 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0), 397 PostorderStack, Visited); 398 break; 399 default: 400 SmallVector<int, 2> OpIndexes; 401 if (TTI->collectFlatAddressOperands(OpIndexes, IID)) { 402 for (int Idx : OpIndexes) { 403 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx), 404 PostorderStack, Visited); 405 } 406 } 407 break; 408 } 409 } 410 411 // Returns all flat address expressions in function F. The elements are 412 // If V is an unvisited flat address expression, appends V to PostorderStack 413 // and marks it as visited. 414 void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack( 415 Value *V, PostorderStackTy &PostorderStack, 416 DenseSet<Value *> &Visited) const { 417 assert(V->getType()->isPointerTy()); 418 419 // Generic addressing expressions may be hidden in nested constant 420 // expressions. 421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 422 // TODO: Look in non-address parts, like icmp operands. 423 if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second) 424 PostorderStack.emplace_back(CE, false); 425 426 return; 427 } 428 429 if (V->getType()->getPointerAddressSpace() == FlatAddrSpace && 430 isAddressExpression(*V, *DL, TTI)) { 431 if (Visited.insert(V).second) { 432 PostorderStack.emplace_back(V, false); 433 434 Operator *Op = cast<Operator>(V); 435 for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) { 436 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) { 437 if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second) 438 PostorderStack.emplace_back(CE, false); 439 } 440 } 441 } 442 } 443 } 444 445 // Returns all flat address expressions in function F. The elements are ordered 446 // ordered in postorder. 447 std::vector<WeakTrackingVH> 448 InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const { 449 // This function implements a non-recursive postorder traversal of a partial 450 // use-def graph of function F. 451 PostorderStackTy PostorderStack; 452 // The set of visited expressions. 453 DenseSet<Value *> Visited; 454 455 auto PushPtrOperand = [&](Value *Ptr) { 456 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack, 457 Visited); 458 }; 459 460 // Look at operations that may be interesting accelerate by moving to a known 461 // address space. We aim at generating after loads and stores, but pure 462 // addressing calculations may also be faster. 463 for (Instruction &I : instructions(F)) { 464 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 465 if (!GEP->getType()->isVectorTy()) 466 PushPtrOperand(GEP->getPointerOperand()); 467 } else if (auto *LI = dyn_cast<LoadInst>(&I)) 468 PushPtrOperand(LI->getPointerOperand()); 469 else if (auto *SI = dyn_cast<StoreInst>(&I)) 470 PushPtrOperand(SI->getPointerOperand()); 471 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I)) 472 PushPtrOperand(RMW->getPointerOperand()); 473 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I)) 474 PushPtrOperand(CmpX->getPointerOperand()); 475 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) { 476 // For memset/memcpy/memmove, any pointer operand can be replaced. 477 PushPtrOperand(MI->getRawDest()); 478 479 // Handle 2nd operand for memcpy/memmove. 480 if (auto *MTI = dyn_cast<MemTransferInst>(MI)) 481 PushPtrOperand(MTI->getRawSource()); 482 } else if (auto *II = dyn_cast<IntrinsicInst>(&I)) 483 collectRewritableIntrinsicOperands(II, PostorderStack, Visited); 484 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) { 485 // FIXME: Handle vectors of pointers 486 if (Cmp->getOperand(0)->getType()->isPointerTy()) { 487 PushPtrOperand(Cmp->getOperand(0)); 488 PushPtrOperand(Cmp->getOperand(1)); 489 } 490 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) { 491 if (!ASC->getType()->isVectorTy()) 492 PushPtrOperand(ASC->getPointerOperand()); 493 } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) { 494 if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI)) 495 PushPtrOperand( 496 cast<Operator>(I2P->getOperand(0))->getOperand(0)); 497 } 498 } 499 500 std::vector<WeakTrackingVH> Postorder; // The resultant postorder. 501 while (!PostorderStack.empty()) { 502 Value *TopVal = PostorderStack.back().getPointer(); 503 // If the operands of the expression on the top are already explored, 504 // adds that expression to the resultant postorder. 505 if (PostorderStack.back().getInt()) { 506 if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace) 507 Postorder.push_back(TopVal); 508 PostorderStack.pop_back(); 509 continue; 510 } 511 // Otherwise, adds its operands to the stack and explores them. 512 PostorderStack.back().setInt(true); 513 // Skip values with an assumed address space. 514 if (TTI->getAssumedAddrSpace(TopVal) == UninitializedAddressSpace) { 515 for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) { 516 appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack, 517 Visited); 518 } 519 } 520 } 521 return Postorder; 522 } 523 524 // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone 525 // of OperandUse.get() in the new address space. If the clone is not ready yet, 526 // returns an undef in the new address space as a placeholder. 527 static Value *operandWithNewAddressSpaceOrCreateUndef( 528 const Use &OperandUse, unsigned NewAddrSpace, 529 const ValueToValueMapTy &ValueWithNewAddrSpace, 530 const PredicatedAddrSpaceMapTy &PredicatedAS, 531 SmallVectorImpl<const Use *> *UndefUsesToFix) { 532 Value *Operand = OperandUse.get(); 533 534 Type *NewPtrTy = PointerType::getWithSamePointeeType( 535 cast<PointerType>(Operand->getType()), NewAddrSpace); 536 537 if (Constant *C = dyn_cast<Constant>(Operand)) 538 return ConstantExpr::getAddrSpaceCast(C, NewPtrTy); 539 540 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) 541 return NewOperand; 542 543 Instruction *Inst = cast<Instruction>(OperandUse.getUser()); 544 auto I = PredicatedAS.find(std::make_pair(Inst, Operand)); 545 if (I != PredicatedAS.end()) { 546 // Insert an addrspacecast on that operand before the user. 547 unsigned NewAS = I->second; 548 Type *NewPtrTy = PointerType::getWithSamePointeeType( 549 cast<PointerType>(Operand->getType()), NewAS); 550 auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy); 551 NewI->insertBefore(Inst); 552 return NewI; 553 } 554 555 UndefUsesToFix->push_back(&OperandUse); 556 return UndefValue::get(NewPtrTy); 557 } 558 559 // Returns a clone of `I` with its operands converted to those specified in 560 // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an 561 // operand whose address space needs to be modified might not exist in 562 // ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and 563 // adds that operand use to UndefUsesToFix so that caller can fix them later. 564 // 565 // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast 566 // from a pointer whose type already matches. Therefore, this function returns a 567 // Value* instead of an Instruction*. 568 // 569 // This may also return nullptr in the case the instruction could not be 570 // rewritten. 571 Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace( 572 Instruction *I, unsigned NewAddrSpace, 573 const ValueToValueMapTy &ValueWithNewAddrSpace, 574 const PredicatedAddrSpaceMapTy &PredicatedAS, 575 SmallVectorImpl<const Use *> *UndefUsesToFix) const { 576 Type *NewPtrType = PointerType::getWithSamePointeeType( 577 cast<PointerType>(I->getType()), NewAddrSpace); 578 579 if (I->getOpcode() == Instruction::AddrSpaceCast) { 580 Value *Src = I->getOperand(0); 581 // Because `I` is flat, the source address space must be specific. 582 // Therefore, the inferred address space must be the source space, according 583 // to our algorithm. 584 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace); 585 if (Src->getType() != NewPtrType) 586 return new BitCastInst(Src, NewPtrType); 587 return Src; 588 } 589 590 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 591 // Technically the intrinsic ID is a pointer typed argument, so specially 592 // handle calls early. 593 assert(II->getIntrinsicID() == Intrinsic::ptrmask); 594 Value *NewPtr = operandWithNewAddressSpaceOrCreateUndef( 595 II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace, 596 PredicatedAS, UndefUsesToFix); 597 Value *Rewrite = 598 TTI->rewriteIntrinsicWithAddressSpace(II, II->getArgOperand(0), NewPtr); 599 if (Rewrite) { 600 assert(Rewrite != II && "cannot modify this pointer operation in place"); 601 return Rewrite; 602 } 603 604 return nullptr; 605 } 606 607 unsigned AS = TTI->getAssumedAddrSpace(I); 608 if (AS != UninitializedAddressSpace) { 609 // For the assumed address space, insert an `addrspacecast` to make that 610 // explicit. 611 Type *NewPtrTy = PointerType::getWithSamePointeeType( 612 cast<PointerType>(I->getType()), AS); 613 auto *NewI = new AddrSpaceCastInst(I, NewPtrTy); 614 NewI->insertAfter(I); 615 return NewI; 616 } 617 618 // Computes the converted pointer operands. 619 SmallVector<Value *, 4> NewPointerOperands; 620 for (const Use &OperandUse : I->operands()) { 621 if (!OperandUse.get()->getType()->isPointerTy()) 622 NewPointerOperands.push_back(nullptr); 623 else 624 NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef( 625 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, 626 UndefUsesToFix)); 627 } 628 629 switch (I->getOpcode()) { 630 case Instruction::BitCast: 631 return new BitCastInst(NewPointerOperands[0], NewPtrType); 632 case Instruction::PHI: { 633 assert(I->getType()->isPointerTy()); 634 PHINode *PHI = cast<PHINode>(I); 635 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues()); 636 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) { 637 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index); 638 NewPHI->addIncoming(NewPointerOperands[OperandNo], 639 PHI->getIncomingBlock(Index)); 640 } 641 return NewPHI; 642 } 643 case Instruction::GetElementPtr: { 644 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 645 GetElementPtrInst *NewGEP = GetElementPtrInst::Create( 646 GEP->getSourceElementType(), NewPointerOperands[0], 647 SmallVector<Value *, 4>(GEP->indices())); 648 NewGEP->setIsInBounds(GEP->isInBounds()); 649 return NewGEP; 650 } 651 case Instruction::Select: 652 assert(I->getType()->isPointerTy()); 653 return SelectInst::Create(I->getOperand(0), NewPointerOperands[1], 654 NewPointerOperands[2], "", nullptr, I); 655 case Instruction::IntToPtr: { 656 assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI)); 657 Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0); 658 if (Src->getType() == NewPtrType) 659 return Src; 660 661 // If we had a no-op inttoptr/ptrtoint pair, we may still have inferred a 662 // source address space from a generic pointer source need to insert a cast 663 // back. 664 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Src, NewPtrType); 665 } 666 default: 667 llvm_unreachable("Unexpected opcode"); 668 } 669 } 670 671 // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the 672 // constant expression `CE` with its operands replaced as specified in 673 // ValueWithNewAddrSpace. 674 static Value *cloneConstantExprWithNewAddressSpace( 675 ConstantExpr *CE, unsigned NewAddrSpace, 676 const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL, 677 const TargetTransformInfo *TTI) { 678 Type *TargetType = CE->getType()->isPointerTy() 679 ? PointerType::getWithSamePointeeType( 680 cast<PointerType>(CE->getType()), NewAddrSpace) 681 : CE->getType(); 682 683 if (CE->getOpcode() == Instruction::AddrSpaceCast) { 684 // Because CE is flat, the source address space must be specific. 685 // Therefore, the inferred address space must be the source space according 686 // to our algorithm. 687 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() == 688 NewAddrSpace); 689 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType); 690 } 691 692 if (CE->getOpcode() == Instruction::BitCast) { 693 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0))) 694 return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType); 695 return ConstantExpr::getAddrSpaceCast(CE, TargetType); 696 } 697 698 if (CE->getOpcode() == Instruction::Select) { 699 Constant *Src0 = CE->getOperand(1); 700 Constant *Src1 = CE->getOperand(2); 701 if (Src0->getType()->getPointerAddressSpace() == 702 Src1->getType()->getPointerAddressSpace()) { 703 704 return ConstantExpr::getSelect( 705 CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType), 706 ConstantExpr::getAddrSpaceCast(Src1, TargetType)); 707 } 708 } 709 710 if (CE->getOpcode() == Instruction::IntToPtr) { 711 assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI)); 712 Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0); 713 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace); 714 return ConstantExpr::getBitCast(Src, TargetType); 715 } 716 717 // Computes the operands of the new constant expression. 718 bool IsNew = false; 719 SmallVector<Constant *, 4> NewOperands; 720 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) { 721 Constant *Operand = CE->getOperand(Index); 722 // If the address space of `Operand` needs to be modified, the new operand 723 // with the new address space should already be in ValueWithNewAddrSpace 724 // because (1) the constant expressions we consider (i.e. addrspacecast, 725 // bitcast, and getelementptr) do not incur cycles in the data flow graph 726 // and (2) this function is called on constant expressions in postorder. 727 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) { 728 IsNew = true; 729 NewOperands.push_back(cast<Constant>(NewOperand)); 730 continue; 731 } 732 if (auto CExpr = dyn_cast<ConstantExpr>(Operand)) 733 if (Value *NewOperand = cloneConstantExprWithNewAddressSpace( 734 CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) { 735 IsNew = true; 736 NewOperands.push_back(cast<Constant>(NewOperand)); 737 continue; 738 } 739 // Otherwise, reuses the old operand. 740 NewOperands.push_back(Operand); 741 } 742 743 // If !IsNew, we will replace the Value with itself. However, replaced values 744 // are assumed to wrapped in a addrspace cast later so drop it now. 745 if (!IsNew) 746 return nullptr; 747 748 if (CE->getOpcode() == Instruction::GetElementPtr) { 749 // Needs to specify the source type while constructing a getelementptr 750 // constant expression. 751 return CE->getWithOperands(NewOperands, TargetType, /*OnlyIfReduced=*/false, 752 cast<GEPOperator>(CE)->getSourceElementType()); 753 } 754 755 return CE->getWithOperands(NewOperands, TargetType); 756 } 757 758 // Returns a clone of the value `V`, with its operands replaced as specified in 759 // ValueWithNewAddrSpace. This function is called on every flat address 760 // expression whose address space needs to be modified, in postorder. 761 // 762 // See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix. 763 Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace( 764 Value *V, unsigned NewAddrSpace, 765 const ValueToValueMapTy &ValueWithNewAddrSpace, 766 const PredicatedAddrSpaceMapTy &PredicatedAS, 767 SmallVectorImpl<const Use *> *UndefUsesToFix) const { 768 // All values in Postorder are flat address expressions. 769 assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace && 770 isAddressExpression(*V, *DL, TTI)); 771 772 if (Instruction *I = dyn_cast<Instruction>(V)) { 773 Value *NewV = cloneInstructionWithNewAddressSpace( 774 I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, UndefUsesToFix); 775 if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) { 776 if (NewI->getParent() == nullptr) { 777 NewI->insertBefore(I); 778 NewI->takeName(I); 779 } 780 } 781 return NewV; 782 } 783 784 return cloneConstantExprWithNewAddressSpace( 785 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI); 786 } 787 788 // Defines the join operation on the address space lattice (see the file header 789 // comments). 790 unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1, 791 unsigned AS2) const { 792 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace) 793 return FlatAddrSpace; 794 795 if (AS1 == UninitializedAddressSpace) 796 return AS2; 797 if (AS2 == UninitializedAddressSpace) 798 return AS1; 799 800 // The join of two different specific address spaces is flat. 801 return (AS1 == AS2) ? AS1 : FlatAddrSpace; 802 } 803 804 bool InferAddressSpacesImpl::run(Function &F) { 805 DL = &F.getParent()->getDataLayout(); 806 807 if (AssumeDefaultIsFlatAddressSpace) 808 FlatAddrSpace = 0; 809 810 if (FlatAddrSpace == UninitializedAddressSpace) { 811 FlatAddrSpace = TTI->getFlatAddressSpace(); 812 if (FlatAddrSpace == UninitializedAddressSpace) 813 return false; 814 } 815 816 // Collects all flat address expressions in postorder. 817 std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F); 818 819 // Runs a data-flow analysis to refine the address spaces of every expression 820 // in Postorder. 821 ValueToAddrSpaceMapTy InferredAddrSpace; 822 PredicatedAddrSpaceMapTy PredicatedAS; 823 inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS); 824 825 // Changes the address spaces of the flat address expressions who are inferred 826 // to point to a specific address space. 827 return rewriteWithNewAddressSpaces(*TTI, Postorder, InferredAddrSpace, 828 PredicatedAS, &F); 829 } 830 831 // Constants need to be tracked through RAUW to handle cases with nested 832 // constant expressions, so wrap values in WeakTrackingVH. 833 void InferAddressSpacesImpl::inferAddressSpaces( 834 ArrayRef<WeakTrackingVH> Postorder, 835 ValueToAddrSpaceMapTy &InferredAddrSpace, 836 PredicatedAddrSpaceMapTy &PredicatedAS) const { 837 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end()); 838 // Initially, all expressions are in the uninitialized address space. 839 for (Value *V : Postorder) 840 InferredAddrSpace[V] = UninitializedAddressSpace; 841 842 while (!Worklist.empty()) { 843 Value *V = Worklist.pop_back_val(); 844 845 // Try to update the address space of the stack top according to the 846 // address spaces of its operands. 847 if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS)) 848 continue; 849 850 for (Value *User : V->users()) { 851 // Skip if User is already in the worklist. 852 if (Worklist.count(User)) 853 continue; 854 855 auto Pos = InferredAddrSpace.find(User); 856 // Our algorithm only updates the address spaces of flat address 857 // expressions, which are those in InferredAddrSpace. 858 if (Pos == InferredAddrSpace.end()) 859 continue; 860 861 // Function updateAddressSpace moves the address space down a lattice 862 // path. Therefore, nothing to do if User is already inferred as flat (the 863 // bottom element in the lattice). 864 if (Pos->second == FlatAddrSpace) 865 continue; 866 867 Worklist.insert(User); 868 } 869 } 870 } 871 872 unsigned InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &V, 873 Value *Opnd) const { 874 const Instruction *I = dyn_cast<Instruction>(&V); 875 if (!I) 876 return UninitializedAddressSpace; 877 878 Opnd = Opnd->stripInBoundsOffsets(); 879 for (auto &AssumeVH : AC.assumptionsFor(Opnd)) { 880 if (!AssumeVH) 881 continue; 882 CallInst *CI = cast<CallInst>(AssumeVH); 883 if (!isValidAssumeForContext(CI, I, DT)) 884 continue; 885 886 const Value *Ptr; 887 unsigned AS; 888 std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0)); 889 if (Ptr) 890 return AS; 891 } 892 893 return UninitializedAddressSpace; 894 } 895 896 bool InferAddressSpacesImpl::updateAddressSpace( 897 const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace, 898 PredicatedAddrSpaceMapTy &PredicatedAS) const { 899 assert(InferredAddrSpace.count(&V)); 900 901 LLVM_DEBUG(dbgs() << "Updating the address space of\n " << V << '\n'); 902 903 // The new inferred address space equals the join of the address spaces 904 // of all its pointer operands. 905 unsigned NewAS = UninitializedAddressSpace; 906 907 const Operator &Op = cast<Operator>(V); 908 if (Op.getOpcode() == Instruction::Select) { 909 Value *Src0 = Op.getOperand(1); 910 Value *Src1 = Op.getOperand(2); 911 912 auto I = InferredAddrSpace.find(Src0); 913 unsigned Src0AS = (I != InferredAddrSpace.end()) ? 914 I->second : Src0->getType()->getPointerAddressSpace(); 915 916 auto J = InferredAddrSpace.find(Src1); 917 unsigned Src1AS = (J != InferredAddrSpace.end()) ? 918 J->second : Src1->getType()->getPointerAddressSpace(); 919 920 auto *C0 = dyn_cast<Constant>(Src0); 921 auto *C1 = dyn_cast<Constant>(Src1); 922 923 // If one of the inputs is a constant, we may be able to do a constant 924 // addrspacecast of it. Defer inferring the address space until the input 925 // address space is known. 926 if ((C1 && Src0AS == UninitializedAddressSpace) || 927 (C0 && Src1AS == UninitializedAddressSpace)) 928 return false; 929 930 if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS)) 931 NewAS = Src1AS; 932 else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS)) 933 NewAS = Src0AS; 934 else 935 NewAS = joinAddressSpaces(Src0AS, Src1AS); 936 } else { 937 unsigned AS = TTI->getAssumedAddrSpace(&V); 938 if (AS != UninitializedAddressSpace) { 939 // Use the assumed address space directly. 940 NewAS = AS; 941 } else { 942 // Otherwise, infer the address space from its pointer operands. 943 for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) { 944 auto I = InferredAddrSpace.find(PtrOperand); 945 unsigned OperandAS; 946 if (I == InferredAddrSpace.end()) { 947 OperandAS = PtrOperand->getType()->getPointerAddressSpace(); 948 if (OperandAS == FlatAddrSpace) { 949 // Check AC for assumption dominating V. 950 unsigned AS = getPredicatedAddrSpace(V, PtrOperand); 951 if (AS != UninitializedAddressSpace) { 952 LLVM_DEBUG(dbgs() 953 << " deduce operand AS from the predicate addrspace " 954 << AS << '\n'); 955 OperandAS = AS; 956 // Record this use with the predicated AS. 957 PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS; 958 } 959 } 960 } else 961 OperandAS = I->second; 962 963 // join(flat, *) = flat. So we can break if NewAS is already flat. 964 NewAS = joinAddressSpaces(NewAS, OperandAS); 965 if (NewAS == FlatAddrSpace) 966 break; 967 } 968 } 969 } 970 971 unsigned OldAS = InferredAddrSpace.lookup(&V); 972 assert(OldAS != FlatAddrSpace); 973 if (OldAS == NewAS) 974 return false; 975 976 // If any updates are made, grabs its users to the worklist because 977 // their address spaces can also be possibly updated. 978 LLVM_DEBUG(dbgs() << " to " << NewAS << '\n'); 979 InferredAddrSpace[&V] = NewAS; 980 return true; 981 } 982 983 /// \p returns true if \p U is the pointer operand of a memory instruction with 984 /// a single pointer operand that can have its address space changed by simply 985 /// mutating the use to a new value. If the memory instruction is volatile, 986 /// return true only if the target allows the memory instruction to be volatile 987 /// in the new address space. 988 static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI, 989 Use &U, unsigned AddrSpace) { 990 User *Inst = U.getUser(); 991 unsigned OpNo = U.getOperandNo(); 992 bool VolatileIsAllowed = false; 993 if (auto *I = dyn_cast<Instruction>(Inst)) 994 VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace); 995 996 if (auto *LI = dyn_cast<LoadInst>(Inst)) 997 return OpNo == LoadInst::getPointerOperandIndex() && 998 (VolatileIsAllowed || !LI->isVolatile()); 999 1000 if (auto *SI = dyn_cast<StoreInst>(Inst)) 1001 return OpNo == StoreInst::getPointerOperandIndex() && 1002 (VolatileIsAllowed || !SI->isVolatile()); 1003 1004 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst)) 1005 return OpNo == AtomicRMWInst::getPointerOperandIndex() && 1006 (VolatileIsAllowed || !RMW->isVolatile()); 1007 1008 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) 1009 return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() && 1010 (VolatileIsAllowed || !CmpX->isVolatile()); 1011 1012 return false; 1013 } 1014 1015 /// Update memory intrinsic uses that require more complex processing than 1016 /// simple memory instructions. Thse require re-mangling and may have multiple 1017 /// pointer operands. 1018 static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV, 1019 Value *NewV) { 1020 IRBuilder<> B(MI); 1021 MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa); 1022 MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope); 1023 MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias); 1024 1025 if (auto *MSI = dyn_cast<MemSetInst>(MI)) { 1026 B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), 1027 MaybeAlign(MSI->getDestAlignment()), 1028 false, // isVolatile 1029 TBAA, ScopeMD, NoAliasMD); 1030 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) { 1031 Value *Src = MTI->getRawSource(); 1032 Value *Dest = MTI->getRawDest(); 1033 1034 // Be careful in case this is a self-to-self copy. 1035 if (Src == OldV) 1036 Src = NewV; 1037 1038 if (Dest == OldV) 1039 Dest = NewV; 1040 1041 if (isa<MemCpyInlineInst>(MTI)) { 1042 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct); 1043 B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src, 1044 MTI->getSourceAlign(), MTI->getLength(), 1045 false, // isVolatile 1046 TBAA, TBAAStruct, ScopeMD, NoAliasMD); 1047 } else if (isa<MemCpyInst>(MTI)) { 1048 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct); 1049 B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(), 1050 MTI->getLength(), 1051 false, // isVolatile 1052 TBAA, TBAAStruct, ScopeMD, NoAliasMD); 1053 } else { 1054 assert(isa<MemMoveInst>(MTI)); 1055 B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(), 1056 MTI->getLength(), 1057 false, // isVolatile 1058 TBAA, ScopeMD, NoAliasMD); 1059 } 1060 } else 1061 llvm_unreachable("unhandled MemIntrinsic"); 1062 1063 MI->eraseFromParent(); 1064 return true; 1065 } 1066 1067 // \p returns true if it is OK to change the address space of constant \p C with 1068 // a ConstantExpr addrspacecast. 1069 bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C, 1070 unsigned NewAS) const { 1071 assert(NewAS != UninitializedAddressSpace); 1072 1073 unsigned SrcAS = C->getType()->getPointerAddressSpace(); 1074 if (SrcAS == NewAS || isa<UndefValue>(C)) 1075 return true; 1076 1077 // Prevent illegal casts between different non-flat address spaces. 1078 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace) 1079 return false; 1080 1081 if (isa<ConstantPointerNull>(C)) 1082 return true; 1083 1084 if (auto *Op = dyn_cast<Operator>(C)) { 1085 // If we already have a constant addrspacecast, it should be safe to cast it 1086 // off. 1087 if (Op->getOpcode() == Instruction::AddrSpaceCast) 1088 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS); 1089 1090 if (Op->getOpcode() == Instruction::IntToPtr && 1091 Op->getType()->getPointerAddressSpace() == FlatAddrSpace) 1092 return true; 1093 } 1094 1095 return false; 1096 } 1097 1098 static Value::use_iterator skipToNextUser(Value::use_iterator I, 1099 Value::use_iterator End) { 1100 User *CurUser = I->getUser(); 1101 ++I; 1102 1103 while (I != End && I->getUser() == CurUser) 1104 ++I; 1105 1106 return I; 1107 } 1108 1109 bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces( 1110 const TargetTransformInfo &TTI, ArrayRef<WeakTrackingVH> Postorder, 1111 const ValueToAddrSpaceMapTy &InferredAddrSpace, 1112 const PredicatedAddrSpaceMapTy &PredicatedAS, Function *F) const { 1113 // For each address expression to be modified, creates a clone of it with its 1114 // pointer operands converted to the new address space. Since the pointer 1115 // operands are converted, the clone is naturally in the new address space by 1116 // construction. 1117 ValueToValueMapTy ValueWithNewAddrSpace; 1118 SmallVector<const Use *, 32> UndefUsesToFix; 1119 for (Value* V : Postorder) { 1120 unsigned NewAddrSpace = InferredAddrSpace.lookup(V); 1121 1122 // In some degenerate cases (e.g. invalid IR in unreachable code), we may 1123 // not even infer the value to have its original address space. 1124 if (NewAddrSpace == UninitializedAddressSpace) 1125 continue; 1126 1127 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) { 1128 Value *New = 1129 cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace, 1130 PredicatedAS, &UndefUsesToFix); 1131 if (New) 1132 ValueWithNewAddrSpace[V] = New; 1133 } 1134 } 1135 1136 if (ValueWithNewAddrSpace.empty()) 1137 return false; 1138 1139 // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace. 1140 for (const Use *UndefUse : UndefUsesToFix) { 1141 User *V = UndefUse->getUser(); 1142 User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V)); 1143 if (!NewV) 1144 continue; 1145 1146 unsigned OperandNo = UndefUse->getOperandNo(); 1147 assert(isa<UndefValue>(NewV->getOperand(OperandNo))); 1148 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get())); 1149 } 1150 1151 SmallVector<Instruction *, 16> DeadInstructions; 1152 1153 // Replaces the uses of the old address expressions with the new ones. 1154 for (const WeakTrackingVH &WVH : Postorder) { 1155 assert(WVH && "value was unexpectedly deleted"); 1156 Value *V = WVH; 1157 Value *NewV = ValueWithNewAddrSpace.lookup(V); 1158 if (NewV == nullptr) 1159 continue; 1160 1161 LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n with\n " 1162 << *NewV << '\n'); 1163 1164 if (Constant *C = dyn_cast<Constant>(V)) { 1165 Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV), 1166 C->getType()); 1167 if (C != Replace) { 1168 LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace 1169 << ": " << *Replace << '\n'); 1170 C->replaceAllUsesWith(Replace); 1171 V = Replace; 1172 } 1173 } 1174 1175 Value::use_iterator I, E, Next; 1176 for (I = V->use_begin(), E = V->use_end(); I != E; ) { 1177 Use &U = *I; 1178 1179 // Some users may see the same pointer operand in multiple operands. Skip 1180 // to the next instruction. 1181 I = skipToNextUser(I, E); 1182 1183 if (isSimplePointerUseValidToReplace( 1184 TTI, U, V->getType()->getPointerAddressSpace())) { 1185 // If V is used as the pointer operand of a compatible memory operation, 1186 // sets the pointer operand to NewV. This replacement does not change 1187 // the element type, so the resultant load/store is still valid. 1188 U.set(NewV); 1189 continue; 1190 } 1191 1192 User *CurUser = U.getUser(); 1193 // Skip if the current user is the new value itself. 1194 if (CurUser == NewV) 1195 continue; 1196 // Handle more complex cases like intrinsic that need to be remangled. 1197 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) { 1198 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV)) 1199 continue; 1200 } 1201 1202 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) { 1203 if (rewriteIntrinsicOperands(II, V, NewV)) 1204 continue; 1205 } 1206 1207 if (isa<Instruction>(CurUser)) { 1208 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) { 1209 // If we can infer that both pointers are in the same addrspace, 1210 // transform e.g. 1211 // %cmp = icmp eq float* %p, %q 1212 // into 1213 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q 1214 1215 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1216 int SrcIdx = U.getOperandNo(); 1217 int OtherIdx = (SrcIdx == 0) ? 1 : 0; 1218 Value *OtherSrc = Cmp->getOperand(OtherIdx); 1219 1220 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) { 1221 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) { 1222 Cmp->setOperand(OtherIdx, OtherNewV); 1223 Cmp->setOperand(SrcIdx, NewV); 1224 continue; 1225 } 1226 } 1227 1228 // Even if the type mismatches, we can cast the constant. 1229 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) { 1230 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) { 1231 Cmp->setOperand(SrcIdx, NewV); 1232 Cmp->setOperand(OtherIdx, 1233 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType())); 1234 continue; 1235 } 1236 } 1237 } 1238 1239 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) { 1240 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1241 if (ASC->getDestAddressSpace() == NewAS) { 1242 if (!cast<PointerType>(ASC->getType()) 1243 ->hasSameElementTypeAs( 1244 cast<PointerType>(NewV->getType()))) { 1245 NewV = CastInst::Create(Instruction::BitCast, NewV, 1246 ASC->getType(), "", ASC); 1247 } 1248 ASC->replaceAllUsesWith(NewV); 1249 DeadInstructions.push_back(ASC); 1250 continue; 1251 } 1252 } 1253 1254 // Otherwise, replaces the use with flat(NewV). 1255 if (Instruction *Inst = dyn_cast<Instruction>(V)) { 1256 // Don't create a copy of the original addrspacecast. 1257 if (U == V && isa<AddrSpaceCastInst>(V)) 1258 continue; 1259 1260 BasicBlock::iterator InsertPos = std::next(Inst->getIterator()); 1261 while (isa<PHINode>(InsertPos)) 1262 ++InsertPos; 1263 U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos)); 1264 } else { 1265 U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV), 1266 V->getType())); 1267 } 1268 } 1269 } 1270 1271 if (V->use_empty()) { 1272 if (Instruction *I = dyn_cast<Instruction>(V)) 1273 DeadInstructions.push_back(I); 1274 } 1275 } 1276 1277 for (Instruction *I : DeadInstructions) 1278 RecursivelyDeleteTriviallyDeadInstructions(I); 1279 1280 return true; 1281 } 1282 1283 bool InferAddressSpaces::runOnFunction(Function &F) { 1284 if (skipFunction(F)) 1285 return false; 1286 1287 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 1288 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 1289 return InferAddressSpacesImpl( 1290 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT, 1291 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F), 1292 FlatAddrSpace) 1293 .run(F); 1294 } 1295 1296 FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) { 1297 return new InferAddressSpaces(AddressSpace); 1298 } 1299 1300 InferAddressSpacesPass::InferAddressSpacesPass() 1301 : FlatAddrSpace(UninitializedAddressSpace) {} 1302 InferAddressSpacesPass::InferAddressSpacesPass(unsigned AddressSpace) 1303 : FlatAddrSpace(AddressSpace) {} 1304 1305 PreservedAnalyses InferAddressSpacesPass::run(Function &F, 1306 FunctionAnalysisManager &AM) { 1307 bool Changed = 1308 InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F), 1309 AM.getCachedResult<DominatorTreeAnalysis>(F), 1310 &AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace) 1311 .run(F); 1312 if (Changed) { 1313 PreservedAnalyses PA; 1314 PA.preserveSet<CFGAnalyses>(); 1315 PA.preserve<DominatorTreeAnalysis>(); 1316 return PA; 1317 } 1318 return PreservedAnalyses::all(); 1319 } 1320