• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
9 #define DEBUG_TYPE "assume-builder"
10 
11 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
12 #include "llvm/ADT/DepthFirstIterator.h"
13 #include "llvm/ADT/MapVector.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Analysis/AssumeBundleQueries.h"
16 #include "llvm/Analysis/AssumptionCache.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/InstIterator.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/InitializePasses.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/DebugCounter.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 
28 using namespace llvm;
29 
30 cl::opt<bool> ShouldPreserveAllAttributes(
31     "assume-preserve-all", cl::init(false), cl::Hidden,
32     cl::desc("enable preservation of all attrbitues. even those that are "
33              "unlikely to be usefull"));
34 
35 cl::opt<bool> EnableKnowledgeRetention(
36     "enable-knowledge-retention", cl::init(false), cl::Hidden,
37     cl::desc(
38         "enable preservation of attributes throughout code transformation"));
39 
40 STATISTIC(NumAssumeBuilt, "Number of assume built by the assume builder");
41 STATISTIC(NumBundlesInAssumes, "Total number of Bundles in the assume built");
42 STATISTIC(NumAssumesMerged,
43           "Number of assume merged by the assume simplify pass");
44 STATISTIC(NumAssumesRemoved,
45           "Number of assume removed by the assume simplify pass");
46 
47 DEBUG_COUNTER(BuildAssumeCounter, "assume-builder-counter",
48               "Controls which assumes gets created");
49 
50 namespace {
51 
isUsefullToPreserve(Attribute::AttrKind Kind)52 bool isUsefullToPreserve(Attribute::AttrKind Kind) {
53   switch (Kind) {
54     case Attribute::NonNull:
55     case Attribute::NoUndef:
56     case Attribute::Alignment:
57     case Attribute::Dereferenceable:
58     case Attribute::DereferenceableOrNull:
59     case Attribute::Cold:
60       return true;
61     default:
62       return false;
63   }
64 }
65 
66 /// This function will try to transform the given knowledge into a more
67 /// canonical one. the canonical knowledge maybe the given one.
canonicalizedKnowledge(RetainedKnowledge RK,Module * M)68 RetainedKnowledge canonicalizedKnowledge(RetainedKnowledge RK, Module *M) {
69   switch (RK.AttrKind) {
70   default:
71     return RK;
72   case Attribute::NonNull:
73     RK.WasOn = getUnderlyingObject(RK.WasOn);
74     return RK;
75   case Attribute::Alignment: {
76     Value *V = RK.WasOn->stripInBoundsOffsets([&](const Value *Strip) {
77       if (auto *GEP = dyn_cast<GEPOperator>(Strip))
78         RK.ArgValue =
79             MinAlign(RK.ArgValue,
80                      GEP->getMaxPreservedAlignment(M->getDataLayout()).value());
81     });
82     RK.WasOn = V;
83     return RK;
84   }
85   case Attribute::Dereferenceable:
86   case Attribute::DereferenceableOrNull: {
87     int64_t Offset = 0;
88     Value *V = GetPointerBaseWithConstantOffset(
89         RK.WasOn, Offset, M->getDataLayout(), /*AllowNonInBounds*/ false);
90     if (Offset < 0)
91       return RK;
92     RK.ArgValue = RK.ArgValue + Offset;
93     RK.WasOn = V;
94   }
95   }
96   return RK;
97 }
98 
99 /// This class contain all knowledge that have been gather while building an
100 /// llvm.assume and the function to manipulate it.
101 struct AssumeBuilderState {
102   Module *M;
103 
104   using MapKey = std::pair<Value *, Attribute::AttrKind>;
105   SmallMapVector<MapKey, unsigned, 8> AssumedKnowledgeMap;
106   Instruction *InstBeingRemoved = nullptr;
107   AssumptionCache* AC = nullptr;
108   DominatorTree* DT = nullptr;
109 
AssumeBuilderState__anon9c9316740111::AssumeBuilderState110   AssumeBuilderState(Module *M, Instruction *I = nullptr,
111                      AssumptionCache *AC = nullptr, DominatorTree *DT = nullptr)
112       : M(M), InstBeingRemoved(I), AC(AC), DT(DT) {}
113 
tryToPreserveWithoutAddingAssume__anon9c9316740111::AssumeBuilderState114   bool tryToPreserveWithoutAddingAssume(RetainedKnowledge RK) {
115     if (!InstBeingRemoved || !RK.WasOn)
116       return false;
117     bool HasBeenPreserved = false;
118     Use* ToUpdate = nullptr;
119     getKnowledgeForValue(
120         RK.WasOn, {RK.AttrKind}, AC,
121         [&](RetainedKnowledge RKOther, Instruction *Assume,
122             const CallInst::BundleOpInfo *Bundle) {
123           if (!isValidAssumeForContext(Assume, InstBeingRemoved, DT))
124             return false;
125           if (RKOther.ArgValue >= RK.ArgValue) {
126             HasBeenPreserved = true;
127             return true;
128           } else if (isValidAssumeForContext(InstBeingRemoved, Assume,
129                                              DT)) {
130             HasBeenPreserved = true;
131             IntrinsicInst *Intr = cast<IntrinsicInst>(Assume);
132             ToUpdate = &Intr->op_begin()[Bundle->Begin + ABA_Argument];
133             return true;
134           }
135           return false;
136         });
137     if (ToUpdate)
138       ToUpdate->set(
139           ConstantInt::get(Type::getInt64Ty(M->getContext()), RK.ArgValue));
140     return HasBeenPreserved;
141   }
142 
isKnowledgeWorthPreserving__anon9c9316740111::AssumeBuilderState143   bool isKnowledgeWorthPreserving(RetainedKnowledge RK) {
144     if (!RK)
145       return false;
146     if (!RK.WasOn)
147       return true;
148     if (RK.WasOn->getType()->isPointerTy()) {
149       Value *UnderlyingPtr = getUnderlyingObject(RK.WasOn);
150       if (isa<AllocaInst>(UnderlyingPtr) || isa<GlobalValue>(UnderlyingPtr))
151         return false;
152     }
153     if (auto *Arg = dyn_cast<Argument>(RK.WasOn)) {
154       if (Arg->hasAttribute(RK.AttrKind) &&
155           (!Attribute::doesAttrKindHaveArgument(RK.AttrKind) ||
156            Arg->getAttribute(RK.AttrKind).getValueAsInt() >= RK.ArgValue))
157         return false;
158       return true;
159     }
160     if (auto *Inst = dyn_cast<Instruction>(RK.WasOn))
161       if (wouldInstructionBeTriviallyDead(Inst)) {
162         if (RK.WasOn->use_empty())
163           return false;
164         Use *SingleUse = RK.WasOn->getSingleUndroppableUse();
165         if (SingleUse && SingleUse->getUser() == InstBeingRemoved)
166           return false;
167       }
168     return true;
169   }
170 
addKnowledge__anon9c9316740111::AssumeBuilderState171   void addKnowledge(RetainedKnowledge RK) {
172     RK = canonicalizedKnowledge(RK, M);
173 
174     if (!isKnowledgeWorthPreserving(RK))
175       return;
176 
177     if (tryToPreserveWithoutAddingAssume(RK))
178       return;
179     MapKey Key{RK.WasOn, RK.AttrKind};
180     auto Lookup = AssumedKnowledgeMap.find(Key);
181     if (Lookup == AssumedKnowledgeMap.end()) {
182       AssumedKnowledgeMap[Key] = RK.ArgValue;
183       return;
184     }
185     assert(((Lookup->second == 0 && RK.ArgValue == 0) ||
186             (Lookup->second != 0 && RK.ArgValue != 0)) &&
187            "inconsistent argument value");
188 
189     /// This is only desirable because for all attributes taking an argument
190     /// higher is better.
191     Lookup->second = std::max(Lookup->second, RK.ArgValue);
192   }
193 
addAttribute__anon9c9316740111::AssumeBuilderState194   void addAttribute(Attribute Attr, Value *WasOn) {
195     if (Attr.isTypeAttribute() || Attr.isStringAttribute() ||
196         (!ShouldPreserveAllAttributes &&
197          !isUsefullToPreserve(Attr.getKindAsEnum())))
198       return;
199     unsigned AttrArg = 0;
200     if (Attr.isIntAttribute())
201       AttrArg = Attr.getValueAsInt();
202     addKnowledge({Attr.getKindAsEnum(), AttrArg, WasOn});
203   }
204 
addCall__anon9c9316740111::AssumeBuilderState205   void addCall(const CallBase *Call) {
206     auto addAttrList = [&](AttributeList AttrList) {
207       for (unsigned Idx = AttributeList::FirstArgIndex;
208            Idx < AttrList.getNumAttrSets(); Idx++)
209         for (Attribute Attr : AttrList.getAttributes(Idx))
210           addAttribute(Attr, Call->getArgOperand(Idx - 1));
211       for (Attribute Attr : AttrList.getFnAttributes())
212         addAttribute(Attr, nullptr);
213     };
214     addAttrList(Call->getAttributes());
215     if (Function *Fn = Call->getCalledFunction())
216       addAttrList(Fn->getAttributes());
217   }
218 
build__anon9c9316740111::AssumeBuilderState219   IntrinsicInst *build() {
220     if (AssumedKnowledgeMap.empty())
221       return nullptr;
222     if (!DebugCounter::shouldExecute(BuildAssumeCounter))
223       return nullptr;
224     Function *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume);
225     LLVMContext &C = M->getContext();
226     SmallVector<OperandBundleDef, 8> OpBundle;
227     for (auto &MapElem : AssumedKnowledgeMap) {
228       SmallVector<Value *, 2> Args;
229       if (MapElem.first.first)
230         Args.push_back(MapElem.first.first);
231 
232       /// This is only valid because for all attribute that currently exist a
233       /// value of 0 is useless. and should not be preserved.
234       if (MapElem.second)
235         Args.push_back(ConstantInt::get(Type::getInt64Ty(M->getContext()),
236                                         MapElem.second));
237       OpBundle.push_back(OperandBundleDefT<Value *>(
238           std::string(Attribute::getNameFromAttrKind(MapElem.first.second)),
239           Args));
240       NumBundlesInAssumes++;
241     }
242     NumAssumeBuilt++;
243     return cast<IntrinsicInst>(CallInst::Create(
244         FnAssume, ArrayRef<Value *>({ConstantInt::getTrue(C)}), OpBundle));
245   }
246 
addAccessedPtr__anon9c9316740111::AssumeBuilderState247   void addAccessedPtr(Instruction *MemInst, Value *Pointer, Type *AccType,
248                       MaybeAlign MA) {
249     unsigned DerefSize = MemInst->getModule()
250                              ->getDataLayout()
251                              .getTypeStoreSize(AccType)
252                              .getKnownMinSize();
253     if (DerefSize != 0) {
254       addKnowledge({Attribute::Dereferenceable, DerefSize, Pointer});
255       if (!NullPointerIsDefined(MemInst->getFunction(),
256                                 Pointer->getType()->getPointerAddressSpace()))
257         addKnowledge({Attribute::NonNull, 0u, Pointer});
258     }
259     if (MA.valueOrOne() > 1)
260       addKnowledge(
261           {Attribute::Alignment, unsigned(MA.valueOrOne().value()), Pointer});
262   }
263 
addInstruction__anon9c9316740111::AssumeBuilderState264   void addInstruction(Instruction *I) {
265     if (auto *Call = dyn_cast<CallBase>(I))
266       return addCall(Call);
267     if (auto *Load = dyn_cast<LoadInst>(I))
268       return addAccessedPtr(I, Load->getPointerOperand(), Load->getType(),
269                             Load->getAlign());
270     if (auto *Store = dyn_cast<StoreInst>(I))
271       return addAccessedPtr(I, Store->getPointerOperand(),
272                             Store->getValueOperand()->getType(),
273                             Store->getAlign());
274     // TODO: Add support for the other Instructions.
275     // TODO: Maybe we should look around and merge with other llvm.assume.
276   }
277 };
278 
279 } // namespace
280 
buildAssumeFromInst(Instruction * I)281 IntrinsicInst *llvm::buildAssumeFromInst(Instruction *I) {
282   if (!EnableKnowledgeRetention)
283     return nullptr;
284   AssumeBuilderState Builder(I->getModule());
285   Builder.addInstruction(I);
286   return Builder.build();
287 }
288 
salvageKnowledge(Instruction * I,AssumptionCache * AC,DominatorTree * DT)289 void llvm::salvageKnowledge(Instruction *I, AssumptionCache *AC,
290                             DominatorTree *DT) {
291   if (!EnableKnowledgeRetention || I->isTerminator())
292     return;
293   AssumeBuilderState Builder(I->getModule(), I, AC, DT);
294   Builder.addInstruction(I);
295   if (IntrinsicInst *Intr = Builder.build()) {
296     Intr->insertBefore(I);
297     if (AC)
298       AC->registerAssumption(Intr);
299   }
300 }
301 
302 namespace {
303 
304 struct AssumeSimplify {
305   Function &F;
306   AssumptionCache &AC;
307   DominatorTree *DT;
308   LLVMContext &C;
309   SmallDenseSet<IntrinsicInst *> CleanupToDo;
310   StringMapEntry<uint32_t> *IgnoreTag;
311   SmallDenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 4>, 8> BBToAssume;
312   bool MadeChange = false;
313 
AssumeSimplify__anon9c9316740511::AssumeSimplify314   AssumeSimplify(Function &F, AssumptionCache &AC, DominatorTree *DT,
315                  LLVMContext &C)
316       : F(F), AC(AC), DT(DT), C(C),
317         IgnoreTag(C.getOrInsertBundleTag(IgnoreBundleTag)) {}
318 
buildMapping__anon9c9316740511::AssumeSimplify319   void buildMapping(bool FilterBooleanArgument) {
320     BBToAssume.clear();
321     for (Value *V : AC.assumptions()) {
322       if (!V)
323         continue;
324       IntrinsicInst *Assume = cast<IntrinsicInst>(V);
325       if (FilterBooleanArgument) {
326         auto *Arg = dyn_cast<ConstantInt>(Assume->getOperand(0));
327         if (!Arg || Arg->isZero())
328           continue;
329       }
330       BBToAssume[Assume->getParent()].push_back(Assume);
331     }
332 
333     for (auto &Elem : BBToAssume) {
334       llvm::sort(Elem.second,
335                  [](const IntrinsicInst *LHS, const IntrinsicInst *RHS) {
336                    return LHS->comesBefore(RHS);
337                  });
338     }
339   }
340 
341   /// Remove all asumes in CleanupToDo if there boolean argument is true and
342   /// ForceCleanup is set or the assume doesn't hold valuable knowledge.
RunCleanup__anon9c9316740511::AssumeSimplify343   void RunCleanup(bool ForceCleanup) {
344     for (IntrinsicInst *Assume : CleanupToDo) {
345       auto *Arg = dyn_cast<ConstantInt>(Assume->getOperand(0));
346       if (!Arg || Arg->isZero() ||
347           (!ForceCleanup && !isAssumeWithEmptyBundle(*Assume)))
348         continue;
349       MadeChange = true;
350       if (ForceCleanup)
351         NumAssumesMerged++;
352       else
353         NumAssumesRemoved++;
354       Assume->eraseFromParent();
355     }
356     CleanupToDo.clear();
357   }
358 
359   /// Remove knowledge stored in assume when it is already know by an attribute
360   /// or an other assume. This can when valid update an existing knowledge in an
361   /// attribute or an other assume.
dropRedundantKnowledge__anon9c9316740511::AssumeSimplify362   void dropRedundantKnowledge() {
363     struct MapValue {
364       IntrinsicInst *Assume;
365       unsigned ArgValue;
366       CallInst::BundleOpInfo *BOI;
367     };
368     buildMapping(false);
369     SmallDenseMap<std::pair<Value *, Attribute::AttrKind>,
370                   SmallVector<MapValue, 2>, 16>
371         Knowledge;
372     for (BasicBlock *BB : depth_first(&F))
373       for (Value *V : BBToAssume[BB]) {
374         if (!V)
375           continue;
376         IntrinsicInst *Assume = cast<IntrinsicInst>(V);
377         for (CallInst::BundleOpInfo &BOI : Assume->bundle_op_infos()) {
378           auto RemoveFromAssume = [&]() {
379             CleanupToDo.insert(Assume);
380             if (BOI.Begin != BOI.End) {
381               Use *U = &Assume->op_begin()[BOI.Begin + ABA_WasOn];
382               U->set(UndefValue::get(U->get()->getType()));
383             }
384             BOI.Tag = IgnoreTag;
385           };
386           if (BOI.Tag == IgnoreTag) {
387             CleanupToDo.insert(Assume);
388             continue;
389           }
390           RetainedKnowledge RK = getKnowledgeFromBundle(*Assume, BOI);
391           if (auto *Arg = dyn_cast_or_null<Argument>(RK.WasOn)) {
392             bool HasSameKindAttr = Arg->hasAttribute(RK.AttrKind);
393             if (HasSameKindAttr)
394               if (!Attribute::doesAttrKindHaveArgument(RK.AttrKind) ||
395                   Arg->getAttribute(RK.AttrKind).getValueAsInt() >=
396                       RK.ArgValue) {
397                 RemoveFromAssume();
398                 continue;
399               }
400             if (isValidAssumeForContext(
401                     Assume, &*F.getEntryBlock().getFirstInsertionPt()) ||
402                 Assume == &*F.getEntryBlock().getFirstInsertionPt()) {
403               if (HasSameKindAttr)
404                 Arg->removeAttr(RK.AttrKind);
405               Arg->addAttr(Attribute::get(C, RK.AttrKind, RK.ArgValue));
406               MadeChange = true;
407               RemoveFromAssume();
408               continue;
409             }
410           }
411           auto &Lookup = Knowledge[{RK.WasOn, RK.AttrKind}];
412           for (MapValue &Elem : Lookup) {
413             if (!isValidAssumeForContext(Elem.Assume, Assume, DT))
414               continue;
415             if (Elem.ArgValue >= RK.ArgValue) {
416               RemoveFromAssume();
417               continue;
418             } else if (isValidAssumeForContext(Assume, Elem.Assume, DT)) {
419               Elem.Assume->op_begin()[Elem.BOI->Begin + ABA_Argument].set(
420                   ConstantInt::get(Type::getInt64Ty(C), RK.ArgValue));
421               MadeChange = true;
422               RemoveFromAssume();
423               continue;
424             }
425           }
426           Lookup.push_back({Assume, RK.ArgValue, &BOI});
427         }
428       }
429   }
430 
431   using MergeIterator = SmallVectorImpl<IntrinsicInst *>::iterator;
432 
433   /// Merge all Assumes from Begin to End in and insert the resulting assume as
434   /// high as possible in the basicblock.
mergeRange__anon9c9316740511::AssumeSimplify435   void mergeRange(BasicBlock *BB, MergeIterator Begin, MergeIterator End) {
436     if (Begin == End || std::next(Begin) == End)
437       return;
438     /// Provide no additional information so that AssumeBuilderState doesn't
439     /// try to do any punning since it already has been done better.
440     AssumeBuilderState Builder(F.getParent());
441 
442     /// For now it is initialized to the best value it could have
443     Instruction *InsertPt = BB->getFirstNonPHI();
444     if (isa<LandingPadInst>(InsertPt))
445       InsertPt = InsertPt->getNextNode();
446     for (IntrinsicInst *I : make_range(Begin, End)) {
447       CleanupToDo.insert(I);
448       for (CallInst::BundleOpInfo &BOI : I->bundle_op_infos()) {
449         RetainedKnowledge RK = getKnowledgeFromBundle(*I, BOI);
450         if (!RK)
451           continue;
452         Builder.addKnowledge(RK);
453         if (auto *I = dyn_cast_or_null<Instruction>(RK.WasOn))
454           if (I->getParent() == InsertPt->getParent() &&
455               (InsertPt->comesBefore(I) || InsertPt == I))
456             InsertPt = I->getNextNode();
457       }
458     }
459 
460     /// Adjust InsertPt if it is before Begin, since mergeAssumes only
461     /// guarantees we can place the resulting assume between Begin and End.
462     if (InsertPt->comesBefore(*Begin))
463       for (auto It = (*Begin)->getIterator(), E = InsertPt->getIterator();
464            It != E; --It)
465         if (!isGuaranteedToTransferExecutionToSuccessor(&*It)) {
466           InsertPt = It->getNextNode();
467           break;
468         }
469     IntrinsicInst *MergedAssume = Builder.build();
470     if (!MergedAssume)
471       return;
472     MadeChange = true;
473     MergedAssume->insertBefore(InsertPt);
474     AC.registerAssumption(MergedAssume);
475   }
476 
477   /// Merge assume when they are in the same BasicBlock and for all instruction
478   /// between them isGuaranteedToTransferExecutionToSuccessor returns true.
mergeAssumes__anon9c9316740511::AssumeSimplify479   void mergeAssumes() {
480     buildMapping(true);
481 
482     SmallVector<MergeIterator, 4> SplitPoints;
483     for (auto &Elem : BBToAssume) {
484       SmallVectorImpl<IntrinsicInst *> &AssumesInBB = Elem.second;
485       if (AssumesInBB.size() < 2)
486         continue;
487       /// AssumesInBB is already sorted by order in the block.
488 
489       BasicBlock::iterator It = AssumesInBB.front()->getIterator();
490       BasicBlock::iterator E = AssumesInBB.back()->getIterator();
491       SplitPoints.push_back(AssumesInBB.begin());
492       MergeIterator LastSplit = AssumesInBB.begin();
493       for (; It != E; ++It)
494         if (!isGuaranteedToTransferExecutionToSuccessor(&*It)) {
495           for (; (*LastSplit)->comesBefore(&*It); ++LastSplit)
496             ;
497           if (SplitPoints.back() != LastSplit)
498             SplitPoints.push_back(LastSplit);
499         }
500       SplitPoints.push_back(AssumesInBB.end());
501       for (auto SplitIt = SplitPoints.begin();
502            SplitIt != std::prev(SplitPoints.end()); SplitIt++) {
503         mergeRange(Elem.first, *SplitIt, *(SplitIt + 1));
504       }
505       SplitPoints.clear();
506     }
507   }
508 };
509 
simplifyAssumes(Function & F,AssumptionCache * AC,DominatorTree * DT)510 bool simplifyAssumes(Function &F, AssumptionCache *AC, DominatorTree *DT) {
511   AssumeSimplify AS(F, *AC, DT, F.getContext());
512 
513   /// Remove knowledge that is already known by a dominating other assume or an
514   /// attribute.
515   AS.dropRedundantKnowledge();
516 
517   /// Remove assume that are empty.
518   AS.RunCleanup(false);
519 
520   /// Merge assume in the same basicblock when possible.
521   AS.mergeAssumes();
522 
523   /// Remove assume that were merged.
524   AS.RunCleanup(true);
525   return AS.MadeChange;
526 }
527 
528 } // namespace
529 
run(Function & F,FunctionAnalysisManager & AM)530 PreservedAnalyses AssumeSimplifyPass::run(Function &F,
531                                           FunctionAnalysisManager &AM) {
532   if (!EnableKnowledgeRetention)
533     return PreservedAnalyses::all();
534   simplifyAssumes(F, &AM.getResult<AssumptionAnalysis>(F),
535                   AM.getCachedResult<DominatorTreeAnalysis>(F));
536   return PreservedAnalyses::all();
537 }
538 
539 namespace {
540 class AssumeSimplifyPassLegacyPass : public FunctionPass {
541 public:
542   static char ID;
543 
AssumeSimplifyPassLegacyPass()544   AssumeSimplifyPassLegacyPass() : FunctionPass(ID) {
545     initializeAssumeSimplifyPassLegacyPassPass(
546         *PassRegistry::getPassRegistry());
547   }
runOnFunction(Function & F)548   bool runOnFunction(Function &F) override {
549     if (skipFunction(F) || !EnableKnowledgeRetention)
550       return false;
551     AssumptionCache &AC =
552         getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
553     DominatorTreeWrapperPass *DTWP =
554         getAnalysisIfAvailable<DominatorTreeWrapperPass>();
555     return simplifyAssumes(F, &AC, DTWP ? &DTWP->getDomTree() : nullptr);
556   }
557 
getAnalysisUsage(AnalysisUsage & AU) const558   void getAnalysisUsage(AnalysisUsage &AU) const override {
559     AU.addRequired<AssumptionCacheTracker>();
560 
561     AU.setPreservesAll();
562   }
563 };
564 } // namespace
565 
566 char AssumeSimplifyPassLegacyPass::ID = 0;
567 
568 INITIALIZE_PASS_BEGIN(AssumeSimplifyPassLegacyPass, "assume-simplify",
569                       "Assume Simplify", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)570 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
571 INITIALIZE_PASS_END(AssumeSimplifyPassLegacyPass, "assume-simplify",
572                     "Assume Simplify", false, false)
573 
574 FunctionPass *llvm::createAssumeSimplifyPass() {
575   return new AssumeSimplifyPassLegacyPass();
576 }
577 
run(Function & F,FunctionAnalysisManager & AM)578 PreservedAnalyses AssumeBuilderPass::run(Function &F,
579                                          FunctionAnalysisManager &AM) {
580   AssumptionCache *AC = &AM.getResult<AssumptionAnalysis>(F);
581   DominatorTree* DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
582   for (Instruction &I : instructions(F))
583     salvageKnowledge(&I, AC, DT);
584   return PreservedAnalyses::all();
585 }
586 
587 namespace {
588 class AssumeBuilderPassLegacyPass : public FunctionPass {
589 public:
590   static char ID;
591 
AssumeBuilderPassLegacyPass()592   AssumeBuilderPassLegacyPass() : FunctionPass(ID) {
593     initializeAssumeBuilderPassLegacyPassPass(*PassRegistry::getPassRegistry());
594   }
runOnFunction(Function & F)595   bool runOnFunction(Function &F) override {
596     AssumptionCache &AC =
597         getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
598     DominatorTreeWrapperPass *DTWP =
599         getAnalysisIfAvailable<DominatorTreeWrapperPass>();
600     for (Instruction &I : instructions(F))
601       salvageKnowledge(&I, &AC, DTWP ? &DTWP->getDomTree() : nullptr);
602     return true;
603   }
604 
getAnalysisUsage(AnalysisUsage & AU) const605   void getAnalysisUsage(AnalysisUsage &AU) const override {
606     AU.addRequired<AssumptionCacheTracker>();
607 
608     AU.setPreservesAll();
609   }
610 };
611 } // namespace
612 
613 char AssumeBuilderPassLegacyPass::ID = 0;
614 
615 INITIALIZE_PASS_BEGIN(AssumeBuilderPassLegacyPass, "assume-builder",
616                       "Assume Builder", false, false)
617 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
618 INITIALIZE_PASS_END(AssumeBuilderPassLegacyPass, "assume-builder",
619                     "Assume Builder", false, false)
620