32 "enable preservation of attributes throughout code transformation"));
35#define DEBUG_TYPE "assume-builder"
37STATISTIC(NumAssumeBuilt,
"Number of assume built by the assume builder");
38STATISTIC(NumBundlesInAssumes,
"Total number of Bundles in the assume built");
40 "Number of assume merged by the assume simplify pass");
42 "Number of assume removed by the assume simplify pass");
45 "Controls which assumes gets created");
51 case Attribute::NonNull:
52 case Attribute::NoUndef:
53 case Attribute::Alignment:
54 case Attribute::Dereferenceable:
55 case Attribute::DereferenceableOrNull:
70 case Attribute::NonNull:
73 case Attribute::Alignment: {
82 case Attribute::Dereferenceable:
83 case Attribute::DereferenceableOrNull: {
98struct AssumeBuilderState {
101 using MapKey = std::pair<Value *, Attribute::AttrKind>;
102 SmallMapVector<MapKey, uint64_t, 8> AssumedKnowledgeMap;
104 AssumptionCache* AC =
nullptr;
105 DominatorTree* DT =
nullptr;
107 AssumeBuilderState(
Module *M, Instruction *
I =
nullptr,
108 AssumptionCache *AC =
nullptr, DominatorTree *DT =
nullptr)
109 : M(M), InstBeingModified(
I), AC(AC), DT(DT) {}
111 bool tryToPreserveWithoutAddingAssume(RetainedKnowledge RK) {
112 if (!InstBeingModified || !RK.
WasOn || !AC)
114 bool HasBeenPreserved =
false;
115 Use* ToUpdate =
nullptr;
117 RK.
WasOn, {RK.AttrKind}, *AC,
118 [&](RetainedKnowledge RKOther, Instruction *Assume,
119 const CallInst::BundleOpInfo *Bundle) {
120 if (!isValidAssumeForContext(Assume, InstBeingModified, DT))
122 if (RKOther.ArgValue >= RK.ArgValue) {
123 HasBeenPreserved = true;
126 HasBeenPreserved =
true;
135 ConstantInt::get(Type::getInt64Ty(M->getContext()), RK.
ArgValue));
136 return HasBeenPreserved;
150 if (Arg->hasAttribute(RK.
AttrKind) &&
161 if (SingleUse && SingleUse->getUser() == InstBeingModified)
168 RK = canonicalizedKnowledge(RK, M->getDataLayout());
170 if (!isKnowledgeWorthPreserving(RK))
173 if (tryToPreserveWithoutAddingAssume(RK))
181 "inconsistent argument value");
199 auto addAttrList = [&](AttributeList AttrList,
unsigned NumArgs) {
200 for (
unsigned Idx = 0; Idx < NumArgs; Idx++)
201 for (
Attribute Attr : AttrList.getParamAttrs(Idx)) {
202 bool IsPoisonAttr = Attr.
hasAttribute(Attribute::NonNull) ||
204 if (!IsPoisonAttr ||
Call->isPassingUndefUB(Idx))
205 addAttribute(Attr,
Call->getArgOperand(Idx));
207 for (
Attribute Attr : AttrList.getFnAttrs())
208 addAttribute(Attr,
nullptr);
210 addAttrList(
Call->getAttributes(),
Call->arg_size());
212 addAttrList(Fn->getAttributes(), Fn->arg_size());
216 if (AssumedKnowledgeMap.
empty())
224 for (
auto &MapElem : AssumedKnowledgeMap) {
226 if (MapElem.first.first)
227 Args.push_back(MapElem.first.first);
237 NumBundlesInAssumes++;
246 unsigned DerefSize = MemInst->
getModule()
250 if (DerefSize != 0) {
251 addKnowledge({Attribute::Dereferenceable, DerefSize,
Pointer});
253 Pointer->getType()->getPointerAddressSpace()))
254 addKnowledge({Attribute::NonNull, 0
u,
Pointer});
262 return addCall(
Call);
264 return addAccessedPtr(
I,
Load->getPointerOperand(),
Load->getType(),
267 return addAccessedPtr(
I,
Store->getPointerOperand(),
268 Store->getValueOperand()->getType(),
271 return addAccessedPtr(
I, RMW->getPointerOperand(),
272 RMW->getValOperand()->getType(), RMW->getAlign());
274 return addAccessedPtr(
I, CmpXchg->getPointerOperand(),
275 CmpXchg->getCompareOperand()->getType(),
276 CmpXchg->getAlign());
286 AssumeBuilderState Builder(
I->getModule());
287 Builder.addInstruction(
I);
288 return Builder.build();
296 AssumeBuilderState Builder(
I->getModule(),
I, AC, DT);
297 Builder.addInstruction(
I);
298 if (
auto *Intr = Builder.build()) {
299 Intr->insertBefore(
I->getIterator());
309struct AssumeSimplify {
317 bool MadeChange =
false;
321 :
F(
F), AC(AC), DT(DT),
C(
C),
324 void buildMapping(
bool FilterBooleanArgument) {
326 for (
Value *V : AC.assumptions()) {
330 if (FilterBooleanArgument) {
332 if (!Arg || Arg->isZero())
335 BBToAssume[
Assume->getParent()].push_back(Assume);
338 for (
auto &Elem : BBToAssume) {
340 [](
const IntrinsicInst *
LHS,
const IntrinsicInst *
RHS) {
341 return LHS->comesBefore(RHS);
348 void RunCleanup(
bool ForceCleanup) {
349 for (IntrinsicInst *Assume : CleanupToDo) {
351 if (!Arg || Arg->isZero() ||
360 Assume->eraseFromParent();
368 void dropRedundantKnowledge() {
372 CallInst::BundleOpInfo *BOI;
375 SmallDenseMap<std::pair<Value *, Attribute::AttrKind>,
379 for (
Value *V : BBToAssume[BB]) {
383 for (CallInst::BundleOpInfo &BOI :
Assume->bundle_op_infos()) {
384 auto RemoveFromAssume = [&]() {
385 CleanupToDo.insert(Assume);
386 if (BOI.Begin != BOI.End) {
392 if (BOI.Tag == IgnoreTag) {
393 CleanupToDo.insert(Assume);
396 RetainedKnowledge RK =
399 bool HasSameKindAttr = Arg->hasAttribute(RK.
AttrKind);
401 if (!Attribute::isIntAttrKind(RK.
AttrKind) ||
402 Arg->getAttribute(RK.
AttrKind).getValueAsInt() >=
408 Assume, &*F.getEntryBlock().getFirstInsertionPt()) ||
409 Assume == &*F.getEntryBlock().getFirstInsertionPt()) {
426 Elem.Assume->op_begin()[Elem.BOI->Begin +
ABA_Argument].set(
427 ConstantInt::get(Type::getInt64Ty(C), RK.
ArgValue));
442 void mergeRange(BasicBlock *BB, MergeIterator Begin, MergeIterator End) {
443 if (Begin == End || std::next(Begin) == End)
447 AssumeBuilderState Builder(F.getParent());
452 InsertPt = std::next(InsertPt);
454 CleanupToDo.insert(
I);
455 for (CallInst::BundleOpInfo &BOI :
I->bundle_op_infos()) {
456 RetainedKnowledge RK =
460 Builder.addKnowledge(RK);
462 if (
I->getParent() == InsertPt->getParent() &&
463 (InsertPt->comesBefore(
I) || &*InsertPt ==
I))
464 InsertPt =
I->getNextNode()->getIterator();
470 if (InsertPt->comesBefore(*Begin))
471 for (
auto It = (*Begin)->getIterator(),
E = InsertPt->getIterator();
474 InsertPt = std::next(It);
477 auto *MergedAssume = Builder.build();
481 MergedAssume->insertBefore(InsertPt);
482 AC.registerAssumption(MergedAssume);
487 void mergeAssumes() {
491 for (
auto &Elem : BBToAssume) {
492 SmallVectorImpl<IntrinsicInst *> &AssumesInBB = Elem.second;
493 if (AssumesInBB.
size() < 2)
500 MergeIterator LastSplit = AssumesInBB.
begin();
501 for (; It !=
E; ++It)
503 for (; (*LastSplit)->comesBefore(&*It); ++LastSplit)
505 if (SplitPoints.
back() != LastSplit)
509 for (
auto SplitIt = SplitPoints.
begin();
510 SplitIt != std::prev(SplitPoints.
end()); SplitIt++) {
511 mergeRange(Elem.first, *SplitIt, *(SplitIt + 1));
519 AssumeSimplify AS(
F, *AC, DT,
F.getContext());
523 AS.dropRedundantKnowledge();
526 AS.RunCleanup(
false);
533 return AS.MadeChange;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
Module.h This file contains the declarations for the Module class.
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
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),...
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...
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)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
LLVM_ABI bool isTypeAttribute() const
Return true if the attribute is a type attribute.
static bool isIntAttrKind(AttrKind Kind)
LLVM_ABI bool hasAttribute(AttrKind Val) const
Return true if the attribute is present.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::iterator iterator
Instruction iterators...
Represents analyses that only rely on functions' control flow.
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.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
static bool shouldExecute(CounterInfo &Counter)
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
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.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
A container for an operand bundle being viewed as a set of values rather than a set of uses.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Implements a dense probed hash-table based set with some number of buckets stored inline.
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isPointerTy() const
True if this is an instance of PointerType.
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
LLVM_ABI Use * getSingleUndroppableUse()
Return true if there is exactly one use of this value that cannot be dropped.
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ C
The default llvm calling convention, compatible with C.
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.
NodeAddr< UseNode * > Use
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > EnableKnowledgeRetention
FunctionAddr VTableAddr Value
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...
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr StringRef IgnoreBundleTag
Tag in operand bundle indicating that this bundle should be ignored.
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.
LLVM_ABI bool isAssumeWithEmptyBundle(const AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
LLVM_ABI RetainedKnowledge getKnowledgeFromBundle(AssumeInst &Assume, const CallBase::BundleOpInfo &BOI)
This extracts the Knowledge from an element of an operand bundle.
auto dyn_cast_or_null(const Y &Val)
void sort(IteratorTy Start, IteratorTy End)
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.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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...
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.
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Look up or compute a value in the value map.
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
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.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Represent one information held inside an operand bundle of an llvm.assume.
Attribute::AttrKind AttrKind