LLVM 24.0.0git
AssumeBundleBuilder.cpp
Go to the documentation of this file.
1//===- AssumeBundleBuilder.cpp - tools to preserve informations -*- C++ -*-===//
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
10#include "llvm/ADT/MapVector.h"
11#include "llvm/ADT/Statistic.h"
15#include "llvm/IR/Dominators.h"
16#include "llvm/IR/Function.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/Operator.h"
24
25using namespace llvm;
26
27namespace llvm {
29 "enable-knowledge-retention", cl::init(false), cl::Hidden,
31 "enable preservation of attributes throughout code transformation"));
32} // namespace llvm
33
34#define DEBUG_TYPE "assume-builder"
35
36STATISTIC(NumAssumeBuilt, "Number of assume built by the assume builder");
37STATISTIC(NumBundlesInAssumes, "Total number of Bundles in the assume built");
38
39DEBUG_COUNTER(BuildAssumeCounter, "assume-builder-counter",
40 "Controls which assumes gets created");
41
42namespace {
43
44bool isUsefullToPreserve(Attribute::AttrKind Kind) {
45 switch (Kind) {
46 case Attribute::NonNull:
47 case Attribute::NoUndef:
48 case Attribute::Alignment:
49 case Attribute::Dereferenceable:
50 case Attribute::DereferenceableOrNull:
51 case Attribute::Cold:
52 return true;
53 default:
54 return false;
55 }
56}
57
58/// This function will try to transform the given knowledge into a more
59/// canonical one. the canonical knowledge maybe the given one.
60RetainedKnowledge canonicalizedKnowledge(RetainedKnowledge RK,
61 const DataLayout &DL) {
62 switch (RK.AttrKind) {
63 default:
64 return RK;
65 case Attribute::NonNull:
67 return RK;
68 case Attribute::Alignment: {
69 Value *V = RK.WasOn->stripInBoundsOffsets([&](const Value *Strip) {
70 if (auto *GEP = dyn_cast<GEPOperator>(Strip))
71 RK.ArgValue =
72 MinAlign(RK.ArgValue, GEP->getMaxPreservedAlignment(DL).value());
73 });
74 RK.WasOn = V;
75 return RK;
76 }
77 case Attribute::Dereferenceable:
78 case Attribute::DereferenceableOrNull: {
79 int64_t Offset = 0;
81 /*AllowNonInBounds*/ false);
82 if (Offset < 0)
83 return RK;
84 RK.ArgValue = RK.ArgValue + Offset;
85 RK.WasOn = V;
86 }
87 }
88 return RK;
89}
90
91/// This class contain all knowledge that have been gather while building an
92/// llvm.assume and the function to manipulate it.
93struct AssumeBuilderState {
94 Module *M;
95
96 using MapKey = std::pair<Value *, Attribute::AttrKind>;
97 SmallMapVector<MapKey, uint64_t, 8> AssumedKnowledgeMap;
98 Instruction *InstBeingModified = nullptr;
99 AssumptionCache* AC = nullptr;
100 DominatorTree* DT = nullptr;
101
102 AssumeBuilderState(Module *M, Instruction *I = nullptr,
103 AssumptionCache *AC = nullptr, DominatorTree *DT = nullptr)
104 : M(M), InstBeingModified(I), AC(AC), DT(DT) {}
105
106 bool tryToPreserveWithoutAddingAssume(RetainedKnowledge RK) {
107 if (!InstBeingModified || !RK.WasOn || !AC)
108 return false;
109 bool HasBeenPreserved = false;
110 Use* ToUpdate = nullptr;
112 RK.WasOn, {RK.AttrKind}, *AC,
113 [&](RetainedKnowledge RKOther, Instruction *Assume,
114 const CallInst::BundleOpInfo *Bundle) {
115 if (!isValidAssumeForContext(Assume, InstBeingModified, DT))
116 return false;
117 if (RKOther.ArgValue >= RK.ArgValue) {
118 HasBeenPreserved = true;
119 return true;
120 } else if (isValidAssumeForContext(InstBeingModified, Assume, DT)) {
121 HasBeenPreserved = true;
122 IntrinsicInst *Intr = cast<IntrinsicInst>(Assume);
123 ToUpdate = &Intr->op_begin()[Bundle->Begin + ABA_Argument];
124 return true;
125 }
126 return false;
127 });
128 if (ToUpdate)
129 ToUpdate->set(
130 ConstantInt::get(Type::getInt64Ty(M->getContext()), RK.ArgValue));
131 return HasBeenPreserved;
132 }
133
134 bool isKnowledgeWorthPreserving(RetainedKnowledge RK) {
135 if (!RK)
136 return false;
137 if (!RK.WasOn)
138 return true;
139 if (RK.WasOn->getType()->isPointerTy()) {
140 Value *UnderlyingPtr = getUnderlyingObject(RK.WasOn);
141 if (isa<AllocaInst>(UnderlyingPtr) || isa<GlobalValue>(UnderlyingPtr))
142 return false;
143 }
144 if (auto *Arg = dyn_cast<Argument>(RK.WasOn)) {
145 if (Arg->hasAttribute(RK.AttrKind) &&
147 Arg->getAttribute(RK.AttrKind).getValueAsInt() >= RK.ArgValue))
148 return false;
149 return true;
150 }
151 if (auto *Inst = dyn_cast<Instruction>(RK.WasOn))
153 if (RK.WasOn->use_empty())
154 return false;
155 Use *SingleUse = RK.WasOn->getSingleUndroppableUse();
156 if (SingleUse && SingleUse->getUser() == InstBeingModified)
157 return false;
158 }
159 return true;
160 }
161
162 void addKnowledge(RetainedKnowledge RK) {
163 RK = canonicalizedKnowledge(RK, M->getDataLayout());
164
165 if (!isKnowledgeWorthPreserving(RK))
166 return;
167
168 if (tryToPreserveWithoutAddingAssume(RK))
169 return;
170 MapKey Key{RK.WasOn, RK.AttrKind};
171 auto [Lookup, Inserted] = AssumedKnowledgeMap.try_emplace(Key, RK.ArgValue);
172 if (Inserted)
173 return;
174 assert(((Lookup->second == 0 && RK.ArgValue == 0) ||
175 (Lookup->second != 0 && RK.ArgValue != 0)) &&
176 "inconsistent argument value");
177
178 /// This is only desirable because for all attributes taking an argument
179 /// higher is better.
180 Lookup->second = std::max(Lookup->second, RK.ArgValue);
181 }
182
183 void addAttribute(Attribute Attr, Value *WasOn) {
184 if (Attr.isTypeAttribute() || Attr.isStringAttribute() ||
185 !isUsefullToPreserve(Attr.getKindAsEnum()))
186 return;
187 uint64_t AttrArg = 0;
188 if (Attr.isIntAttribute())
189 AttrArg = Attr.getValueAsInt();
190 addKnowledge({Attr.getKindAsEnum(), AttrArg, WasOn});
191 }
192
193 void addCall(const CallBase *Call) {
194 auto addAttrList = [&](AttributeList AttrList, unsigned NumArgs) {
195 for (unsigned Idx = 0; Idx < NumArgs; Idx++)
196 for (Attribute Attr : AttrList.getParamAttrs(Idx)) {
197 bool IsPoisonAttr = Attr.hasAttribute(Attribute::NonNull) ||
198 Attr.hasAttribute(Attribute::Alignment);
199 if (!IsPoisonAttr || Call->isPassingUndefUB(Idx))
200 addAttribute(Attr, Call->getArgOperand(Idx));
201 }
202 for (Attribute Attr : AttrList.getFnAttrs())
203 addAttribute(Attr, nullptr);
204 };
205 addAttrList(Call->getAttributes(), Call->arg_size());
206 if (Function *Fn = Call->getCalledFunction())
207 addAttrList(Fn->getAttributes(), Fn->arg_size());
208 }
209
210 AssumeInst *build() {
211 if (AssumedKnowledgeMap.empty())
212 return nullptr;
213 if (!DebugCounter::shouldExecute(BuildAssumeCounter))
214 return nullptr;
215 Function *FnAssume =
216 Intrinsic::getOrInsertDeclaration(M, Intrinsic::assume);
217 LLVMContext &C = M->getContext();
219 for (auto &MapElem : AssumedKnowledgeMap) {
221 if (MapElem.first.first)
222 Args.push_back(MapElem.first.first);
223
224 /// This is only valid because for all attribute that currently exist a
225 /// value of 0 is useless. and should not be preserved.
226 if (MapElem.second)
227 Args.push_back(ConstantInt::get(Type::getInt64Ty(M->getContext()),
228 MapElem.second));
230 std::string(Attribute::getNameFromAttrKind(MapElem.first.second)),
231 Args));
232 NumBundlesInAssumes++;
233 }
234 NumAssumeBuilt++;
236 FnAssume, ArrayRef<Value *>({ConstantInt::getTrue(C)}), OpBundle));
237 }
238
239 void addAccessedPtr(Instruction *MemInst, Value *Pointer, Type *AccType,
240 MaybeAlign MA) {
241 unsigned DerefSize = MemInst->getModule()
242 ->getDataLayout()
243 .getTypeStoreSize(AccType)
245 if (DerefSize != 0) {
246 addKnowledge({Attribute::Dereferenceable, DerefSize, Pointer});
247 if (!NullPointerIsDefined(MemInst->getFunction(),
248 Pointer->getType()->getPointerAddressSpace()))
249 addKnowledge({Attribute::NonNull, 0u, Pointer});
250 }
251 if (MA.valueOrOne() > 1)
252 addKnowledge({Attribute::Alignment, MA.valueOrOne().value(), Pointer});
253 }
254
255 void addInstruction(Instruction *I) {
256 if (auto *Call = dyn_cast<CallBase>(I))
257 return addCall(Call);
258 if (auto *Load = dyn_cast<LoadInst>(I))
259 return addAccessedPtr(I, Load->getPointerOperand(), Load->getType(),
260 Load->getAlign());
261 if (auto *Store = dyn_cast<StoreInst>(I))
262 return addAccessedPtr(I, Store->getPointerOperand(),
263 Store->getValueOperand()->getType(),
264 Store->getAlign());
265 if (auto *RMW = dyn_cast<AtomicRMWInst>(I))
266 return addAccessedPtr(I, RMW->getPointerOperand(),
267 RMW->getValOperand()->getType(), RMW->getAlign());
268 if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(I))
269 return addAccessedPtr(I, CmpXchg->getPointerOperand(),
270 CmpXchg->getCompareOperand()->getType(),
271 CmpXchg->getAlign());
272 // TODO: Maybe we should look around and merge with other llvm.assume.
273 }
274};
275
276} // namespace
277
280 return nullptr;
281 AssumeBuilderState Builder(I->getModule());
282 Builder.addInstruction(I);
283 return Builder.build();
284}
285
287 DominatorTree *DT) {
288 if (!EnableKnowledgeRetention || I->isTerminator())
289 return false;
290 bool Changed = false;
291 AssumeBuilderState Builder(I->getModule(), I, AC, DT);
292 Builder.addInstruction(I);
293 if (auto *Intr = Builder.build()) {
294 Intr->insertBefore(I->getIterator());
295 Changed = true;
296 if (AC)
297 AC->registerAssumption(Intr);
298 }
299 return Changed;
300}
301
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
if(PassOpts->AAPipeline)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
LLVM_ABI bool isIntAttribute() const
Return true if the attribute is an integer attribute.
LLVM_ABI uint64_t getValueAsInt() const
Return the attribute's value as an integer.
LLVM_ABI Attribute::AttrKind getKindAsEnum() const
Return the attribute's kind as an enum (Attribute::AttrKind).
static LLVM_ABI StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind)
LLVM_ABI bool isTypeAttribute() const
Return true if the attribute is a type attribute.
static bool isIntAttrKind(AttrKind Kind)
Definition Attributes.h:140
LLVM_ABI bool hasAttribute(AttrKind Val) const
Return true if the attribute is present.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:581
static bool shouldExecute(CounterInfo &Counter)
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:119
bool empty() const
Definition MapVector.h:80
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition Module.h:325
A container for an operand bundle being viewed as a set of values rather than a set of uses.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_iterator op_begin()
Definition User.h:259
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:823
LLVM_ABI Use * getSingleUndroppableUse()
Return true if there is exactly one use of this value that cannot be dropped.
Definition Value.cpp:168
bool use_empty() const
Definition Value.h:348
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
initializer< Ty > init(const Ty &Val)
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
Definition IRSymtab.cpp:348
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > EnableKnowledgeRetention
@ Offset
Definition DWP.cpp:577
LLVM_ABI RetainedKnowledge getKnowledgeForValue(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, function_ref< bool(RetainedKnowledge, Instruction *, const CallBase::BundleOpInfo *)> Filter=[](auto...) { return true;})
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and it match...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:352
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:415
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI AssumeInst * buildAssumeFromInst(Instruction *I)
Build a call to llvm.assume to preserve informations that can be derived from the given instruction.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
uint32_t Begin
The index in the Use& vector where operands for this operand bundle starts.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
Represent one information held inside an operand bundle of an llvm.assume.
Attribute::AttrKind AttrKind