1 //===-- NVPTXInferAddressSpace.cpp - ---------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // CUDA C/C++ includes memory space designation as variable type qualifers (such 11 // as __global__ and __shared__). Knowing the space of a memory access allows 12 // CUDA compilers to emit faster PTX loads and stores. For example, a load from 13 // shared memory can be translated to `ld.shared` which is roughly 10% faster 14 // than a generic `ld` on an NVIDIA Tesla K40c. 15 // 16 // Unfortunately, type qualifiers only apply to variable declarations, so CUDA 17 // compilers must infer the memory space of an address expression from 18 // type-qualified variables. 19 // 20 // LLVM IR uses non-zero (so-called) specific address spaces to represent memory 21 // spaces (e.g. addrspace(3) means shared memory). The Clang frontend 22 // places only type-qualified variables in specific address spaces, and then 23 // conservatively `addrspacecast`s each type-qualified variable to addrspace(0) 24 // (so-called the generic address space) for other instructions to use. 25 // 26 // For example, the Clang translates the following CUDA code 27 // __shared__ float a[10]; 28 // float v = a[i]; 29 // to 30 // %0 = addrspacecast [10 x float] addrspace(3)* @a to [10 x float]* 31 // %1 = gep [10 x float], [10 x float]* %0, i64 0, i64 %i 32 // %v = load float, float* %1 ; emits ld.f32 33 // @a is in addrspace(3) since it's type-qualified, but its use from %1 is 34 // redirected to %0 (the generic version of @a). 35 // 36 // The optimization implemented in this file propagates specific address spaces 37 // from type-qualified variable declarations to its users. For example, it 38 // optimizes the above IR to 39 // %1 = gep [10 x float] addrspace(3)* @a, i64 0, i64 %i 40 // %v = load float addrspace(3)* %1 ; emits ld.shared.f32 41 // propagating the addrspace(3) from @a to %1. As the result, the NVPTX 42 // codegen is able to emit ld.shared.f32 for %v. 43 // 44 // Address space inference works in two steps. First, it uses a data-flow 45 // analysis to infer as many generic pointers as possible to point to only one 46 // specific address space. In the above example, it can prove that %1 only 47 // points to addrspace(3). This algorithm was published in 48 // CUDA: Compiling and optimizing for a GPU platform 49 // Chakrabarti, Grover, Aarts, Kong, Kudlur, Lin, Marathe, Murphy, Wang 50 // ICCS 2012 51 // 52 // Then, address space inference replaces all refinable generic pointers with 53 // equivalent specific pointers. 54 // 55 // The major challenge of implementing this optimization is handling PHINodes, 56 // which may create loops in the data flow graph. This brings two complications. 57 // 58 // First, the data flow analysis in Step 1 needs to be circular. For example, 59 // %generic.input = addrspacecast float addrspace(3)* %input to float* 60 // loop: 61 // %y = phi [ %generic.input, %y2 ] 62 // %y2 = getelementptr %y, 1 63 // %v = load %y2 64 // br ..., label %loop, ... 65 // proving %y specific requires proving both %generic.input and %y2 specific, 66 // but proving %y2 specific circles back to %y. To address this complication, 67 // the data flow analysis operates on a lattice: 68 // uninitialized > specific address spaces > generic. 69 // All address expressions (our implementation only considers phi, bitcast, 70 // addrspacecast, and getelementptr) start with the uninitialized address space. 71 // The monotone transfer function moves the address space of a pointer down a 72 // lattice path from uninitialized to specific and then to generic. A join 73 // operation of two different specific address spaces pushes the expression down 74 // to the generic address space. The analysis completes once it reaches a fixed 75 // point. 76 // 77 // Second, IR rewriting in Step 2 also needs to be circular. For example, 78 // converting %y to addrspace(3) requires the compiler to know the converted 79 // %y2, but converting %y2 needs the converted %y. To address this complication, 80 // we break these cycles using "undef" placeholders. When converting an 81 // instruction `I` to a new address space, if its operand `Op` is not converted 82 // yet, we let `I` temporarily use `undef` and fix all the uses of undef later. 83 // For instance, our algorithm first converts %y to 84 // %y' = phi float addrspace(3)* [ %input, undef ] 85 // Then, it converts %y2 to 86 // %y2' = getelementptr %y', 1 87 // Finally, it fixes the undef in %y' so that 88 // %y' = phi float addrspace(3)* [ %input, %y2' ] 89 // 90 //===----------------------------------------------------------------------===// 91 92 #include "llvm/ADT/DenseSet.h" 93 #include "llvm/ADT/Optional.h" 94 #include "llvm/ADT/SetVector.h" 95 #include "llvm/Analysis/TargetTransformInfo.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/IRBuilder.h" 98 #include "llvm/IR/InstIterator.h" 99 #include "llvm/IR/Instructions.h" 100 #include "llvm/IR/IntrinsicInst.h" 101 #include "llvm/IR/Operator.h" 102 #include "llvm/Support/Debug.h" 103 #include "llvm/Support/raw_ostream.h" 104 #include "llvm/Transforms/Scalar.h" 105 #include "llvm/Transforms/Utils/Local.h" 106 #include "llvm/Transforms/Utils/ValueMapper.h" 107 108 #define DEBUG_TYPE "infer-address-spaces" 109 110 using namespace llvm; 111 112 namespace { 113 static const unsigned UninitializedAddressSpace = ~0u; 114 115 using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>; 116 117 /// \brief InferAddressSpaces 118 class InferAddressSpaces : public FunctionPass { 119 /// Target specific address space which uses of should be replaced if 120 /// possible. 121 unsigned FlatAddrSpace; 122 123 public: 124 static char ID; 125 126 InferAddressSpaces() : FunctionPass(ID) {} 127 128 void getAnalysisUsage(AnalysisUsage &AU) const override { 129 AU.setPreservesCFG(); 130 AU.addRequired<TargetTransformInfoWrapperPass>(); 131 } 132 133 bool runOnFunction(Function &F) override; 134 135 private: 136 // Returns the new address space of V if updated; otherwise, returns None. 137 Optional<unsigned> 138 updateAddressSpace(const Value &V, 139 const ValueToAddrSpaceMapTy &InferredAddrSpace) const; 140 141 // Tries to infer the specific address space of each address expression in 142 // Postorder. 143 void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder, 144 ValueToAddrSpaceMapTy *InferredAddrSpace) const; 145 146 bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const; 147 148 // Changes the flat address expressions in function F to point to specific 149 // address spaces if InferredAddrSpace says so. Postorder is the postorder of 150 // all flat expressions in the use-def graph of function F. 151 bool rewriteWithNewAddressSpaces( 152 const TargetTransformInfo &TTI, ArrayRef<WeakTrackingVH> Postorder, 153 const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const; 154 155 void appendsFlatAddressExpressionToPostorderStack( 156 Value *V, std::vector<std::pair<Value *, bool>> &PostorderStack, 157 DenseSet<Value *> &Visited) const; 158 159 bool rewriteIntrinsicOperands(IntrinsicInst *II, 160 Value *OldV, Value *NewV) const; 161 void collectRewritableIntrinsicOperands( 162 IntrinsicInst *II, 163 std::vector<std::pair<Value *, bool>> &PostorderStack, 164 DenseSet<Value *> &Visited) const; 165 166 std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const; 167 168 Value *cloneValueWithNewAddressSpace( 169 Value *V, unsigned NewAddrSpace, 170 const ValueToValueMapTy &ValueWithNewAddrSpace, 171 SmallVectorImpl<const Use *> *UndefUsesToFix) const; 172 unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const; 173 }; 174 } // end anonymous namespace 175 176 char InferAddressSpaces::ID = 0; 177 178 namespace llvm { 179 void initializeInferAddressSpacesPass(PassRegistry &); 180 } 181 182 INITIALIZE_PASS(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces", 183 false, false) 184 185 // Returns true if V is an address expression. 186 // TODO: Currently, we consider only phi, bitcast, addrspacecast, and 187 // getelementptr operators. 188 static bool isAddressExpression(const Value &V) { 189 if (!isa<Operator>(V)) 190 return false; 191 192 switch (cast<Operator>(V).getOpcode()) { 193 case Instruction::PHI: 194 case Instruction::BitCast: 195 case Instruction::AddrSpaceCast: 196 case Instruction::GetElementPtr: 197 case Instruction::Select: 198 return true; 199 default: 200 return false; 201 } 202 } 203 204 // Returns the pointer operands of V. 205 // 206 // Precondition: V is an address expression. 207 static SmallVector<Value *, 2> getPointerOperands(const Value &V) { 208 const Operator &Op = cast<Operator>(V); 209 switch (Op.getOpcode()) { 210 case Instruction::PHI: { 211 auto IncomingValues = cast<PHINode>(Op).incoming_values(); 212 return SmallVector<Value *, 2>(IncomingValues.begin(), 213 IncomingValues.end()); 214 } 215 case Instruction::BitCast: 216 case Instruction::AddrSpaceCast: 217 case Instruction::GetElementPtr: 218 return {Op.getOperand(0)}; 219 case Instruction::Select: 220 return {Op.getOperand(1), Op.getOperand(2)}; 221 default: 222 llvm_unreachable("Unexpected instruction type."); 223 } 224 } 225 226 // TODO: Move logic to TTI? 227 bool InferAddressSpaces::rewriteIntrinsicOperands(IntrinsicInst *II, 228 Value *OldV, 229 Value *NewV) const { 230 Module *M = II->getParent()->getParent()->getParent(); 231 232 switch (II->getIntrinsicID()) { 233 case Intrinsic::amdgcn_atomic_inc: 234 case Intrinsic::amdgcn_atomic_dec:{ 235 const ConstantInt *IsVolatile = dyn_cast<ConstantInt>(II->getArgOperand(4)); 236 if (!IsVolatile || !IsVolatile->isZero()) 237 return false; 238 239 LLVM_FALLTHROUGH; 240 } 241 case Intrinsic::objectsize: { 242 Type *DestTy = II->getType(); 243 Type *SrcTy = NewV->getType(); 244 Function *NewDecl = 245 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy}); 246 II->setArgOperand(0, NewV); 247 II->setCalledFunction(NewDecl); 248 return true; 249 } 250 default: 251 return false; 252 } 253 } 254 255 // TODO: Move logic to TTI? 256 void InferAddressSpaces::collectRewritableIntrinsicOperands( 257 IntrinsicInst *II, std::vector<std::pair<Value *, bool>> &PostorderStack, 258 DenseSet<Value *> &Visited) const { 259 switch (II->getIntrinsicID()) { 260 case Intrinsic::objectsize: 261 case Intrinsic::amdgcn_atomic_inc: 262 case Intrinsic::amdgcn_atomic_dec: 263 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0), 264 PostorderStack, Visited); 265 break; 266 default: 267 break; 268 } 269 } 270 271 // Returns all flat address expressions in function F. The elements are 272 // If V is an unvisited flat address expression, appends V to PostorderStack 273 // and marks it as visited. 274 void InferAddressSpaces::appendsFlatAddressExpressionToPostorderStack( 275 Value *V, std::vector<std::pair<Value *, bool>> &PostorderStack, 276 DenseSet<Value *> &Visited) const { 277 assert(V->getType()->isPointerTy()); 278 279 // Generic addressing expressions may be hidden in nested constant 280 // expressions. 281 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 282 // TODO: Look in non-address parts, like icmp operands. 283 if (isAddressExpression(*CE) && Visited.insert(CE).second) 284 PostorderStack.push_back(std::make_pair(CE, false)); 285 286 return; 287 } 288 289 if (isAddressExpression(*V) && 290 V->getType()->getPointerAddressSpace() == FlatAddrSpace) { 291 if (Visited.insert(V).second) { 292 PostorderStack.push_back(std::make_pair(V, false)); 293 294 Operator *Op = cast<Operator>(V); 295 for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) { 296 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) { 297 if (isAddressExpression(*CE) && Visited.insert(CE).second) 298 PostorderStack.emplace_back(CE, false); 299 } 300 } 301 } 302 } 303 } 304 305 // Returns all flat address expressions in function F. The elements are ordered 306 // ordered in postorder. 307 std::vector<WeakTrackingVH> 308 InferAddressSpaces::collectFlatAddressExpressions(Function &F) const { 309 // This function implements a non-recursive postorder traversal of a partial 310 // use-def graph of function F. 311 std::vector<std::pair<Value *, bool>> PostorderStack; 312 // The set of visited expressions. 313 DenseSet<Value *> Visited; 314 315 auto PushPtrOperand = [&](Value *Ptr) { 316 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack, 317 Visited); 318 }; 319 320 // Look at operations that may be interesting accelerate by moving to a known 321 // address space. We aim at generating after loads and stores, but pure 322 // addressing calculations may also be faster. 323 for (Instruction &I : instructions(F)) { 324 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 325 if (!GEP->getType()->isVectorTy()) 326 PushPtrOperand(GEP->getPointerOperand()); 327 } else if (auto *LI = dyn_cast<LoadInst>(&I)) 328 PushPtrOperand(LI->getPointerOperand()); 329 else if (auto *SI = dyn_cast<StoreInst>(&I)) 330 PushPtrOperand(SI->getPointerOperand()); 331 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I)) 332 PushPtrOperand(RMW->getPointerOperand()); 333 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I)) 334 PushPtrOperand(CmpX->getPointerOperand()); 335 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) { 336 // For memset/memcpy/memmove, any pointer operand can be replaced. 337 PushPtrOperand(MI->getRawDest()); 338 339 // Handle 2nd operand for memcpy/memmove. 340 if (auto *MTI = dyn_cast<MemTransferInst>(MI)) 341 PushPtrOperand(MTI->getRawSource()); 342 } else if (auto *II = dyn_cast<IntrinsicInst>(&I)) 343 collectRewritableIntrinsicOperands(II, PostorderStack, Visited); 344 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) { 345 // FIXME: Handle vectors of pointers 346 if (Cmp->getOperand(0)->getType()->isPointerTy()) { 347 PushPtrOperand(Cmp->getOperand(0)); 348 PushPtrOperand(Cmp->getOperand(1)); 349 } 350 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) { 351 if (!ASC->getType()->isVectorTy()) 352 PushPtrOperand(ASC->getPointerOperand()); 353 } 354 } 355 356 std::vector<WeakTrackingVH> Postorder; // The resultant postorder. 357 while (!PostorderStack.empty()) { 358 Value *TopVal = PostorderStack.back().first; 359 // If the operands of the expression on the top are already explored, 360 // adds that expression to the resultant postorder. 361 if (PostorderStack.back().second) { 362 if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace) 363 Postorder.push_back(TopVal); 364 PostorderStack.pop_back(); 365 continue; 366 } 367 // Otherwise, adds its operands to the stack and explores them. 368 PostorderStack.back().second = true; 369 for (Value *PtrOperand : getPointerOperands(*TopVal)) { 370 appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack, 371 Visited); 372 } 373 } 374 return Postorder; 375 } 376 377 // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone 378 // of OperandUse.get() in the new address space. If the clone is not ready yet, 379 // returns an undef in the new address space as a placeholder. 380 static Value *operandWithNewAddressSpaceOrCreateUndef( 381 const Use &OperandUse, unsigned NewAddrSpace, 382 const ValueToValueMapTy &ValueWithNewAddrSpace, 383 SmallVectorImpl<const Use *> *UndefUsesToFix) { 384 Value *Operand = OperandUse.get(); 385 386 Type *NewPtrTy = 387 Operand->getType()->getPointerElementType()->getPointerTo(NewAddrSpace); 388 389 if (Constant *C = dyn_cast<Constant>(Operand)) 390 return ConstantExpr::getAddrSpaceCast(C, NewPtrTy); 391 392 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) 393 return NewOperand; 394 395 UndefUsesToFix->push_back(&OperandUse); 396 return UndefValue::get(NewPtrTy); 397 } 398 399 // Returns a clone of `I` with its operands converted to those specified in 400 // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an 401 // operand whose address space needs to be modified might not exist in 402 // ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and 403 // adds that operand use to UndefUsesToFix so that caller can fix them later. 404 // 405 // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast 406 // from a pointer whose type already matches. Therefore, this function returns a 407 // Value* instead of an Instruction*. 408 static Value *cloneInstructionWithNewAddressSpace( 409 Instruction *I, unsigned NewAddrSpace, 410 const ValueToValueMapTy &ValueWithNewAddrSpace, 411 SmallVectorImpl<const Use *> *UndefUsesToFix) { 412 Type *NewPtrType = 413 I->getType()->getPointerElementType()->getPointerTo(NewAddrSpace); 414 415 if (I->getOpcode() == Instruction::AddrSpaceCast) { 416 Value *Src = I->getOperand(0); 417 // Because `I` is flat, the source address space must be specific. 418 // Therefore, the inferred address space must be the source space, according 419 // to our algorithm. 420 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace); 421 if (Src->getType() != NewPtrType) 422 return new BitCastInst(Src, NewPtrType); 423 return Src; 424 } 425 426 // Computes the converted pointer operands. 427 SmallVector<Value *, 4> NewPointerOperands; 428 for (const Use &OperandUse : I->operands()) { 429 if (!OperandUse.get()->getType()->isPointerTy()) 430 NewPointerOperands.push_back(nullptr); 431 else 432 NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef( 433 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix)); 434 } 435 436 switch (I->getOpcode()) { 437 case Instruction::BitCast: 438 return new BitCastInst(NewPointerOperands[0], NewPtrType); 439 case Instruction::PHI: { 440 assert(I->getType()->isPointerTy()); 441 PHINode *PHI = cast<PHINode>(I); 442 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues()); 443 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) { 444 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index); 445 NewPHI->addIncoming(NewPointerOperands[OperandNo], 446 PHI->getIncomingBlock(Index)); 447 } 448 return NewPHI; 449 } 450 case Instruction::GetElementPtr: { 451 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 452 GetElementPtrInst *NewGEP = GetElementPtrInst::Create( 453 GEP->getSourceElementType(), NewPointerOperands[0], 454 SmallVector<Value *, 4>(GEP->idx_begin(), GEP->idx_end())); 455 NewGEP->setIsInBounds(GEP->isInBounds()); 456 return NewGEP; 457 } 458 case Instruction::Select: { 459 assert(I->getType()->isPointerTy()); 460 return SelectInst::Create(I->getOperand(0), NewPointerOperands[1], 461 NewPointerOperands[2], "", nullptr, I); 462 } 463 default: 464 llvm_unreachable("Unexpected opcode"); 465 } 466 } 467 468 // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the 469 // constant expression `CE` with its operands replaced as specified in 470 // ValueWithNewAddrSpace. 471 static Value *cloneConstantExprWithNewAddressSpace( 472 ConstantExpr *CE, unsigned NewAddrSpace, 473 const ValueToValueMapTy &ValueWithNewAddrSpace) { 474 Type *TargetType = 475 CE->getType()->getPointerElementType()->getPointerTo(NewAddrSpace); 476 477 if (CE->getOpcode() == Instruction::AddrSpaceCast) { 478 // Because CE is flat, the source address space must be specific. 479 // Therefore, the inferred address space must be the source space according 480 // to our algorithm. 481 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() == 482 NewAddrSpace); 483 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType); 484 } 485 486 if (CE->getOpcode() == Instruction::BitCast) { 487 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0))) 488 return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType); 489 return ConstantExpr::getAddrSpaceCast(CE, TargetType); 490 } 491 492 if (CE->getOpcode() == Instruction::Select) { 493 Constant *Src0 = CE->getOperand(1); 494 Constant *Src1 = CE->getOperand(2); 495 if (Src0->getType()->getPointerAddressSpace() == 496 Src1->getType()->getPointerAddressSpace()) { 497 498 return ConstantExpr::getSelect( 499 CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType), 500 ConstantExpr::getAddrSpaceCast(Src1, TargetType)); 501 } 502 } 503 504 // Computes the operands of the new constant expression. 505 bool IsNew = false; 506 SmallVector<Constant *, 4> NewOperands; 507 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) { 508 Constant *Operand = CE->getOperand(Index); 509 // If the address space of `Operand` needs to be modified, the new operand 510 // with the new address space should already be in ValueWithNewAddrSpace 511 // because (1) the constant expressions we consider (i.e. addrspacecast, 512 // bitcast, and getelementptr) do not incur cycles in the data flow graph 513 // and (2) this function is called on constant expressions in postorder. 514 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) { 515 IsNew = true; 516 NewOperands.push_back(cast<Constant>(NewOperand)); 517 } else { 518 // Otherwise, reuses the old operand. 519 NewOperands.push_back(Operand); 520 } 521 } 522 523 // If !IsNew, we will replace the Value with itself. However, replaced values 524 // are assumed to wrapped in a addrspace cast later so drop it now. 525 if (!IsNew) 526 return nullptr; 527 528 if (CE->getOpcode() == Instruction::GetElementPtr) { 529 // Needs to specify the source type while constructing a getelementptr 530 // constant expression. 531 return CE->getWithOperands( 532 NewOperands, TargetType, /*OnlyIfReduced=*/false, 533 NewOperands[0]->getType()->getPointerElementType()); 534 } 535 536 return CE->getWithOperands(NewOperands, TargetType); 537 } 538 539 // Returns a clone of the value `V`, with its operands replaced as specified in 540 // ValueWithNewAddrSpace. This function is called on every flat address 541 // expression whose address space needs to be modified, in postorder. 542 // 543 // See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix. 544 Value *InferAddressSpaces::cloneValueWithNewAddressSpace( 545 Value *V, unsigned NewAddrSpace, 546 const ValueToValueMapTy &ValueWithNewAddrSpace, 547 SmallVectorImpl<const Use *> *UndefUsesToFix) const { 548 // All values in Postorder are flat address expressions. 549 assert(isAddressExpression(*V) && 550 V->getType()->getPointerAddressSpace() == FlatAddrSpace); 551 552 if (Instruction *I = dyn_cast<Instruction>(V)) { 553 Value *NewV = cloneInstructionWithNewAddressSpace( 554 I, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix); 555 if (Instruction *NewI = dyn_cast<Instruction>(NewV)) { 556 if (NewI->getParent() == nullptr) { 557 NewI->insertBefore(I); 558 NewI->takeName(I); 559 } 560 } 561 return NewV; 562 } 563 564 return cloneConstantExprWithNewAddressSpace( 565 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace); 566 } 567 568 // Defines the join operation on the address space lattice (see the file header 569 // comments). 570 unsigned InferAddressSpaces::joinAddressSpaces(unsigned AS1, 571 unsigned AS2) const { 572 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace) 573 return FlatAddrSpace; 574 575 if (AS1 == UninitializedAddressSpace) 576 return AS2; 577 if (AS2 == UninitializedAddressSpace) 578 return AS1; 579 580 // The join of two different specific address spaces is flat. 581 return (AS1 == AS2) ? AS1 : FlatAddrSpace; 582 } 583 584 bool InferAddressSpaces::runOnFunction(Function &F) { 585 if (skipFunction(F)) 586 return false; 587 588 const TargetTransformInfo &TTI = 589 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 590 FlatAddrSpace = TTI.getFlatAddressSpace(); 591 if (FlatAddrSpace == UninitializedAddressSpace) 592 return false; 593 594 // Collects all flat address expressions in postorder. 595 std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F); 596 597 // Runs a data-flow analysis to refine the address spaces of every expression 598 // in Postorder. 599 ValueToAddrSpaceMapTy InferredAddrSpace; 600 inferAddressSpaces(Postorder, &InferredAddrSpace); 601 602 // Changes the address spaces of the flat address expressions who are inferred 603 // to point to a specific address space. 604 return rewriteWithNewAddressSpaces(TTI, Postorder, InferredAddrSpace, &F); 605 } 606 607 // Constants need to be tracked through RAUW to handle cases with nested 608 // constant expressions, so wrap values in WeakTrackingVH. 609 void InferAddressSpaces::inferAddressSpaces( 610 ArrayRef<WeakTrackingVH> Postorder, 611 ValueToAddrSpaceMapTy *InferredAddrSpace) const { 612 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end()); 613 // Initially, all expressions are in the uninitialized address space. 614 for (Value *V : Postorder) 615 (*InferredAddrSpace)[V] = UninitializedAddressSpace; 616 617 while (!Worklist.empty()) { 618 Value *V = Worklist.pop_back_val(); 619 620 // Tries to update the address space of the stack top according to the 621 // address spaces of its operands. 622 DEBUG(dbgs() << "Updating the address space of\n " << *V << '\n'); 623 Optional<unsigned> NewAS = updateAddressSpace(*V, *InferredAddrSpace); 624 if (!NewAS.hasValue()) 625 continue; 626 // If any updates are made, grabs its users to the worklist because 627 // their address spaces can also be possibly updated. 628 DEBUG(dbgs() << " to " << NewAS.getValue() << '\n'); 629 (*InferredAddrSpace)[V] = NewAS.getValue(); 630 631 for (Value *User : V->users()) { 632 // Skip if User is already in the worklist. 633 if (Worklist.count(User)) 634 continue; 635 636 auto Pos = InferredAddrSpace->find(User); 637 // Our algorithm only updates the address spaces of flat address 638 // expressions, which are those in InferredAddrSpace. 639 if (Pos == InferredAddrSpace->end()) 640 continue; 641 642 // Function updateAddressSpace moves the address space down a lattice 643 // path. Therefore, nothing to do if User is already inferred as flat (the 644 // bottom element in the lattice). 645 if (Pos->second == FlatAddrSpace) 646 continue; 647 648 Worklist.insert(User); 649 } 650 } 651 } 652 653 Optional<unsigned> InferAddressSpaces::updateAddressSpace( 654 const Value &V, const ValueToAddrSpaceMapTy &InferredAddrSpace) const { 655 assert(InferredAddrSpace.count(&V)); 656 657 // The new inferred address space equals the join of the address spaces 658 // of all its pointer operands. 659 unsigned NewAS = UninitializedAddressSpace; 660 661 const Operator &Op = cast<Operator>(V); 662 if (Op.getOpcode() == Instruction::Select) { 663 Value *Src0 = Op.getOperand(1); 664 Value *Src1 = Op.getOperand(2); 665 666 auto I = InferredAddrSpace.find(Src0); 667 unsigned Src0AS = (I != InferredAddrSpace.end()) ? 668 I->second : Src0->getType()->getPointerAddressSpace(); 669 670 auto J = InferredAddrSpace.find(Src1); 671 unsigned Src1AS = (J != InferredAddrSpace.end()) ? 672 J->second : Src1->getType()->getPointerAddressSpace(); 673 674 auto *C0 = dyn_cast<Constant>(Src0); 675 auto *C1 = dyn_cast<Constant>(Src1); 676 677 // If one of the inputs is a constant, we may be able to do a constant 678 // addrspacecast of it. Defer inferring the address space until the input 679 // address space is known. 680 if ((C1 && Src0AS == UninitializedAddressSpace) || 681 (C0 && Src1AS == UninitializedAddressSpace)) 682 return None; 683 684 if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS)) 685 NewAS = Src1AS; 686 else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS)) 687 NewAS = Src0AS; 688 else 689 NewAS = joinAddressSpaces(Src0AS, Src1AS); 690 } else { 691 for (Value *PtrOperand : getPointerOperands(V)) { 692 auto I = InferredAddrSpace.find(PtrOperand); 693 unsigned OperandAS = I != InferredAddrSpace.end() ? 694 I->second : PtrOperand->getType()->getPointerAddressSpace(); 695 696 // join(flat, *) = flat. So we can break if NewAS is already flat. 697 NewAS = joinAddressSpaces(NewAS, OperandAS); 698 if (NewAS == FlatAddrSpace) 699 break; 700 } 701 } 702 703 unsigned OldAS = InferredAddrSpace.lookup(&V); 704 assert(OldAS != FlatAddrSpace); 705 if (OldAS == NewAS) 706 return None; 707 return NewAS; 708 } 709 710 /// \p returns true if \p U is the pointer operand of a memory instruction with 711 /// a single pointer operand that can have its address space changed by simply 712 /// mutating the use to a new value. If the memory instruction is volatile, 713 /// return true only if the target allows the memory instruction to be volatile 714 /// in the new address space. 715 static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI, 716 Use &U, unsigned AddrSpace) { 717 User *Inst = U.getUser(); 718 unsigned OpNo = U.getOperandNo(); 719 bool VolatileIsAllowed = false; 720 if (auto *I = dyn_cast<Instruction>(Inst)) 721 VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace); 722 723 if (auto *LI = dyn_cast<LoadInst>(Inst)) 724 return OpNo == LoadInst::getPointerOperandIndex() && 725 (VolatileIsAllowed || !LI->isVolatile()); 726 727 if (auto *SI = dyn_cast<StoreInst>(Inst)) 728 return OpNo == StoreInst::getPointerOperandIndex() && 729 (VolatileIsAllowed || !SI->isVolatile()); 730 731 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst)) 732 return OpNo == AtomicRMWInst::getPointerOperandIndex() && 733 (VolatileIsAllowed || !RMW->isVolatile()); 734 735 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { 736 return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() && 737 (VolatileIsAllowed || !CmpX->isVolatile()); 738 } 739 740 return false; 741 } 742 743 /// Update memory intrinsic uses that require more complex processing than 744 /// simple memory instructions. Thse require re-mangling and may have multiple 745 /// pointer operands. 746 static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV, 747 Value *NewV) { 748 IRBuilder<> B(MI); 749 MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa); 750 MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope); 751 MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias); 752 753 if (auto *MSI = dyn_cast<MemSetInst>(MI)) { 754 B.CreateMemSet(NewV, MSI->getValue(), 755 MSI->getLength(), MSI->getAlignment(), 756 false, // isVolatile 757 TBAA, ScopeMD, NoAliasMD); 758 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) { 759 Value *Src = MTI->getRawSource(); 760 Value *Dest = MTI->getRawDest(); 761 762 // Be careful in case this is a self-to-self copy. 763 if (Src == OldV) 764 Src = NewV; 765 766 if (Dest == OldV) 767 Dest = NewV; 768 769 if (isa<MemCpyInst>(MTI)) { 770 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct); 771 B.CreateMemCpy(Dest, Src, MTI->getLength(), 772 MTI->getAlignment(), 773 false, // isVolatile 774 TBAA, TBAAStruct, ScopeMD, NoAliasMD); 775 } else { 776 assert(isa<MemMoveInst>(MTI)); 777 B.CreateMemMove(Dest, Src, MTI->getLength(), 778 MTI->getAlignment(), 779 false, // isVolatile 780 TBAA, ScopeMD, NoAliasMD); 781 } 782 } else 783 llvm_unreachable("unhandled MemIntrinsic"); 784 785 MI->eraseFromParent(); 786 return true; 787 } 788 789 // \p returns true if it is OK to change the address space of constant \p C with 790 // a ConstantExpr addrspacecast. 791 bool InferAddressSpaces::isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const { 792 assert(NewAS != UninitializedAddressSpace); 793 794 unsigned SrcAS = C->getType()->getPointerAddressSpace(); 795 if (SrcAS == NewAS || isa<UndefValue>(C)) 796 return true; 797 798 // Prevent illegal casts between different non-flat address spaces. 799 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace) 800 return false; 801 802 if (isa<ConstantPointerNull>(C)) 803 return true; 804 805 if (auto *Op = dyn_cast<Operator>(C)) { 806 // If we already have a constant addrspacecast, it should be safe to cast it 807 // off. 808 if (Op->getOpcode() == Instruction::AddrSpaceCast) 809 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS); 810 811 if (Op->getOpcode() == Instruction::IntToPtr && 812 Op->getType()->getPointerAddressSpace() == FlatAddrSpace) 813 return true; 814 } 815 816 return false; 817 } 818 819 static Value::use_iterator skipToNextUser(Value::use_iterator I, 820 Value::use_iterator End) { 821 User *CurUser = I->getUser(); 822 ++I; 823 824 while (I != End && I->getUser() == CurUser) 825 ++I; 826 827 return I; 828 } 829 830 bool InferAddressSpaces::rewriteWithNewAddressSpaces( 831 const TargetTransformInfo &TTI, ArrayRef<WeakTrackingVH> Postorder, 832 const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const { 833 // For each address expression to be modified, creates a clone of it with its 834 // pointer operands converted to the new address space. Since the pointer 835 // operands are converted, the clone is naturally in the new address space by 836 // construction. 837 ValueToValueMapTy ValueWithNewAddrSpace; 838 SmallVector<const Use *, 32> UndefUsesToFix; 839 for (Value* V : Postorder) { 840 unsigned NewAddrSpace = InferredAddrSpace.lookup(V); 841 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) { 842 ValueWithNewAddrSpace[V] = cloneValueWithNewAddressSpace( 843 V, NewAddrSpace, ValueWithNewAddrSpace, &UndefUsesToFix); 844 } 845 } 846 847 if (ValueWithNewAddrSpace.empty()) 848 return false; 849 850 // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace. 851 for (const Use *UndefUse : UndefUsesToFix) { 852 User *V = UndefUse->getUser(); 853 User *NewV = cast<User>(ValueWithNewAddrSpace.lookup(V)); 854 unsigned OperandNo = UndefUse->getOperandNo(); 855 assert(isa<UndefValue>(NewV->getOperand(OperandNo))); 856 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get())); 857 } 858 859 SmallVector<Instruction *, 16> DeadInstructions; 860 861 // Replaces the uses of the old address expressions with the new ones. 862 for (const WeakTrackingVH &WVH : Postorder) { 863 assert(WVH && "value was unexpectedly deleted"); 864 Value *V = WVH; 865 Value *NewV = ValueWithNewAddrSpace.lookup(V); 866 if (NewV == nullptr) 867 continue; 868 869 DEBUG(dbgs() << "Replacing the uses of " << *V 870 << "\n with\n " << *NewV << '\n'); 871 872 if (Constant *C = dyn_cast<Constant>(V)) { 873 Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV), 874 C->getType()); 875 if (C != Replace) { 876 DEBUG(dbgs() << "Inserting replacement const cast: " 877 << Replace << ": " << *Replace << '\n'); 878 C->replaceAllUsesWith(Replace); 879 V = Replace; 880 } 881 } 882 883 Value::use_iterator I, E, Next; 884 for (I = V->use_begin(), E = V->use_end(); I != E; ) { 885 Use &U = *I; 886 887 // Some users may see the same pointer operand in multiple operands. Skip 888 // to the next instruction. 889 I = skipToNextUser(I, E); 890 891 if (isSimplePointerUseValidToReplace( 892 TTI, U, V->getType()->getPointerAddressSpace())) { 893 // If V is used as the pointer operand of a compatible memory operation, 894 // sets the pointer operand to NewV. This replacement does not change 895 // the element type, so the resultant load/store is still valid. 896 U.set(NewV); 897 continue; 898 } 899 900 User *CurUser = U.getUser(); 901 // Handle more complex cases like intrinsic that need to be remangled. 902 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) { 903 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV)) 904 continue; 905 } 906 907 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) { 908 if (rewriteIntrinsicOperands(II, V, NewV)) 909 continue; 910 } 911 912 if (isa<Instruction>(CurUser)) { 913 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) { 914 // If we can infer that both pointers are in the same addrspace, 915 // transform e.g. 916 // %cmp = icmp eq float* %p, %q 917 // into 918 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q 919 920 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 921 int SrcIdx = U.getOperandNo(); 922 int OtherIdx = (SrcIdx == 0) ? 1 : 0; 923 Value *OtherSrc = Cmp->getOperand(OtherIdx); 924 925 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) { 926 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) { 927 Cmp->setOperand(OtherIdx, OtherNewV); 928 Cmp->setOperand(SrcIdx, NewV); 929 continue; 930 } 931 } 932 933 // Even if the type mismatches, we can cast the constant. 934 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) { 935 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) { 936 Cmp->setOperand(SrcIdx, NewV); 937 Cmp->setOperand(OtherIdx, 938 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType())); 939 continue; 940 } 941 } 942 } 943 944 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) { 945 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 946 if (ASC->getDestAddressSpace() == NewAS) { 947 ASC->replaceAllUsesWith(NewV); 948 DeadInstructions.push_back(ASC); 949 continue; 950 } 951 } 952 953 // Otherwise, replaces the use with flat(NewV). 954 if (Instruction *I = dyn_cast<Instruction>(V)) { 955 BasicBlock::iterator InsertPos = std::next(I->getIterator()); 956 while (isa<PHINode>(InsertPos)) 957 ++InsertPos; 958 U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos)); 959 } else { 960 U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV), 961 V->getType())); 962 } 963 } 964 } 965 966 if (V->use_empty()) { 967 if (Instruction *I = dyn_cast<Instruction>(V)) 968 DeadInstructions.push_back(I); 969 } 970 } 971 972 for (Instruction *I : DeadInstructions) 973 RecursivelyDeleteTriviallyDeadInstructions(I); 974 975 return true; 976 } 977 978 FunctionPass *llvm::createInferAddressSpacesPass() { 979 return new InferAddressSpaces(); 980 } 981