InferAddressSpaces.cpp 51 KB

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