LLVM 17.0.0git
InferAddressSpaces.cpp
Go to the documentation of this file.
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
92#include "llvm/ADT/ArrayRef.h"
93#include "llvm/ADT/DenseMap.h"
94#include "llvm/ADT/DenseSet.h"
95#include "llvm/ADT/SetVector.h"
100#include "llvm/IR/BasicBlock.h"
101#include "llvm/IR/Constant.h"
102#include "llvm/IR/Constants.h"
103#include "llvm/IR/Dominators.h"
104#include "llvm/IR/Function.h"
105#include "llvm/IR/IRBuilder.h"
106#include "llvm/IR/InstIterator.h"
107#include "llvm/IR/Instruction.h"
108#include "llvm/IR/Instructions.h"
110#include "llvm/IR/Intrinsics.h"
111#include "llvm/IR/LLVMContext.h"
112#include "llvm/IR/Operator.h"
113#include "llvm/IR/PassManager.h"
114#include "llvm/IR/Type.h"
115#include "llvm/IR/Use.h"
116#include "llvm/IR/User.h"
117#include "llvm/IR/Value.h"
118#include "llvm/IR/ValueHandle.h"
120#include "llvm/Pass.h"
121#include "llvm/Support/Casting.h"
124#include "llvm/Support/Debug.h"
130#include <cassert>
131#include <iterator>
132#include <limits>
133#include <utility>
134#include <vector>
135
136#define DEBUG_TYPE "infer-address-spaces"
137
138using namespace llvm;
139
141 "assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden,
142 cl::desc("The default address space is assumed as the flat address space. "
143 "This is mainly for test purpose."));
144
145static const unsigned UninitializedAddressSpace =
146 std::numeric_limits<unsigned>::max();
147
148namespace {
149
150using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
151// Different from ValueToAddrSpaceMapTy, where a new addrspace is inferred on
152// the *def* of a value, PredicatedAddrSpaceMapTy is map where a new
153// addrspace is inferred on the *use* of a pointer. This map is introduced to
154// infer addrspace from the addrspace predicate assumption built from assume
155// intrinsic. In that scenario, only specific uses (under valid assumption
156// context) could be inferred with a new addrspace.
157using PredicatedAddrSpaceMapTy =
159using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>;
160
161class InferAddressSpaces : public FunctionPass {
162 unsigned FlatAddrSpace = 0;
163
164public:
165 static char ID;
166
167 InferAddressSpaces() :
168 FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {}
169 InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {}
170
171 void getAnalysisUsage(AnalysisUsage &AU) const override {
172 AU.setPreservesCFG();
176 }
177
178 bool runOnFunction(Function &F) override;
179};
180
181class InferAddressSpacesImpl {
182 AssumptionCache &AC;
183 const DominatorTree *DT = nullptr;
184 const TargetTransformInfo *TTI = nullptr;
185 const DataLayout *DL = nullptr;
186
187 /// Target specific address space which uses of should be replaced if
188 /// possible.
189 unsigned FlatAddrSpace = 0;
190
191 // Try to update the address space of V. If V is updated, returns true and
192 // false otherwise.
193 bool updateAddressSpace(const Value &V,
194 ValueToAddrSpaceMapTy &InferredAddrSpace,
195 PredicatedAddrSpaceMapTy &PredicatedAS) const;
196
197 // Tries to infer the specific address space of each address expression in
198 // Postorder.
199 void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
200 ValueToAddrSpaceMapTy &InferredAddrSpace,
201 PredicatedAddrSpaceMapTy &PredicatedAS) const;
202
203 bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
204
205 Value *cloneInstructionWithNewAddressSpace(
206 Instruction *I, unsigned NewAddrSpace,
207 const ValueToValueMapTy &ValueWithNewAddrSpace,
208 const PredicatedAddrSpaceMapTy &PredicatedAS,
209 SmallVectorImpl<const Use *> *UndefUsesToFix) const;
210
211 // Changes the flat address expressions in function F to point to specific
212 // address spaces if InferredAddrSpace says so. Postorder is the postorder of
213 // all flat expressions in the use-def graph of function F.
214 bool
215 rewriteWithNewAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
216 const ValueToAddrSpaceMapTy &InferredAddrSpace,
217 const PredicatedAddrSpaceMapTy &PredicatedAS,
218 Function *F) const;
219
220 void appendsFlatAddressExpressionToPostorderStack(
221 Value *V, PostorderStackTy &PostorderStack,
222 DenseSet<Value *> &Visited) const;
223
224 bool rewriteIntrinsicOperands(IntrinsicInst *II,
225 Value *OldV, Value *NewV) const;
226 void collectRewritableIntrinsicOperands(IntrinsicInst *II,
227 PostorderStackTy &PostorderStack,
228 DenseSet<Value *> &Visited) const;
229
230 std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const;
231
232 Value *cloneValueWithNewAddressSpace(
233 Value *V, unsigned NewAddrSpace,
234 const ValueToValueMapTy &ValueWithNewAddrSpace,
235 const PredicatedAddrSpaceMapTy &PredicatedAS,
236 SmallVectorImpl<const Use *> *UndefUsesToFix) const;
237 unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
238
239 unsigned getPredicatedAddrSpace(const Value &V, Value *Opnd) const;
240
241public:
242 InferAddressSpacesImpl(AssumptionCache &AC, const DominatorTree *DT,
243 const TargetTransformInfo *TTI, unsigned FlatAddrSpace)
244 : AC(AC), DT(DT), TTI(TTI), FlatAddrSpace(FlatAddrSpace) {}
245 bool run(Function &F);
246};
247
248} // end anonymous namespace
249
250char InferAddressSpaces::ID = 0;
251
252INITIALIZE_PASS_BEGIN(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
253 false, false)
256INITIALIZE_PASS_END(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
258
259// Check whether that's no-op pointer bicast using a pair of
260// `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over
261// different address spaces.
264 assert(I2P->getOpcode() == Instruction::IntToPtr);
265 auto *P2I = dyn_cast<Operator>(I2P->getOperand(0));
266 if (!P2I || P2I->getOpcode() != Instruction::PtrToInt)
267 return false;
268 // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a
269 // no-op cast. Besides checking both of them are no-op casts, as the
270 // reinterpreted pointer may be used in other pointer arithmetic, we also
271 // need to double-check that through the target-specific hook. That ensures
272 // the underlying target also agrees that's a no-op address space cast and
273 // pointer bits are preserved.
274 // The current IR spec doesn't have clear rules on address space casts,
275 // especially a clear definition for pointer bits in non-default address
276 // spaces. It would be undefined if that pointer is dereferenced after an
277 // invalid reinterpret cast. Also, due to the unclearness for the meaning of
278 // bits in non-default address spaces in the current spec, the pointer
279 // arithmetic may also be undefined after invalid pointer reinterpret cast.
280 // However, as we confirm through the target hooks that it's a no-op
281 // addrspacecast, it doesn't matter since the bits should be the same.
282 unsigned P2IOp0AS = P2I->getOperand(0)->getType()->getPointerAddressSpace();
283 unsigned I2PAS = I2P->getType()->getPointerAddressSpace();
284 return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()),
285 I2P->getOperand(0)->getType(), I2P->getType(),
286 DL) &&
288 P2I->getOperand(0)->getType(), P2I->getType(),
289 DL) &&
290 (P2IOp0AS == I2PAS || TTI->isNoopAddrSpaceCast(P2IOp0AS, I2PAS));
291}
292
293// Returns true if V is an address expression.
294// TODO: Currently, we consider only phi, bitcast, addrspacecast, and
295// getelementptr operators.
296static bool isAddressExpression(const Value &V, const DataLayout &DL,
297 const TargetTransformInfo *TTI) {
298 const Operator *Op = dyn_cast<Operator>(&V);
299 if (!Op)
300 return false;
301
302 switch (Op->getOpcode()) {
303 case Instruction::PHI:
304 assert(Op->getType()->isPointerTy());
305 return true;
306 case Instruction::BitCast:
307 case Instruction::AddrSpaceCast:
308 case Instruction::GetElementPtr:
309 return true;
310 case Instruction::Select:
311 return Op->getType()->isPointerTy();
312 case Instruction::Call: {
313 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V);
314 return II && II->getIntrinsicID() == Intrinsic::ptrmask;
315 }
316 case Instruction::IntToPtr:
317 return isNoopPtrIntCastPair(Op, DL, TTI);
318 default:
319 // That value is an address expression if it has an assumed address space.
321 }
322}
323
324// Returns the pointer operands of V.
325//
326// Precondition: V is an address expression.
329 const TargetTransformInfo *TTI) {
330 const Operator &Op = cast<Operator>(V);
331 switch (Op.getOpcode()) {
332 case Instruction::PHI: {
333 auto IncomingValues = cast<PHINode>(Op).incoming_values();
334 return {IncomingValues.begin(), IncomingValues.end()};
335 }
336 case Instruction::BitCast:
337 case Instruction::AddrSpaceCast:
338 case Instruction::GetElementPtr:
339 return {Op.getOperand(0)};
340 case Instruction::Select:
341 return {Op.getOperand(1), Op.getOperand(2)};
342 case Instruction::Call: {
343 const IntrinsicInst &II = cast<IntrinsicInst>(Op);
344 assert(II.getIntrinsicID() == Intrinsic::ptrmask &&
345 "unexpected intrinsic call");
346 return {II.getArgOperand(0)};
347 }
348 case Instruction::IntToPtr: {
350 auto *P2I = cast<Operator>(Op.getOperand(0));
351 return {P2I->getOperand(0)};
352 }
353 default:
354 llvm_unreachable("Unexpected instruction type.");
355 }
356}
357
358bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II,
359 Value *OldV,
360 Value *NewV) const {
361 Module *M = II->getParent()->getParent()->getParent();
362
363 switch (II->getIntrinsicID()) {
364 case Intrinsic::objectsize: {
365 Type *DestTy = II->getType();
366 Type *SrcTy = NewV->getType();
367 Function *NewDecl =
368 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
369 II->setArgOperand(0, NewV);
370 II->setCalledFunction(NewDecl);
371 return true;
372 }
373 case Intrinsic::ptrmask:
374 // This is handled as an address expression, not as a use memory operation.
375 return false;
376 default: {
377 Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
378 if (!Rewrite)
379 return false;
380 if (Rewrite != II)
381 II->replaceAllUsesWith(Rewrite);
382 return true;
383 }
384 }
385}
386
387void InferAddressSpacesImpl::collectRewritableIntrinsicOperands(
388 IntrinsicInst *II, PostorderStackTy &PostorderStack,
389 DenseSet<Value *> &Visited) const {
390 auto IID = II->getIntrinsicID();
391 switch (IID) {
392 case Intrinsic::ptrmask:
393 case Intrinsic::objectsize:
394 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
395 PostorderStack, Visited);
396 break;
397 default:
398 SmallVector<int, 2> OpIndexes;
399 if (TTI->collectFlatAddressOperands(OpIndexes, IID)) {
400 for (int Idx : OpIndexes) {
401 appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx),
402 PostorderStack, Visited);
403 }
404 }
405 break;
406 }
407}
408
409// Returns all flat address expressions in function F. The elements are
410// If V is an unvisited flat address expression, appends V to PostorderStack
411// and marks it as visited.
412void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack(
413 Value *V, PostorderStackTy &PostorderStack,
414 DenseSet<Value *> &Visited) const {
415 assert(V->getType()->isPointerTy());
416
417 // Generic addressing expressions may be hidden in nested constant
418 // expressions.
419 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
420 // TODO: Look in non-address parts, like icmp operands.
421 if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
422 PostorderStack.emplace_back(CE, false);
423
424 return;
425 }
426
427 if (V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
428 isAddressExpression(*V, *DL, TTI)) {
429 if (Visited.insert(V).second) {
430 PostorderStack.emplace_back(V, false);
431
432 Operator *Op = cast<Operator>(V);
433 for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) {
434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) {
435 if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
436 PostorderStack.emplace_back(CE, false);
437 }
438 }
439 }
440 }
441}
442
443// Returns all flat address expressions in function F. The elements are ordered
444// ordered in postorder.
445std::vector<WeakTrackingVH>
446InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const {
447 // This function implements a non-recursive postorder traversal of a partial
448 // use-def graph of function F.
449 PostorderStackTy PostorderStack;
450 // The set of visited expressions.
451 DenseSet<Value *> Visited;
452
453 auto PushPtrOperand = [&](Value *Ptr) {
454 appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
455 Visited);
456 };
457
458 // Look at operations that may be interesting accelerate by moving to a known
459 // address space. We aim at generating after loads and stores, but pure
460 // addressing calculations may also be faster.
461 for (Instruction &I : instructions(F)) {
462 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
463 if (!GEP->getType()->isVectorTy())
464 PushPtrOperand(GEP->getPointerOperand());
465 } else if (auto *LI = dyn_cast<LoadInst>(&I))
466 PushPtrOperand(LI->getPointerOperand());
467 else if (auto *SI = dyn_cast<StoreInst>(&I))
468 PushPtrOperand(SI->getPointerOperand());
469 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
470 PushPtrOperand(RMW->getPointerOperand());
471 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
472 PushPtrOperand(CmpX->getPointerOperand());
473 else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
474 // For memset/memcpy/memmove, any pointer operand can be replaced.
475 PushPtrOperand(MI->getRawDest());
476
477 // Handle 2nd operand for memcpy/memmove.
478 if (auto *MTI = dyn_cast<MemTransferInst>(MI))
479 PushPtrOperand(MTI->getRawSource());
480 } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
481 collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
482 else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
483 // FIXME: Handle vectors of pointers
484 if (Cmp->getOperand(0)->getType()->isPointerTy()) {
485 PushPtrOperand(Cmp->getOperand(0));
486 PushPtrOperand(Cmp->getOperand(1));
487 }
488 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
489 if (!ASC->getType()->isVectorTy())
490 PushPtrOperand(ASC->getPointerOperand());
491 } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) {
492 if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI))
493 PushPtrOperand(
494 cast<Operator>(I2P->getOperand(0))->getOperand(0));
495 }
496 }
497
498 std::vector<WeakTrackingVH> Postorder; // The resultant postorder.
499 while (!PostorderStack.empty()) {
500 Value *TopVal = PostorderStack.back().getPointer();
501 // If the operands of the expression on the top are already explored,
502 // adds that expression to the resultant postorder.
503 if (PostorderStack.back().getInt()) {
504 if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
505 Postorder.push_back(TopVal);
506 PostorderStack.pop_back();
507 continue;
508 }
509 // Otherwise, adds its operands to the stack and explores them.
510 PostorderStack.back().setInt(true);
511 // Skip values with an assumed address space.
513 for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) {
514 appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
515 Visited);
516 }
517 }
518 }
519 return Postorder;
520}
521
522// A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
523// of OperandUse.get() in the new address space. If the clone is not ready yet,
524// returns an undef in the new address space as a placeholder.
526 const Use &OperandUse, unsigned NewAddrSpace,
527 const ValueToValueMapTy &ValueWithNewAddrSpace,
528 const PredicatedAddrSpaceMapTy &PredicatedAS,
529 SmallVectorImpl<const Use *> *UndefUsesToFix) {
530 Value *Operand = OperandUse.get();
531
532 Type *NewPtrTy = PointerType::getWithSamePointeeType(
533 cast<PointerType>(Operand->getType()), NewAddrSpace);
534
535 if (Constant *C = dyn_cast<Constant>(Operand))
536 return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
537
538 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
539 return NewOperand;
540
541 Instruction *Inst = cast<Instruction>(OperandUse.getUser());
542 auto I = PredicatedAS.find(std::make_pair(Inst, Operand));
543 if (I != PredicatedAS.end()) {
544 // Insert an addrspacecast on that operand before the user.
545 unsigned NewAS = I->second;
546 Type *NewPtrTy = PointerType::getWithSamePointeeType(
547 cast<PointerType>(Operand->getType()), NewAS);
548 auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy);
549 NewI->insertBefore(Inst);
550 NewI->setDebugLoc(Inst->getDebugLoc());
551 return NewI;
552 }
553
554 UndefUsesToFix->push_back(&OperandUse);
555 return UndefValue::get(NewPtrTy);
556}
557
558// Returns a clone of `I` with its operands converted to those specified in
559// ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
560// operand whose address space needs to be modified might not exist in
561// ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
562// adds that operand use to UndefUsesToFix so that caller can fix them later.
563//
564// Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
565// from a pointer whose type already matches. Therefore, this function returns a
566// Value* instead of an Instruction*.
567//
568// This may also return nullptr in the case the instruction could not be
569// rewritten.
570Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace(
571 Instruction *I, unsigned NewAddrSpace,
572 const ValueToValueMapTy &ValueWithNewAddrSpace,
573 const PredicatedAddrSpaceMapTy &PredicatedAS,
574 SmallVectorImpl<const Use *> *UndefUsesToFix) const {
575 Type *NewPtrType = PointerType::getWithSamePointeeType(
576 cast<PointerType>(I->getType()), NewAddrSpace);
577
578 if (I->getOpcode() == Instruction::AddrSpaceCast) {
579 Value *Src = I->getOperand(0);
580 // Because `I` is flat, the source address space must be specific.
581 // Therefore, the inferred address space must be the source space, according
582 // to our algorithm.
583 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
584 if (Src->getType() != NewPtrType)
585 return new BitCastInst(Src, NewPtrType);
586 return Src;
587 }
588
589 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
590 // Technically the intrinsic ID is a pointer typed argument, so specially
591 // handle calls early.
592 assert(II->getIntrinsicID() == Intrinsic::ptrmask);
594 II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace,
595 PredicatedAS, UndefUsesToFix);
596 Value *Rewrite =
598 if (Rewrite) {
599 assert(Rewrite != II && "cannot modify this pointer operation in place");
600 return Rewrite;
601 }
602
603 return nullptr;
604 }
605
606 unsigned AS = TTI->getAssumedAddrSpace(I);
607 if (AS != UninitializedAddressSpace) {
608 // For the assumed address space, insert an `addrspacecast` to make that
609 // explicit.
610 Type *NewPtrTy = PointerType::getWithSamePointeeType(
611 cast<PointerType>(I->getType()), AS);
612 auto *NewI = new AddrSpaceCastInst(I, NewPtrTy);
613 NewI->insertAfter(I);
614 return NewI;
615 }
616
617 // Computes the converted pointer operands.
618 SmallVector<Value *, 4> NewPointerOperands;
619 for (const Use &OperandUse : I->operands()) {
620 if (!OperandUse.get()->getType()->isPointerTy())
621 NewPointerOperands.push_back(nullptr);
622 else
624 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS,
625 UndefUsesToFix));
626 }
627
628 switch (I->getOpcode()) {
629 case Instruction::BitCast:
630 return new BitCastInst(NewPointerOperands[0], NewPtrType);
631 case Instruction::PHI: {
632 assert(I->getType()->isPointerTy());
633 PHINode *PHI = cast<PHINode>(I);
634 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
635 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
636 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
637 NewPHI->addIncoming(NewPointerOperands[OperandNo],
638 PHI->getIncomingBlock(Index));
639 }
640 return NewPHI;
641 }
642 case Instruction::GetElementPtr: {
643 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
645 GEP->getSourceElementType(), NewPointerOperands[0],
646 SmallVector<Value *, 4>(GEP->indices()));
647 NewGEP->setIsInBounds(GEP->isInBounds());
648 return NewGEP;
649 }
650 case Instruction::Select:
651 assert(I->getType()->isPointerTy());
652 return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
653 NewPointerOperands[2], "", nullptr, I);
654 case Instruction::IntToPtr: {
655 assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI));
656 Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0);
657 if (Src->getType() == NewPtrType)
658 return Src;
659
660 // If we had a no-op inttoptr/ptrtoint pair, we may still have inferred a
661 // source address space from a generic pointer source need to insert a cast
662 // back.
663 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Src, NewPtrType);
664 }
665 default:
666 llvm_unreachable("Unexpected opcode");
667 }
668}
669
670// Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
671// constant expression `CE` with its operands replaced as specified in
672// ValueWithNewAddrSpace.
674 ConstantExpr *CE, unsigned NewAddrSpace,
675 const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
676 const TargetTransformInfo *TTI) {
677 Type *TargetType = CE->getType()->isPointerTy()
678 ? PointerType::getWithSamePointeeType(
679 cast<PointerType>(CE->getType()), NewAddrSpace)
680 : CE->getType();
681
682 if (CE->getOpcode() == Instruction::AddrSpaceCast) {
683 // Because CE is flat, the source address space must be specific.
684 // Therefore, the inferred address space must be the source space according
685 // to our algorithm.
686 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
687 NewAddrSpace);
688 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
689 }
690
691 if (CE->getOpcode() == Instruction::BitCast) {
692 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
693 return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
694 return ConstantExpr::getAddrSpaceCast(CE, TargetType);
695 }
696
697 if (CE->getOpcode() == Instruction::IntToPtr) {
698 assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI));
699 Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0);
700 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
701 return ConstantExpr::getBitCast(Src, TargetType);
702 }
703
704 // Computes the operands of the new constant expression.
705 bool IsNew = false;
706 SmallVector<Constant *, 4> NewOperands;
707 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
708 Constant *Operand = CE->getOperand(Index);
709 // If the address space of `Operand` needs to be modified, the new operand
710 // with the new address space should already be in ValueWithNewAddrSpace
711 // because (1) the constant expressions we consider (i.e. addrspacecast,
712 // bitcast, and getelementptr) do not incur cycles in the data flow graph
713 // and (2) this function is called on constant expressions in postorder.
714 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
715 IsNew = true;
716 NewOperands.push_back(cast<Constant>(NewOperand));
717 continue;
718 }
719 if (auto *CExpr = dyn_cast<ConstantExpr>(Operand))
721 CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) {
722 IsNew = true;
723 NewOperands.push_back(cast<Constant>(NewOperand));
724 continue;
725 }
726 // Otherwise, reuses the old operand.
727 NewOperands.push_back(Operand);
728 }
729
730 // If !IsNew, we will replace the Value with itself. However, replaced values
731 // are assumed to wrapped in an addrspacecast cast later so drop it now.
732 if (!IsNew)
733 return nullptr;
734
735 if (CE->getOpcode() == Instruction::GetElementPtr) {
736 // Needs to specify the source type while constructing a getelementptr
737 // constant expression.
738 return CE->getWithOperands(NewOperands, TargetType, /*OnlyIfReduced=*/false,
739 cast<GEPOperator>(CE)->getSourceElementType());
740 }
741
742 return CE->getWithOperands(NewOperands, TargetType);
743}
744
745// Returns a clone of the value `V`, with its operands replaced as specified in
746// ValueWithNewAddrSpace. This function is called on every flat address
747// expression whose address space needs to be modified, in postorder.
748//
749// See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
750Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace(
751 Value *V, unsigned NewAddrSpace,
752 const ValueToValueMapTy &ValueWithNewAddrSpace,
753 const PredicatedAddrSpaceMapTy &PredicatedAS,
754 SmallVectorImpl<const Use *> *UndefUsesToFix) const {
755 // All values in Postorder are flat address expressions.
756 assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
757 isAddressExpression(*V, *DL, TTI));
758
759 if (Instruction *I = dyn_cast<Instruction>(V)) {
760 Value *NewV = cloneInstructionWithNewAddressSpace(
761 I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, UndefUsesToFix);
762 if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
763 if (NewI->getParent() == nullptr) {
764 NewI->insertBefore(I);
765 NewI->takeName(I);
766 NewI->setDebugLoc(I->getDebugLoc());
767 }
768 }
769 return NewV;
770 }
771
773 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI);
774}
775
776// Defines the join operation on the address space lattice (see the file header
777// comments).
778unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1,
779 unsigned AS2) const {
780 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
781 return FlatAddrSpace;
782
783 if (AS1 == UninitializedAddressSpace)
784 return AS2;
785 if (AS2 == UninitializedAddressSpace)
786 return AS1;
787
788 // The join of two different specific address spaces is flat.
789 return (AS1 == AS2) ? AS1 : FlatAddrSpace;
790}
791
792bool InferAddressSpacesImpl::run(Function &F) {
793 DL = &F.getParent()->getDataLayout();
794
796 FlatAddrSpace = 0;
797
798 if (FlatAddrSpace == UninitializedAddressSpace) {
799 FlatAddrSpace = TTI->getFlatAddressSpace();
800 if (FlatAddrSpace == UninitializedAddressSpace)
801 return false;
802 }
803
804 // Collects all flat address expressions in postorder.
805 std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
806
807 // Runs a data-flow analysis to refine the address spaces of every expression
808 // in Postorder.
809 ValueToAddrSpaceMapTy InferredAddrSpace;
810 PredicatedAddrSpaceMapTy PredicatedAS;
811 inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS);
812
813 // Changes the address spaces of the flat address expressions who are inferred
814 // to point to a specific address space.
815 return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS,
816 &F);
817}
818
819// Constants need to be tracked through RAUW to handle cases with nested
820// constant expressions, so wrap values in WeakTrackingVH.
821void InferAddressSpacesImpl::inferAddressSpaces(
822 ArrayRef<WeakTrackingVH> Postorder,
823 ValueToAddrSpaceMapTy &InferredAddrSpace,
824 PredicatedAddrSpaceMapTy &PredicatedAS) const {
825 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
826 // Initially, all expressions are in the uninitialized address space.
827 for (Value *V : Postorder)
828 InferredAddrSpace[V] = UninitializedAddressSpace;
829
830 while (!Worklist.empty()) {
831 Value *V = Worklist.pop_back_val();
832
833 // Try to update the address space of the stack top according to the
834 // address spaces of its operands.
835 if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS))
836 continue;
837
838 for (Value *User : V->users()) {
839 // Skip if User is already in the worklist.
840 if (Worklist.count(User))
841 continue;
842
843 auto Pos = InferredAddrSpace.find(User);
844 // Our algorithm only updates the address spaces of flat address
845 // expressions, which are those in InferredAddrSpace.
846 if (Pos == InferredAddrSpace.end())
847 continue;
848
849 // Function updateAddressSpace moves the address space down a lattice
850 // path. Therefore, nothing to do if User is already inferred as flat (the
851 // bottom element in the lattice).
852 if (Pos->second == FlatAddrSpace)
853 continue;
854
855 Worklist.insert(User);
856 }
857 }
858}
859
860unsigned InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &V,
861 Value *Opnd) const {
862 const Instruction *I = dyn_cast<Instruction>(&V);
863 if (!I)
865
866 Opnd = Opnd->stripInBoundsOffsets();
867 for (auto &AssumeVH : AC.assumptionsFor(Opnd)) {
868 if (!AssumeVH)
869 continue;
870 CallInst *CI = cast<CallInst>(AssumeVH);
871 if (!isValidAssumeForContext(CI, I, DT))
872 continue;
873
874 const Value *Ptr;
875 unsigned AS;
876 std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0));
877 if (Ptr)
878 return AS;
879 }
880
882}
883
884bool InferAddressSpacesImpl::updateAddressSpace(
885 const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace,
886 PredicatedAddrSpaceMapTy &PredicatedAS) const {
887 assert(InferredAddrSpace.count(&V));
888
889 LLVM_DEBUG(dbgs() << "Updating the address space of\n " << V << '\n');
890
891 // The new inferred address space equals the join of the address spaces
892 // of all its pointer operands.
893 unsigned NewAS = UninitializedAddressSpace;
894
895 const Operator &Op = cast<Operator>(V);
896 if (Op.getOpcode() == Instruction::Select) {
897 Value *Src0 = Op.getOperand(1);
898 Value *Src1 = Op.getOperand(2);
899
900 auto I = InferredAddrSpace.find(Src0);
901 unsigned Src0AS = (I != InferredAddrSpace.end()) ?
902 I->second : Src0->getType()->getPointerAddressSpace();
903
904 auto J = InferredAddrSpace.find(Src1);
905 unsigned Src1AS = (J != InferredAddrSpace.end()) ?
906 J->second : Src1->getType()->getPointerAddressSpace();
907
908 auto *C0 = dyn_cast<Constant>(Src0);
909 auto *C1 = dyn_cast<Constant>(Src1);
910
911 // If one of the inputs is a constant, we may be able to do a constant
912 // addrspacecast of it. Defer inferring the address space until the input
913 // address space is known.
914 if ((C1 && Src0AS == UninitializedAddressSpace) ||
915 (C0 && Src1AS == UninitializedAddressSpace))
916 return false;
917
918 if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
919 NewAS = Src1AS;
920 else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
921 NewAS = Src0AS;
922 else
923 NewAS = joinAddressSpaces(Src0AS, Src1AS);
924 } else {
925 unsigned AS = TTI->getAssumedAddrSpace(&V);
926 if (AS != UninitializedAddressSpace) {
927 // Use the assumed address space directly.
928 NewAS = AS;
929 } else {
930 // Otherwise, infer the address space from its pointer operands.
931 for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) {
932 auto I = InferredAddrSpace.find(PtrOperand);
933 unsigned OperandAS;
934 if (I == InferredAddrSpace.end()) {
935 OperandAS = PtrOperand->getType()->getPointerAddressSpace();
936 if (OperandAS == FlatAddrSpace) {
937 // Check AC for assumption dominating V.
938 unsigned AS = getPredicatedAddrSpace(V, PtrOperand);
939 if (AS != UninitializedAddressSpace) {
941 << " deduce operand AS from the predicate addrspace "
942 << AS << '\n');
943 OperandAS = AS;
944 // Record this use with the predicated AS.
945 PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS;
946 }
947 }
948 } else
949 OperandAS = I->second;
950
951 // join(flat, *) = flat. So we can break if NewAS is already flat.
952 NewAS = joinAddressSpaces(NewAS, OperandAS);
953 if (NewAS == FlatAddrSpace)
954 break;
955 }
956 }
957 }
958
959 unsigned OldAS = InferredAddrSpace.lookup(&V);
960 assert(OldAS != FlatAddrSpace);
961 if (OldAS == NewAS)
962 return false;
963
964 // If any updates are made, grabs its users to the worklist because
965 // their address spaces can also be possibly updated.
966 LLVM_DEBUG(dbgs() << " to " << NewAS << '\n');
967 InferredAddrSpace[&V] = NewAS;
968 return true;
969}
970
971/// \p returns true if \p U is the pointer operand of a memory instruction with
972/// a single pointer operand that can have its address space changed by simply
973/// mutating the use to a new value. If the memory instruction is volatile,
974/// return true only if the target allows the memory instruction to be volatile
975/// in the new address space.
977 Use &U, unsigned AddrSpace) {
978 User *Inst = U.getUser();
979 unsigned OpNo = U.getOperandNo();
980 bool VolatileIsAllowed = false;
981 if (auto *I = dyn_cast<Instruction>(Inst))
982 VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace);
983
984 if (auto *LI = dyn_cast<LoadInst>(Inst))
985 return OpNo == LoadInst::getPointerOperandIndex() &&
986 (VolatileIsAllowed || !LI->isVolatile());
987
988 if (auto *SI = dyn_cast<StoreInst>(Inst))
989 return OpNo == StoreInst::getPointerOperandIndex() &&
990 (VolatileIsAllowed || !SI->isVolatile());
991
992 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
993 return OpNo == AtomicRMWInst::getPointerOperandIndex() &&
994 (VolatileIsAllowed || !RMW->isVolatile());
995
996 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
998 (VolatileIsAllowed || !CmpX->isVolatile());
999
1000 return false;
1001}
1002
1003/// Update memory intrinsic uses that require more complex processing than
1004/// simple memory instructions. These require re-mangling and may have multiple
1005/// pointer operands.
1007 Value *NewV) {
1008 IRBuilder<> B(MI);
1009 MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
1010 MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
1011 MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
1012
1013 if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
1014 B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), MSI->getDestAlign(),
1015 false, // isVolatile
1016 TBAA, ScopeMD, NoAliasMD);
1017 } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
1018 Value *Src = MTI->getRawSource();
1019 Value *Dest = MTI->getRawDest();
1020
1021 // Be careful in case this is a self-to-self copy.
1022 if (Src == OldV)
1023 Src = NewV;
1024
1025 if (Dest == OldV)
1026 Dest = NewV;
1027
1028 if (isa<MemCpyInlineInst>(MTI)) {
1029 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
1030 B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src,
1031 MTI->getSourceAlign(), MTI->getLength(),
1032 false, // isVolatile
1033 TBAA, TBAAStruct, ScopeMD, NoAliasMD);
1034 } else if (isa<MemCpyInst>(MTI)) {
1035 MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
1036 B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
1037 MTI->getLength(),
1038 false, // isVolatile
1039 TBAA, TBAAStruct, ScopeMD, NoAliasMD);
1040 } else {
1041 assert(isa<MemMoveInst>(MTI));
1042 B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
1043 MTI->getLength(),
1044 false, // isVolatile
1045 TBAA, ScopeMD, NoAliasMD);
1046 }
1047 } else
1048 llvm_unreachable("unhandled MemIntrinsic");
1049
1050 MI->eraseFromParent();
1051 return true;
1052}
1053
1054// \p returns true if it is OK to change the address space of constant \p C with
1055// a ConstantExpr addrspacecast.
1056bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C,
1057 unsigned NewAS) const {
1059
1060 unsigned SrcAS = C->getType()->getPointerAddressSpace();
1061 if (SrcAS == NewAS || isa<UndefValue>(C))
1062 return true;
1063
1064 // Prevent illegal casts between different non-flat address spaces.
1065 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
1066 return false;
1067
1068 if (isa<ConstantPointerNull>(C))
1069 return true;
1070
1071 if (auto *Op = dyn_cast<Operator>(C)) {
1072 // If we already have a constant addrspacecast, it should be safe to cast it
1073 // off.
1074 if (Op->getOpcode() == Instruction::AddrSpaceCast)
1075 return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
1076
1077 if (Op->getOpcode() == Instruction::IntToPtr &&
1078 Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
1079 return true;
1080 }
1081
1082 return false;
1083}
1084
1086 Value::use_iterator End) {
1087 User *CurUser = I->getUser();
1088 ++I;
1089
1090 while (I != End && I->getUser() == CurUser)
1091 ++I;
1092
1093 return I;
1094}
1095
1096bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces(
1097 ArrayRef<WeakTrackingVH> Postorder,
1098 const ValueToAddrSpaceMapTy &InferredAddrSpace,
1099 const PredicatedAddrSpaceMapTy &PredicatedAS, Function *F) const {
1100 // For each address expression to be modified, creates a clone of it with its
1101 // pointer operands converted to the new address space. Since the pointer
1102 // operands are converted, the clone is naturally in the new address space by
1103 // construction.
1104 ValueToValueMapTy ValueWithNewAddrSpace;
1105 SmallVector<const Use *, 32> UndefUsesToFix;
1106 for (Value* V : Postorder) {
1107 unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
1108
1109 // In some degenerate cases (e.g. invalid IR in unreachable code), we may
1110 // not even infer the value to have its original address space.
1111 if (NewAddrSpace == UninitializedAddressSpace)
1112 continue;
1113
1114 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
1115 Value *New =
1116 cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace,
1117 PredicatedAS, &UndefUsesToFix);
1118 if (New)
1119 ValueWithNewAddrSpace[V] = New;
1120 }
1121 }
1122
1123 if (ValueWithNewAddrSpace.empty())
1124 return false;
1125
1126 // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
1127 for (const Use *UndefUse : UndefUsesToFix) {
1128 User *V = UndefUse->getUser();
1129 User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V));
1130 if (!NewV)
1131 continue;
1132
1133 unsigned OperandNo = UndefUse->getOperandNo();
1134 assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
1135 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
1136 }
1137
1138 SmallVector<Instruction *, 16> DeadInstructions;
1139
1140 // Replaces the uses of the old address expressions with the new ones.
1141 for (const WeakTrackingVH &WVH : Postorder) {
1142 assert(WVH && "value was unexpectedly deleted");
1143 Value *V = WVH;
1144 Value *NewV = ValueWithNewAddrSpace.lookup(V);
1145 if (NewV == nullptr)
1146 continue;
1147
1148 LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n with\n "
1149 << *NewV << '\n');
1150
1151 if (Constant *C = dyn_cast<Constant>(V)) {
1152 Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1153 C->getType());
1154 if (C != Replace) {
1155 LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
1156 << ": " << *Replace << '\n');
1157 C->replaceAllUsesWith(Replace);
1158 V = Replace;
1159 }
1160 }
1161
1162 Value::use_iterator I, E, Next;
1163 for (I = V->use_begin(), E = V->use_end(); I != E; ) {
1164 Use &U = *I;
1165
1166 // Some users may see the same pointer operand in multiple operands. Skip
1167 // to the next instruction.
1168 I = skipToNextUser(I, E);
1169
1171 *TTI, U, V->getType()->getPointerAddressSpace())) {
1172 // If V is used as the pointer operand of a compatible memory operation,
1173 // sets the pointer operand to NewV. This replacement does not change
1174 // the element type, so the resultant load/store is still valid.
1175 U.set(NewV);
1176 continue;
1177 }
1178
1179 User *CurUser = U.getUser();
1180 // Skip if the current user is the new value itself.
1181 if (CurUser == NewV)
1182 continue;
1183 // Handle more complex cases like intrinsic that need to be remangled.
1184 if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
1185 if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
1186 continue;
1187 }
1188
1189 if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
1190 if (rewriteIntrinsicOperands(II, V, NewV))
1191 continue;
1192 }
1193
1194 if (isa<Instruction>(CurUser)) {
1195 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
1196 // If we can infer that both pointers are in the same addrspace,
1197 // transform e.g.
1198 // %cmp = icmp eq float* %p, %q
1199 // into
1200 // %cmp = icmp eq float addrspace(3)* %new_p, %new_q
1201
1202 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1203 int SrcIdx = U.getOperandNo();
1204 int OtherIdx = (SrcIdx == 0) ? 1 : 0;
1205 Value *OtherSrc = Cmp->getOperand(OtherIdx);
1206
1207 if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
1208 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
1209 Cmp->setOperand(OtherIdx, OtherNewV);
1210 Cmp->setOperand(SrcIdx, NewV);
1211 continue;
1212 }
1213 }
1214
1215 // Even if the type mismatches, we can cast the constant.
1216 if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
1217 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
1218 Cmp->setOperand(SrcIdx, NewV);
1219 Cmp->setOperand(OtherIdx,
1220 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
1221 continue;
1222 }
1223 }
1224 }
1225
1226 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
1227 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1228 if (ASC->getDestAddressSpace() == NewAS) {
1229 if (!cast<PointerType>(ASC->getType())
1230 ->hasSameElementTypeAs(
1231 cast<PointerType>(NewV->getType()))) {
1232 BasicBlock::iterator InsertPos;
1233 if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
1234 InsertPos = std::next(NewVInst->getIterator());
1235 else if (Instruction *VInst = dyn_cast<Instruction>(V))
1236 InsertPos = std::next(VInst->getIterator());
1237 else
1238 InsertPos = ASC->getIterator();
1239
1240 NewV = CastInst::Create(Instruction::BitCast, NewV,
1241 ASC->getType(), "", &*InsertPos);
1242 }
1243 ASC->replaceAllUsesWith(NewV);
1244 DeadInstructions.push_back(ASC);
1245 continue;
1246 }
1247 }
1248
1249 // Otherwise, replaces the use with flat(NewV).
1250 if (Instruction *VInst = dyn_cast<Instruction>(V)) {
1251 // Don't create a copy of the original addrspacecast.
1252 if (U == V && isa<AddrSpaceCastInst>(V))
1253 continue;
1254
1255 // Insert the addrspacecast after NewV.
1256 BasicBlock::iterator InsertPos;
1257 if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
1258 InsertPos = std::next(NewVInst->getIterator());
1259 else
1260 InsertPos = std::next(VInst->getIterator());
1261
1262 while (isa<PHINode>(InsertPos))
1263 ++InsertPos;
1264 U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
1265 } else {
1266 U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1267 V->getType()));
1268 }
1269 }
1270 }
1271
1272 if (V->use_empty()) {
1273 if (Instruction *I = dyn_cast<Instruction>(V))
1274 DeadInstructions.push_back(I);
1275 }
1276 }
1277
1278 for (Instruction *I : DeadInstructions)
1280
1281 return true;
1282}
1283
1284bool InferAddressSpaces::runOnFunction(Function &F) {
1285 if (skipFunction(F))
1286 return false;
1287
1288 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1289 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1290 return InferAddressSpacesImpl(
1291 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT,
1292 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
1293 FlatAddrSpace)
1294 .run(F);
1295}
1296
1298 return new InferAddressSpaces(AddressSpace);
1299}
1300
1302 : FlatAddrSpace(UninitializedAddressSpace) {}
1304 : FlatAddrSpace(AddressSpace) {}
1305
1308 bool Changed =
1309 InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F),
1311 &AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace)
1312 .run(F);
1313 if (Changed) {
1317 return PA;
1318 }
1319 return PreservedAnalyses::all();
1320}
aarch64 promote const
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Hexagon Common GEP
IRTranslator LLVM IR MI
static cl::opt< bool > AssumeDefaultIsFlatAddressSpace("assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden, cl::desc("The default address space is assumed as the flat address space. " "This is mainly for test purpose."))
static bool isAddressExpression(const Value &V, const DataLayout &DL, const TargetTransformInfo *TTI)
static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV, Value *NewV)
Update memory intrinsic uses that require more complex processing than simple memory instructions.
Infer address spaces
static Value * operandWithNewAddressSpaceOrCreateUndef(const Use &OperandUse, unsigned NewAddrSpace, const ValueToValueMapTy &ValueWithNewAddrSpace, const PredicatedAddrSpaceMapTy &PredicatedAS, SmallVectorImpl< const Use * > *UndefUsesToFix)
static SmallVector< Value *, 2 > getPointerOperands(const Value &V, const DataLayout &DL, const TargetTransformInfo *TTI)
static Value * cloneConstantExprWithNewAddressSpace(ConstantExpr *CE, unsigned NewAddrSpace, const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL, const TargetTransformInfo *TTI)
Infer address static false bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL, const TargetTransformInfo *TTI)
static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI, Use &U, unsigned AddrSpace)
returns true if U is the pointer operand of a memory instruction with a single pointer operand that c...
static Value::use_iterator skipToNextUser(Value::use_iterator I, Value::use_iterator End)
#define DEBUG_TYPE
static const unsigned UninitializedAddressSpace
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
print must be executed print the must be executed context for all instructions
This header defines various interfaces for pass management in LLVM.
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
@ SI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This pass exposes codegen information to IR-level passes.
This defines the Use class.
This class represents a conversion between pointers from one address space to another.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:793
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:265
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:152
iterator begin() const
Definition: ArrayRef.h:151
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
static unsigned getPointerOperandIndex()
Definition: Instructions.h:645
static unsigned getPointerOperandIndex()
Definition: Instructions.h:879
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:112
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
This class represents a no-op cast from one type to another.
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:113
const Use & getArgOperandUse(unsigned i) const
Wrappers for getting the Use of a call argument.
Definition: InstrTypes.h:1364
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1353
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1358
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1447
This class represents a function call, abstracting a target machine's calling convention.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static CastInst * CreatePointerBitCastOrAddrSpaceCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast or an AddrSpaceCast cast instruction.
static bool isNoopCast(Instruction::CastOps Opcode, Type *SrcTy, Type *DstTy, const DataLayout &DL)
A no-op cast is one that can be effected without changing any bits.
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1002
static Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2232
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2220
This is an important base class in LLVM.
Definition: Constant.h:41
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:314
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:940
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:966
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2558
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:358
const BasicBlock * getParent() const
Definition: Instruction.h:90
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:54
static unsigned getPointerOperandIndex()
Definition: Instructions.h:266
Metadata node.
Definition: Metadata.h:943
This is the common base class for memset/memcpy/memmove.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition: Operator.h:31
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static unsigned getOperandNumForIncomingValue(unsigned i)
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:188
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:173
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
A vector that has set insertion semantics.
Definition: SetVector.h:40
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
static unsigned getPointerOperandIndex()
Definition: Instructions.h:395
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
unsigned getAssumedAddrSpace(const Value *V) const
bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const
bool collectFlatAddressOperands(SmallVectorImpl< int > &OpIndexes, Intrinsic::ID IID) const
Return any intrinsic address operand indexes which may be rewritten if they use a flat address space ...
Value * rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV, Value *NewV) const
Rewrite intrinsic call II such that OldV will be replaced with NewV, which has a different address sp...
unsigned getFlatAddressSpace() const
Returns the address space ID for a target's 'flat' address space.
bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const
Return true if the given instruction (assumed to be a memory access instruction) has a volatile varia...
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1731
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
User * getUser() const
Returns the User that contains this Use.
Definition: Use.h:72
Value * get() const
Definition: Use.h:66
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
Value * getOperand(unsigned i) const
Definition: User.h:169
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:164
bool empty() const
Definition: ValueMap.h:139
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:532
const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition: Value.cpp:777
use_iterator_impl< Use > use_iterator
Definition: Value.h:353
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:204
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1506
@ ReallyHidden
Definition: CommandLine.h:139
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition: Local.cpp:537
AddressSpace
Definition: NVPTXBaseInfo.h:21
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createInferAddressSpacesPass(unsigned AddressSpace=~0u)
bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)