106 #define DEBUG_TYPE "infer-address-spaces"
108 using namespace llvm;
111 static const unsigned UninitializedAddressSpace = ~0u;
119 unsigned FlatAddrSpace;
131 bool runOnFunction(
Function &
F)
override;
136 updateAddressSpace(
const Value &V,
137 const ValueToAddrSpaceMapTy &InferredAddrSpace)
const;
142 ValueToAddrSpaceMapTy *InferredAddrSpace)
const;
144 bool isSafeToCastConstAddrSpace(
Constant *
C,
unsigned NewAS)
const;
151 const ValueToAddrSpaceMapTy &InferredAddrSpace,
154 void appendsFlatAddressExpressionToPostorderStack(
155 Value *V, std::vector<std::pair<Value *, bool>> &PostorderStack,
160 void collectRewritableIntrinsicOperands(
162 std::vector<std::pair<Value *, bool>> &PostorderStack,
165 std::vector<WeakTrackingVH> collectFlatAddressExpressions(
Function &F)
const;
167 Value *cloneValueWithNewAddressSpace(
168 Value *V,
unsigned NewAddrSpace,
171 unsigned joinAddressSpaces(
unsigned AS1,
unsigned AS2)
const;
187 static
bool isAddressExpression(
const Value &V) {
188 if (!isa<Operator>(V))
191 switch (cast<Operator>(V).getOpcode()) {
192 case Instruction::PHI:
193 case Instruction::BitCast:
194 case Instruction::AddrSpaceCast:
195 case Instruction::GetElementPtr:
209 case Instruction::PHI: {
210 auto IncomingValues = cast<PHINode>(
Op).incoming_values();
212 IncomingValues.end());
214 case Instruction::BitCast:
215 case Instruction::AddrSpaceCast:
216 case Instruction::GetElementPtr:
226 bool InferAddressSpaces::rewriteIntrinsicOperands(
IntrinsicInst *II,
232 case Intrinsic::amdgcn_atomic_inc:
233 case Intrinsic::amdgcn_atomic_dec:{
235 if (!IsVolatile || !IsVolatile->
isZero())
240 case Intrinsic::objectsize: {
255 void InferAddressSpaces::collectRewritableIntrinsicOperands(
256 IntrinsicInst *II, std::vector<std::pair<Value *, bool>> &PostorderStack,
259 case Intrinsic::objectsize:
260 case Intrinsic::amdgcn_atomic_inc:
261 case Intrinsic::amdgcn_atomic_dec:
262 appendsFlatAddressExpressionToPostorderStack(II->
getArgOperand(0),
263 PostorderStack, Visited);
273 void InferAddressSpaces::appendsFlatAddressExpressionToPostorderStack(
274 Value *V, std::vector<std::pair<Value *, bool>> &PostorderStack,
282 if (isAddressExpression(*CE) && Visited.
insert(CE).second)
283 PostorderStack.push_back(std::make_pair(CE,
false));
288 if (isAddressExpression(*V) &&
290 if (Visited.
insert(V).second) {
291 PostorderStack.push_back(std::make_pair(V,
false));
296 if (isAddressExpression(*CE) && Visited.
insert(CE).second)
297 PostorderStack.emplace_back(CE,
false);
306 std::vector<WeakTrackingVH>
307 InferAddressSpaces::collectFlatAddressExpressions(
Function &
F)
const {
310 std::vector<std::pair<Value *, bool>> PostorderStack;
314 auto PushPtrOperand = [&](
Value *
Ptr) {
315 appendsFlatAddressExpressionToPostorderStack(
Ptr, PostorderStack,
323 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(&
I)) {
324 if (!
GEP->getType()->isVectorTy())
325 PushPtrOperand(
GEP->getPointerOperand());
326 }
else if (
auto *LI = dyn_cast<LoadInst>(&
I))
327 PushPtrOperand(LI->getPointerOperand());
328 else if (
auto *SI = dyn_cast<StoreInst>(&
I))
329 PushPtrOperand(
SI->getPointerOperand());
330 else if (
auto *RMW = dyn_cast<AtomicRMWInst>(&
I))
331 PushPtrOperand(RMW->getPointerOperand());
332 else if (
auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&
I))
333 PushPtrOperand(CmpX->getPointerOperand());
334 else if (
auto *
MI = dyn_cast<MemIntrinsic>(&
I)) {
336 PushPtrOperand(
MI->getRawDest());
339 if (
auto *MTI = dyn_cast<MemTransferInst>(
MI))
340 PushPtrOperand(MTI->getRawSource());
341 }
else if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
342 collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
343 else if (
ICmpInst *Cmp = dyn_cast<ICmpInst>(&
I)) {
345 if (Cmp->getOperand(0)->getType()->isPointerTy()) {
346 PushPtrOperand(Cmp->getOperand(0));
347 PushPtrOperand(Cmp->getOperand(1));
349 }
else if (
auto *ASC = dyn_cast<AddrSpaceCastInst>(&
I)) {
350 if (!ASC->getType()->isVectorTy())
351 PushPtrOperand(ASC->getPointerOperand());
355 std::vector<WeakTrackingVH> Postorder;
356 while (!PostorderStack.empty()) {
357 Value *TopVal = PostorderStack.back().first;
360 if (PostorderStack.back().second) {
362 Postorder.push_back(TopVal);
363 PostorderStack.pop_back();
367 PostorderStack.back().second =
true;
369 appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
380 const Use &OperandUse,
unsigned NewAddrSpace,
388 if (
Constant *
C = dyn_cast<Constant>(Operand))
391 if (
Value *NewOperand = ValueWithNewAddrSpace.
lookup(Operand))
414 if (I->
getOpcode() == Instruction::AddrSpaceCast) {
420 if (Src->
getType() != NewPtrType)
428 if (!OperandUse.get()->getType()->isPointerTy())
432 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix));
436 case Instruction::BitCast:
437 return new BitCastInst(NewPointerOperands[0], NewPtrType);
438 case Instruction::PHI: {
442 for (
unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
444 NewPHI->addIncoming(NewPointerOperands[OperandNo],
445 PHI->getIncomingBlock(Index));
449 case Instruction::GetElementPtr: {
460 NewPointerOperands[2],
"",
nullptr,
I);
476 if (CE->
getOpcode() == Instruction::AddrSpaceCast) {
485 if (CE->
getOpcode() == Instruction::BitCast) {
513 if (
Value *NewOperand = ValueWithNewAddrSpace.
lookup(Operand)) {
515 NewOperands.
push_back(cast<Constant>(NewOperand));
527 if (CE->
getOpcode() == Instruction::GetElementPtr) {
531 NewOperands, TargetType,
false,
532 NewOperands[0]->
getType()->getPointerElementType());
543 Value *InferAddressSpaces::cloneValueWithNewAddressSpace(
544 Value *V,
unsigned NewAddrSpace,
548 assert(isAddressExpression(*V) &&
553 I, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix);
554 if (
Instruction *NewI = dyn_cast<Instruction>(NewV)) {
555 if (NewI->getParent() ==
nullptr) {
556 NewI->insertBefore(
I);
564 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace);
569 unsigned InferAddressSpaces::joinAddressSpaces(
unsigned AS1,
570 unsigned AS2)
const {
571 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
572 return FlatAddrSpace;
574 if (AS1 == UninitializedAddressSpace)
576 if (AS2 == UninitializedAddressSpace)
580 return (AS1 == AS2) ? AS1 : FlatAddrSpace;
583 bool InferAddressSpaces::runOnFunction(
Function &F) {
588 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
590 if (FlatAddrSpace == UninitializedAddressSpace)
594 std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
598 ValueToAddrSpaceMapTy InferredAddrSpace;
599 inferAddressSpaces(Postorder, &InferredAddrSpace);
603 return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, &F);
608 void InferAddressSpaces::inferAddressSpaces(
610 ValueToAddrSpaceMapTy *InferredAddrSpace)
const {
613 for (
Value *V : Postorder)
614 (*InferredAddrSpace)[V] = UninitializedAddressSpace;
616 while (!Worklist.empty()) {
617 Value *V = Worklist.pop_back_val();
621 DEBUG(
dbgs() <<
"Updating the address space of\n " << *V <<
'\n');
628 (*InferredAddrSpace)[V] = NewAS.
getValue();
632 if (Worklist.count(
User))
635 auto Pos = InferredAddrSpace->find(
User);
638 if (Pos == InferredAddrSpace->end())
644 if (Pos->second == FlatAddrSpace)
647 Worklist.insert(
User);
653 const Value &V,
const ValueToAddrSpaceMapTy &InferredAddrSpace)
const {
654 assert(InferredAddrSpace.count(&V));
658 unsigned NewAS = UninitializedAddressSpace;
660 const Operator &Op = cast<Operator>(V);
665 auto I = InferredAddrSpace.find(Src0);
666 unsigned Src0AS = (
I != InferredAddrSpace.end()) ?
669 auto J = InferredAddrSpace.find(Src1);
670 unsigned Src1AS = (J != InferredAddrSpace.end()) ?
679 if ((C1 && Src0AS == UninitializedAddressSpace) ||
680 (C0 && Src1AS == UninitializedAddressSpace))
683 if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
685 else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
688 NewAS = joinAddressSpaces(Src0AS, Src1AS);
691 auto I = InferredAddrSpace.find(PtrOperand);
692 unsigned OperandAS =
I != InferredAddrSpace.end() ?
693 I->second : PtrOperand->getType()->getPointerAddressSpace();
696 NewAS = joinAddressSpaces(NewAS, OperandAS);
697 if (NewAS == FlatAddrSpace)
702 unsigned OldAS = InferredAddrSpace.lookup(&V);
703 assert(OldAS != FlatAddrSpace);
716 if (
auto *LI = dyn_cast<LoadInst>(Inst))
719 if (
auto *
SI = dyn_cast<StoreInst>(Inst))
722 if (
auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
725 if (
auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
743 if (
auto *MSI = dyn_cast<MemSetInst>(MI)) {
745 MSI->getLength(), MSI->getAlignment(),
747 TBAA, ScopeMD, NoAliasMD);
748 }
else if (
auto *MTI = dyn_cast<MemTransferInst>(MI)) {
749 Value *Src = MTI->getRawSource();
750 Value *Dest = MTI->getRawDest();
759 if (isa<MemCpyInst>(MTI)) {
764 TBAA, TBAAStruct, ScopeMD, NoAliasMD);
766 assert(isa<MemMoveInst>(MTI));
770 TBAA, ScopeMD, NoAliasMD);
781 bool InferAddressSpaces::isSafeToCastConstAddrSpace(
Constant *
C,
unsigned NewAS)
const {
782 assert(NewAS != UninitializedAddressSpace);
785 if (SrcAS == NewAS || isa<UndefValue>(C))
789 if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
792 if (isa<ConstantPointerNull>(C))
795 if (
auto *Op = dyn_cast<Operator>(C)) {
798 if (Op->
getOpcode() == Instruction::AddrSpaceCast)
799 return isSafeToCastConstAddrSpace(cast<Constant>(Op->
getOperand(0)), NewAS);
801 if (Op->
getOpcode() == Instruction::IntToPtr &&
811 User *CurUser = I->getUser();
814 while (I != End && I->getUser() == CurUser)
820 bool InferAddressSpaces::rewriteWithNewAddressSpaces(
822 const ValueToAddrSpaceMapTy &InferredAddrSpace,
Function *F)
const {
829 for (
Value* V : Postorder) {
830 unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
832 ValueWithNewAddrSpace[V] = cloneValueWithNewAddressSpace(
833 V, NewAddrSpace, ValueWithNewAddrSpace, &UndefUsesToFix);
837 if (ValueWithNewAddrSpace.
empty())
841 for (
const Use *UndefUse : UndefUsesToFix) {
842 User *V = UndefUse->getUser();
843 User *NewV = cast<User>(ValueWithNewAddrSpace.
lookup(V));
844 unsigned OperandNo = UndefUse->getOperandNo();
853 assert(WVH &&
"value was unexpectedly deleted");
859 DEBUG(
dbgs() <<
"Replacing the uses of " << *V
860 <<
"\n with\n " << *NewV <<
'\n');
862 if (
Constant *C = dyn_cast<Constant>(V)) {
866 DEBUG(
dbgs() <<
"Inserting replacement const cast: "
867 << Replace <<
": " << *Replace <<
'\n');
891 if (
auto *
MI = dyn_cast<MemIntrinsic>(CurUser)) {
896 if (
auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
897 if (rewriteIntrinsicOperands(II, V, NewV))
901 if (isa<Instruction>(CurUser)) {
902 if (
ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
911 int OtherIdx = (SrcIdx == 0) ? 1 : 0;
912 Value *OtherSrc = Cmp->getOperand(OtherIdx);
914 if (
Value *OtherNewV = ValueWithNewAddrSpace.
lookup(OtherSrc)) {
915 if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
916 Cmp->setOperand(OtherIdx, OtherNewV);
917 Cmp->setOperand(SrcIdx, NewV);
923 if (
auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
924 if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
925 Cmp->setOperand(SrcIdx, NewV);
926 Cmp->setOperand(OtherIdx,
935 if (ASC->getDestAddressSpace() == NewAS) {
936 ASC->replaceAllUsesWith(NewV);
945 while (isa<PHINode>(InsertPos))
968 return new InferAddressSpaces();
static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV, Value *NewV)
Update memory intrinsic uses that require more complex processing than simple memory instructions...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
Type * getSourceElementType() const
static Value * operandWithNewAddressSpaceOrCreateUndef(const Use &OperandUse, unsigned NewAddrSpace, const ValueToValueMapTy &ValueWithNewAddrSpace, SmallVectorImpl< const Use * > *UndefUsesToFix)
A Module instance is used to store all the information related to an LLVM module. ...
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
unsigned getNumOperands() const
static Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
const Function * getParent() const
Return the enclosing method, or null if none.
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memset to the specified pointer and the specified value.
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
INITIALIZE_PASS(InferAddressSpaces, DEBUG_TYPE,"Infer address spaces", false, false) static bool isAddressExpression(const Value &V)
Type * getPointerElementType() const
static unsigned getOperandNumForIncomingValue(unsigned i)
AnalysisUsage & addRequired()
This class represents a conversion between pointers from one address space to another.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const AMDGPUAS &AS return SrcAS
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
A constant value that is initialized with an expression using other constant values.
Value handle that is nullable, but tries to track the Value.
const T & getValue() const LLVM_LVALUE_FUNCTION
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
CallInst * CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memmove between the specified pointers.
This class represents a no-op cast from one type to another.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
use_iterator_impl< Use > use_iterator
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static unsigned getPointerOperandIndex()
unsigned getOperandNo() const
Return the operand # of this use in its User.
The instances of the Type class are immutable: once they are created, they are never changed...
static unsigned getPointerOperandIndex()
This is an important base class in LLVM.
std::pair< iterator, bool > insert(const ValueT &V)
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
static const unsigned End
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
void initializeInferAddressSpacesPass(PassRegistry &)
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
static wasm::ValType getType(const TargetRegisterClass *RC)
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static bool isSimplePointerUseValidToReplace(Use &U)
returns true if U is the pointer operand of a memory instruction with a single pointer operand that c...
static Value * cloneConstantExprWithNewAddressSpace(ConstantExpr *CE, unsigned NewAddrSpace, const ValueToValueMapTy &ValueWithNewAddrSpace)
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
This is a utility class that provides an abstraction for the common functionality between Instruction...
Type * getType() const
All values are typed, get the type of this value.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
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...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
static Value * cloneInstructionWithNewAddressSpace(Instruction *I, unsigned NewAddrSpace, const ValueToValueMapTy &ValueWithNewAddrSpace, SmallVectorImpl< const Use * > *UndefUsesToFix)
iterator_range< user_iterator > users()
llvm_unreachable("Unknown RegBank!")
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
FunctionPass * createInferAddressSpacesPass()
void setCalledFunction(Value *Fn)
Set the function called.
CallInst * CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
void setArgOperand(unsigned i, Value *v)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static unsigned getPointerOperandIndex()
static unsigned getPointerOperandIndex()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
static SmallVector< Value *, 2 > getPointerOperands(const Value &V)
static Value::use_iterator skipToNextUser(Value::use_iterator I, Value::use_iterator End)
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
inst_range instructions(Function *F)
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Constant * getWithOperands(ArrayRef< Constant * > Ops) const
This returns the current constant expression with the operands replaced with the specified values...
const BasicBlock * getParent() const
A wrapper class for inspecting calls to intrinsic functions.