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