1 //===- Attributor.cpp - Module-wide attribute deduction -------------------===//
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 // This file implements an inter procedural pass that deduces and/or propagating
10 // attributes. This is done in an abstract interpretation style fixpoint
11 // iteration. See the Attributor.h file comment and the class descriptions in
12 // that file for more information.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/IPO/Attributor.h"
17 
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/EHPersonalities.h"
26 #include "llvm/Analysis/GlobalsModRef.h"
27 #include "llvm/Analysis/Loads.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/Argument.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/InstIterator.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 
40 #include <cassert>
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "attributor"
45 
46 STATISTIC(NumFnWithExactDefinition,
47           "Number of function with exact definitions");
48 STATISTIC(NumFnWithoutExactDefinition,
49           "Number of function without exact definitions");
50 STATISTIC(NumAttributesTimedOut,
51           "Number of abstract attributes timed out before fixpoint");
52 STATISTIC(NumAttributesValidFixpoint,
53           "Number of abstract attributes in a valid fixpoint state");
54 STATISTIC(NumAttributesManifested,
55           "Number of abstract attributes manifested in IR");
56 
57 // Some helper macros to deal with statistics tracking.
58 //
59 // Usage:
60 // For simple IR attribute tracking overload trackStatistics in the abstract
61 // attribute and choose the right STATS_DECL_AND_TRACK_********* macro,
62 // e.g.,:
63 //  void trackStatistics() const override {
64 //    STATS_DECL_AND_TRACK_ARG_ATTR(returned)
65 //  }
66 // If there is a single "increment" side one can use the macro
67 // STATS_DECL_AND_TRACK with a custom message. If there are multiple increment
68 // sides, STATS_DECL and STATS_TRACK can also be used separatly.
69 //
70 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME)                                     \
71   ("Number of " #TYPE " marked '" #NAME "'")
72 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
73 #define STATS_DECL(NAME, TYPE, MSG) STATISTIC(BUILD_STAT_NAME(NAME, TYPE), MSG);
74 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
75 #define STATS_DECL_AND_TRACK(NAME, TYPE, MSG)                                  \
76   STATS_DECL(NAME, TYPE, MSG)                                                  \
77   STATS_TRACK(NAME, TYPE)
78 #define STATS_DECL_AND_TRACK_ARG_ATTR(NAME)                                    \
79   STATS_DECL_AND_TRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
80 #define STATS_DECL_AND_TRACK_CSARG_ATTR(NAME)                                  \
81   STATS_DECL_AND_TRACK(NAME, CSArguments,                                      \
82                        BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
83 #define STATS_DECL_AND_TRACK_FN_ATTR(NAME)                                     \
84   STATS_DECL_AND_TRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
85 #define STATS_DECL_AND_TRACK_FNRET_ATTR(NAME)                                  \
86   STATS_DECL_AND_TRACK(NAME, FunctionReturn,                                   \
87                        BUILD_STAT_MSG_IR_ATTR(function returns, NAME));
88 
89 // TODO: Determine a good default value.
90 //
91 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
92 // (when run with the first 5 abstract attributes). The results also indicate
93 // that we never reach 32 iterations but always find a fixpoint sooner.
94 //
95 // This will become more evolved once we perform two interleaved fixpoint
96 // iterations: bottom-up and top-down.
97 static cl::opt<unsigned>
98     MaxFixpointIterations("attributor-max-iterations", cl::Hidden,
99                           cl::desc("Maximal number of fixpoint iterations."),
100                           cl::init(32));
101 
102 static cl::opt<bool> DisableAttributor(
103     "attributor-disable", cl::Hidden,
104     cl::desc("Disable the attributor inter-procedural deduction pass."),
105     cl::init(true));
106 
107 static cl::opt<bool> VerifyAttributor(
108     "attributor-verify", cl::Hidden,
109     cl::desc("Verify the Attributor deduction and "
110              "manifestation of attributes -- may issue false-positive errors"),
111     cl::init(false));
112 
113 /// Logic operators for the change status enum class.
114 ///
115 ///{
116 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) {
117   return l == ChangeStatus::CHANGED ? l : r;
118 }
119 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) {
120   return l == ChangeStatus::UNCHANGED ? l : r;
121 }
122 ///}
123 
124 template <typename StateTy>
125 using followValueCB_t = std::function<bool(Value *, StateTy &State)>;
126 template <typename StateTy>
127 using visitValueCB_t = std::function<void(Value *, StateTy &State)>;
128 
129 /// Recursively visit all values that might become \p InitV at some point. This
130 /// will be done by looking through cast instructions, selects, phis, and calls
131 /// with the "returned" attribute. The callback \p FollowValueCB is asked before
132 /// a potential origin value is looked at. If no \p FollowValueCB is passed, a
133 /// default one is used that will make sure we visit every value only once. Once
134 /// we cannot look through the value any further, the callback \p VisitValueCB
135 /// is invoked and passed the current value and the \p State. To limit how much
136 /// effort is invested, we will never visit more than \p MaxValues values.
137 template <typename StateTy>
138 static bool genericValueTraversal(
139     Value *InitV, StateTy &State, visitValueCB_t<StateTy> &VisitValueCB,
140     followValueCB_t<StateTy> *FollowValueCB = nullptr, int MaxValues = 8) {
141 
142   SmallPtrSet<Value *, 16> Visited;
143   followValueCB_t<bool> DefaultFollowValueCB = [&](Value *Val, bool &) {
144     return Visited.insert(Val).second;
145   };
146 
147   if (!FollowValueCB)
148     FollowValueCB = &DefaultFollowValueCB;
149 
150   SmallVector<Value *, 16> Worklist;
151   Worklist.push_back(InitV);
152 
153   int Iteration = 0;
154   do {
155     Value *V = Worklist.pop_back_val();
156 
157     // Check if we should process the current value. To prevent endless
158     // recursion keep a record of the values we followed!
159     if (!(*FollowValueCB)(V, State))
160       continue;
161 
162     // Make sure we limit the compile time for complex expressions.
163     if (Iteration++ >= MaxValues)
164       return false;
165 
166     // Explicitly look through calls with a "returned" attribute if we do
167     // not have a pointer as stripPointerCasts only works on them.
168     if (V->getType()->isPointerTy()) {
169       V = V->stripPointerCasts();
170     } else {
171       CallSite CS(V);
172       if (CS && CS.getCalledFunction()) {
173         Value *NewV = nullptr;
174         for (Argument &Arg : CS.getCalledFunction()->args())
175           if (Arg.hasReturnedAttr()) {
176             NewV = CS.getArgOperand(Arg.getArgNo());
177             break;
178           }
179         if (NewV) {
180           Worklist.push_back(NewV);
181           continue;
182         }
183       }
184     }
185 
186     // Look through select instructions, visit both potential values.
187     if (auto *SI = dyn_cast<SelectInst>(V)) {
188       Worklist.push_back(SI->getTrueValue());
189       Worklist.push_back(SI->getFalseValue());
190       continue;
191     }
192 
193     // Look through phi nodes, visit all operands.
194     if (auto *PHI = dyn_cast<PHINode>(V)) {
195       Worklist.append(PHI->op_begin(), PHI->op_end());
196       continue;
197     }
198 
199     // Once a leaf is reached we inform the user through the callback.
200     VisitValueCB(V, State);
201   } while (!Worklist.empty());
202 
203   // All values have been visited.
204   return true;
205 }
206 
207 /// Return true if \p New is equal or worse than \p Old.
208 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
209   if (!Old.isIntAttribute())
210     return true;
211 
212   return Old.getValueAsInt() >= New.getValueAsInt();
213 }
214 
215 /// Return true if the information provided by \p Attr was added to the
216 /// attribute list \p Attrs. This is only the case if it was not already present
217 /// in \p Attrs at the position describe by \p PK and \p AttrIdx.
218 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
219                              AttributeList &Attrs, int AttrIdx) {
220 
221   if (Attr.isEnumAttribute()) {
222     Attribute::AttrKind Kind = Attr.getKindAsEnum();
223     if (Attrs.hasAttribute(AttrIdx, Kind))
224       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
225         return false;
226     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
227     return true;
228   }
229   if (Attr.isStringAttribute()) {
230     StringRef Kind = Attr.getKindAsString();
231     if (Attrs.hasAttribute(AttrIdx, Kind))
232       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
233         return false;
234     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
235     return true;
236   }
237   if (Attr.isIntAttribute()) {
238     Attribute::AttrKind Kind = Attr.getKindAsEnum();
239     if (Attrs.hasAttribute(AttrIdx, Kind))
240       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
241         return false;
242     Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind);
243     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
244     return true;
245   }
246 
247   llvm_unreachable("Expected enum or string attribute!");
248 }
249 
250 ChangeStatus AbstractAttribute::update(Attributor &A,
251                                        InformationCache &InfoCache) {
252   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
253   if (getState().isAtFixpoint())
254     return HasChanged;
255 
256   LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
257 
258   HasChanged = updateImpl(A, InfoCache);
259 
260   LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
261                     << "\n");
262 
263   return HasChanged;
264 }
265 
266 ChangeStatus
267 IRAttributeManifest::manifestAttrs(Attributor &A, IRPosition &IRP,
268                                    const ArrayRef<Attribute> &DeducedAttrs) {
269   assert(IRP.getAssociatedValue() &&
270          "Attempted to manifest an attribute without associated value!");
271 
272   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
273 
274   Function &ScopeFn = IRP.getAnchorScope();
275   LLVMContext &Ctx = ScopeFn.getContext();
276   IRPosition::Kind PK = IRP.getPositionKind();
277 
278   // In the following some generic code that will manifest attributes in
279   // DeducedAttrs if they improve the current IR. Due to the different
280   // annotation positions we use the underlying AttributeList interface.
281 
282   AttributeList Attrs;
283   switch (PK) {
284   case IRPosition::IRP_ARGUMENT:
285   case IRPosition::IRP_FUNCTION:
286   case IRPosition::IRP_RETURNED:
287     Attrs = ScopeFn.getAttributes();
288     break;
289   case IRPosition::IRP_CALL_SITE_ARGUMENT:
290     Attrs = ImmutableCallSite(&IRP.getAnchorValue()).getAttributes();
291     break;
292   }
293 
294   for (const Attribute &Attr : DeducedAttrs) {
295     if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx()))
296       continue;
297 
298     HasChanged = ChangeStatus::CHANGED;
299   }
300 
301   if (HasChanged == ChangeStatus::UNCHANGED)
302     return HasChanged;
303 
304   switch (PK) {
305   case IRPosition::IRP_ARGUMENT:
306   case IRPosition::IRP_FUNCTION:
307   case IRPosition::IRP_RETURNED:
308     ScopeFn.setAttributes(Attrs);
309     break;
310   case IRPosition::IRP_CALL_SITE_ARGUMENT:
311     CallSite(&IRP.getAnchorValue()).setAttributes(Attrs);
312   }
313 
314   return HasChanged;
315 }
316 
317 /// -----------------------NoUnwind Function Attribute--------------------------
318 
319 struct AANoUnwindImpl : AANoUnwind {
320   IRPositionConstructorForward(AANoUnwindImpl, AANoUnwind);
321 
322   const std::string getAsStr() const override {
323     return getAssumed() ? "nounwind" : "may-unwind";
324   }
325 
326   /// See AbstractAttribute::updateImpl(...).
327   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
328 };
329 
330 struct AANoUnwindFunction final : public AANoUnwindImpl {
331   AANoUnwindFunction(Function &F) : AANoUnwindImpl(F, IRP_FUNCTION) {}
332 
333   /// See AbstractAttribute::trackStatistics()
334   void trackStatistics() const override {
335     STATS_DECL_AND_TRACK_FN_ATTR(nounwind)
336   }
337 };
338 
339 ChangeStatus AANoUnwindImpl::updateImpl(Attributor &A,
340                                         InformationCache &InfoCache) {
341   Function &F = getAnchorScope();
342 
343   // The map from instruction opcodes to those instructions in the function.
344   auto Opcodes = {
345       (unsigned)Instruction::Invoke,      (unsigned)Instruction::CallBr,
346       (unsigned)Instruction::Call,        (unsigned)Instruction::CleanupRet,
347       (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
348 
349   auto CheckForNoUnwind = [&](Instruction &I) {
350     if (!I.mayThrow())
351       return true;
352 
353     auto *NoUnwindAA = A.getAAFor<AANoUnwind>(*this, I);
354     return NoUnwindAA && NoUnwindAA->isAssumedNoUnwind();
355   };
356 
357   if (!A.checkForAllInstructions(F, CheckForNoUnwind, *this, InfoCache,
358                                  Opcodes))
359     return indicatePessimisticFixpoint();
360 
361   return ChangeStatus::UNCHANGED;
362 }
363 
364 /// --------------------- Function Return Values -------------------------------
365 
366 /// "Attribute" that collects all potential returned values and the return
367 /// instructions that they arise from.
368 ///
369 /// If there is a unique returned value R, the manifest method will:
370 ///   - mark R with the "returned" attribute, if R is an argument.
371 ///
372 /// TODO: We should use liveness during construction of the returned values map
373 ///       and before we set HasOverdefinedReturnedCalls.
374 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState {
375 
376   /// Mapping of values potentially returned by the associated function to the
377   /// return instructions that might return them.
378   DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> ReturnedValues;
379 
380   /// State flags
381   ///
382   ///{
383   bool IsFixed;
384   bool IsValidState;
385   bool HasOverdefinedReturnedCalls;
386   ///}
387 
388   /// Collect values that could become \p V in the set \p Values, each mapped to
389   /// \p ReturnInsts.
390   void collectValuesRecursively(
391       Attributor &A, Value *V, SmallPtrSetImpl<ReturnInst *> &ReturnInsts,
392       DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> &Values) {
393 
394     visitValueCB_t<bool> VisitValueCB = [&](Value *Val, bool &) {
395       assert(!isa<Instruction>(Val) ||
396              &getAnchorScope() == cast<Instruction>(Val)->getFunction());
397       Values[Val].insert(ReturnInsts.begin(), ReturnInsts.end());
398     };
399 
400     bool UnusedBool;
401     bool Success = genericValueTraversal(V, UnusedBool, VisitValueCB);
402 
403     // If we did abort the above traversal we haven't see all the values.
404     // Consequently, we cannot know if the information we would derive is
405     // accurate so we give up early.
406     if (!Success)
407       indicatePessimisticFixpoint();
408   }
409 
410 public:
411   IRPositionConstructorForward(AAReturnedValuesImpl, AAReturnedValues);
412 
413   /// See AbstractAttribute::initialize(...).
414   void initialize(Attributor &A, InformationCache &InfoCache) override {
415     // Reset the state.
416     setAssociatedValue(nullptr);
417     IsFixed = false;
418     IsValidState = true;
419     HasOverdefinedReturnedCalls = false;
420     ReturnedValues.clear();
421 
422     Function &F = getAnchorScope();
423 
424     // The map from instruction opcodes to those instructions in the function.
425     auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
426 
427     // Look through all arguments, if one is marked as returned we are done.
428     for (Argument &Arg : F.args()) {
429       if (Arg.hasReturnedAttr()) {
430 
431         auto &ReturnInstSet = ReturnedValues[&Arg];
432         for (Instruction *RI : OpcodeInstMap[Instruction::Ret])
433           ReturnInstSet.insert(cast<ReturnInst>(RI));
434 
435         indicateOptimisticFixpoint();
436         return;
437       }
438     }
439 
440     // If no argument was marked as returned we look at all return instructions
441     // and collect potentially returned values.
442     for (Instruction *RI : OpcodeInstMap[Instruction::Ret]) {
443       SmallPtrSet<ReturnInst *, 1> RISet({cast<ReturnInst>(RI)});
444       collectValuesRecursively(A, cast<ReturnInst>(RI)->getReturnValue(), RISet,
445                                ReturnedValues);
446     }
447   }
448 
449   /// See AbstractAttribute::manifest(...).
450   ChangeStatus manifest(Attributor &A) override;
451 
452   /// See AbstractAttribute::getState(...).
453   AbstractState &getState() override { return *this; }
454 
455   /// See AbstractAttribute::getState(...).
456   const AbstractState &getState() const override { return *this; }
457 
458   /// See AbstractAttribute::updateImpl(Attributor &A).
459   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
460 
461   /// Return the number of potential return values, -1 if unknown.
462   size_t getNumReturnValues() const {
463     return isValidState() ? ReturnedValues.size() : -1;
464   }
465 
466   /// Return an assumed unique return value if a single candidate is found. If
467   /// there cannot be one, return a nullptr. If it is not clear yet, return the
468   /// Optional::NoneType.
469   Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const;
470 
471   /// See AbstractState::checkForAllReturnedValues(...).
472   bool checkForAllReturnedValuesAndReturnInsts(
473       const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
474           &Pred) const override;
475 
476   /// Pretty print the attribute similar to the IR representation.
477   const std::string getAsStr() const override;
478 
479   /// See AbstractState::isAtFixpoint().
480   bool isAtFixpoint() const override { return IsFixed; }
481 
482   /// See AbstractState::isValidState().
483   bool isValidState() const override { return IsValidState; }
484 
485   /// See AbstractState::indicateOptimisticFixpoint(...).
486   ChangeStatus indicateOptimisticFixpoint() override {
487     IsFixed = true;
488     IsValidState &= true;
489     return ChangeStatus::UNCHANGED;
490   }
491 
492   ChangeStatus indicatePessimisticFixpoint() override {
493     IsFixed = true;
494     IsValidState = false;
495     return ChangeStatus::CHANGED;
496   }
497 };
498 
499 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl {
500   AAReturnedValuesFunction(Function &F)
501       : AAReturnedValuesImpl(F, IRP_FUNCTION) {}
502 
503   /// See AbstractAttribute::trackStatistics()
504   void trackStatistics() const override {
505     STATS_DECL_AND_TRACK_ARG_ATTR(returned)
506   }
507 };
508 
509 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
510   ChangeStatus Changed = ChangeStatus::UNCHANGED;
511 
512   // Bookkeeping.
513   assert(isValidState());
514   STATS_DECL_AND_TRACK(KnownReturnValues, FunctionReturn,
515                        "Number of function with known return values");
516 
517   // Check if we have an assumed unique return value that we could manifest.
518   Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
519 
520   if (!UniqueRV.hasValue() || !UniqueRV.getValue())
521     return Changed;
522 
523   // Bookkeeping.
524   STATS_DECL_AND_TRACK(UniqueReturnValue, FunctionReturn,
525                        "Number of function with unique return");
526 
527   // If the assumed unique return value is an argument, annotate it.
528   if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
529     setAssociatedValue(UniqueRVArg);
530     setAttributeIdx(UniqueRVArg->getArgNo() + AttributeList::FirstArgIndex);
531     Changed = IRAttribute::manifest(A) | Changed;
532   }
533 
534   return Changed;
535 }
536 
537 const std::string AAReturnedValuesImpl::getAsStr() const {
538   return (isAtFixpoint() ? "returns(#" : "may-return(#") +
539          (isValidState() ? std::to_string(getNumReturnValues()) : "?") +
540          ")[OD: " + std::to_string(HasOverdefinedReturnedCalls) + "]";
541 }
542 
543 Optional<Value *>
544 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const {
545   // If checkForAllReturnedValues provides a unique value, ignoring potential
546   // undef values that can also be present, it is assumed to be the actual
547   // return value and forwarded to the caller of this method. If there are
548   // multiple, a nullptr is returned indicating there cannot be a unique
549   // returned value.
550   Optional<Value *> UniqueRV;
551 
552   auto Pred = [&](Value &RV) -> bool {
553     // If we found a second returned value and neither the current nor the saved
554     // one is an undef, there is no unique returned value. Undefs are special
555     // since we can pretend they have any value.
556     if (UniqueRV.hasValue() && UniqueRV != &RV &&
557         !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) {
558       UniqueRV = nullptr;
559       return false;
560     }
561 
562     // Do not overwrite a value with an undef.
563     if (!UniqueRV.hasValue() || !isa<UndefValue>(RV))
564       UniqueRV = &RV;
565 
566     return true;
567   };
568 
569   if (!A.checkForAllReturnedValues(getAnchorScope(), Pred, *this))
570     UniqueRV = nullptr;
571 
572   return UniqueRV;
573 }
574 
575 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
576     const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
577         &Pred) const {
578   if (!isValidState())
579     return false;
580 
581   // Check all returned values but ignore call sites as long as we have not
582   // encountered an overdefined one during an update.
583   for (auto &It : ReturnedValues) {
584     Value *RV = It.first;
585     const SmallPtrSetImpl<ReturnInst *> &RetInsts = It.second;
586 
587     ImmutableCallSite ICS(RV);
588     if (ICS && !HasOverdefinedReturnedCalls)
589       continue;
590 
591     if (!Pred(*RV, RetInsts))
592       return false;
593   }
594 
595   return true;
596 }
597 
598 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A,
599                                               InformationCache &InfoCache) {
600 
601   // Check if we know of any values returned by the associated function,
602   // if not, we are done.
603   if (getNumReturnValues() == 0) {
604     indicateOptimisticFixpoint();
605     return ChangeStatus::UNCHANGED;
606   }
607 
608   // Check if any of the returned values is a call site we can refine.
609   decltype(ReturnedValues) AddRVs;
610   bool HasCallSite = false;
611 
612   // Keep track of any change to trigger updates on dependent attributes.
613   ChangeStatus Changed = ChangeStatus::UNCHANGED;
614 
615   auto *LivenessAA = A.getAAFor<AAIsDead>(*this, getAnchorScope());
616 
617   // Look at all returned call sites.
618   for (auto &It : ReturnedValues) {
619     SmallPtrSet<ReturnInst *, 2> &ReturnInsts = It.second;
620     Value *RV = It.first;
621 
622     LLVM_DEBUG(dbgs() << "[AAReturnedValues] Potentially returned value " << *RV
623                       << "\n");
624 
625     // Only call sites can change during an update, ignore the rest.
626     CallSite RetCS(RV);
627     if (!RetCS)
628       continue;
629 
630     // For now, any call site we see will prevent us from directly fixing the
631     // state. However, if the information on the callees is fixed, the call
632     // sites will be removed and we will fix the information for this state.
633     HasCallSite = true;
634 
635     // Ignore dead ReturnValues.
636     if (LivenessAA &&
637         !LivenessAA->isLiveInstSet(ReturnInsts.begin(), ReturnInsts.end())) {
638       LLVM_DEBUG(dbgs() << "[AAReturnedValues] all returns are assumed dead, "
639                            "skip it for now\n");
640       continue;
641     }
642 
643     // Try to find a assumed unique return value for the called function.
644     auto *RetCSAA = A.getAAFor<AAReturnedValuesImpl>(*this, *RV);
645     if (!RetCSAA) {
646       if (!HasOverdefinedReturnedCalls)
647         Changed = ChangeStatus::CHANGED;
648       HasOverdefinedReturnedCalls = true;
649       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned call site (" << *RV
650                         << ") with " << (RetCSAA ? "invalid" : "no")
651                         << " associated state\n");
652       continue;
653     }
654 
655     // Try to find a assumed unique return value for the called function.
656     Optional<Value *> AssumedUniqueRV = RetCSAA->getAssumedUniqueReturnValue(A);
657 
658     // If no assumed unique return value was found due to the lack of
659     // candidates, we may need to resolve more calls (through more update
660     // iterations) or the called function will not return. Either way, we simply
661     // stick with the call sites as return values. Because there were not
662     // multiple possibilities, we do not treat it as overdefined.
663     if (!AssumedUniqueRV.hasValue())
664       continue;
665 
666     // If multiple, non-refinable values were found, there cannot be a unique
667     // return value for the called function. The returned call is overdefined!
668     if (!AssumedUniqueRV.getValue()) {
669       if (!HasOverdefinedReturnedCalls)
670         Changed = ChangeStatus::CHANGED;
671       HasOverdefinedReturnedCalls = true;
672       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned call site has multiple "
673                            "potentially returned values\n");
674       continue;
675     }
676 
677     LLVM_DEBUG({
678       bool UniqueRVIsKnown = RetCSAA->isAtFixpoint();
679       dbgs() << "[AAReturnedValues] Returned call site "
680              << (UniqueRVIsKnown ? "known" : "assumed")
681              << " unique return value: " << *AssumedUniqueRV << "\n";
682     });
683 
684     // The assumed unique return value.
685     Value *AssumedRetVal = AssumedUniqueRV.getValue();
686 
687     // If the assumed unique return value is an argument, lookup the matching
688     // call site operand and recursively collect new returned values.
689     // If it is not an argument, it is just put into the set of returned values
690     // as we would have already looked through casts, phis, and similar values.
691     if (Argument *AssumedRetArg = dyn_cast<Argument>(AssumedRetVal))
692       collectValuesRecursively(A,
693                                RetCS.getArgOperand(AssumedRetArg->getArgNo()),
694                                ReturnInsts, AddRVs);
695     else
696       AddRVs[AssumedRetVal].insert(ReturnInsts.begin(), ReturnInsts.end());
697   }
698 
699   for (auto &It : AddRVs) {
700     assert(!It.second.empty() && "Entry does not add anything.");
701     auto &ReturnInsts = ReturnedValues[It.first];
702     for (ReturnInst *RI : It.second)
703       if (ReturnInsts.insert(RI).second) {
704         LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value "
705                           << *It.first << " => " << *RI << "\n");
706         Changed = ChangeStatus::CHANGED;
707       }
708   }
709 
710   // If there is no call site in the returned values we are done.
711   if (!HasCallSite) {
712     indicateOptimisticFixpoint();
713     return ChangeStatus::CHANGED;
714   }
715 
716   return Changed;
717 }
718 
719 /// ------------------------ NoSync Function Attribute -------------------------
720 
721 struct AANoSyncImpl : AANoSync {
722   IRPositionConstructorForward(AANoSyncImpl, AANoSync);
723 
724   const std::string getAsStr() const override {
725     return getAssumed() ? "nosync" : "may-sync";
726   }
727 
728   /// See AbstractAttribute::updateImpl(...).
729   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
730 
731   /// Helper function used to determine whether an instruction is non-relaxed
732   /// atomic. In other words, if an atomic instruction does not have unordered
733   /// or monotonic ordering
734   static bool isNonRelaxedAtomic(Instruction *I);
735 
736   /// Helper function used to determine whether an instruction is volatile.
737   static bool isVolatile(Instruction *I);
738 
739   /// Helper function uset to check if intrinsic is volatile (memcpy, memmove,
740   /// memset).
741   static bool isNoSyncIntrinsic(Instruction *I);
742 };
743 
744 struct AANoSyncFunction final : public AANoSyncImpl {
745   AANoSyncFunction(Function &F) : AANoSyncImpl(F, IRP_FUNCTION) {}
746 
747   /// See AbstractAttribute::trackStatistics()
748   void trackStatistics() const override { STATS_DECL_AND_TRACK_FN_ATTR(nosync) }
749 };
750 
751 bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) {
752   if (!I->isAtomic())
753     return false;
754 
755   AtomicOrdering Ordering;
756   switch (I->getOpcode()) {
757   case Instruction::AtomicRMW:
758     Ordering = cast<AtomicRMWInst>(I)->getOrdering();
759     break;
760   case Instruction::Store:
761     Ordering = cast<StoreInst>(I)->getOrdering();
762     break;
763   case Instruction::Load:
764     Ordering = cast<LoadInst>(I)->getOrdering();
765     break;
766   case Instruction::Fence: {
767     auto *FI = cast<FenceInst>(I);
768     if (FI->getSyncScopeID() == SyncScope::SingleThread)
769       return false;
770     Ordering = FI->getOrdering();
771     break;
772   }
773   case Instruction::AtomicCmpXchg: {
774     AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering();
775     AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering();
776     // Only if both are relaxed, than it can be treated as relaxed.
777     // Otherwise it is non-relaxed.
778     if (Success != AtomicOrdering::Unordered &&
779         Success != AtomicOrdering::Monotonic)
780       return true;
781     if (Failure != AtomicOrdering::Unordered &&
782         Failure != AtomicOrdering::Monotonic)
783       return true;
784     return false;
785   }
786   default:
787     llvm_unreachable(
788         "New atomic operations need to be known in the attributor.");
789   }
790 
791   // Relaxed.
792   if (Ordering == AtomicOrdering::Unordered ||
793       Ordering == AtomicOrdering::Monotonic)
794     return false;
795   return true;
796 }
797 
798 /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics.
799 /// FIXME: We should ipmrove the handling of intrinsics.
800 bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) {
801   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
802     switch (II->getIntrinsicID()) {
803     /// Element wise atomic memory intrinsics are can only be unordered,
804     /// therefore nosync.
805     case Intrinsic::memset_element_unordered_atomic:
806     case Intrinsic::memmove_element_unordered_atomic:
807     case Intrinsic::memcpy_element_unordered_atomic:
808       return true;
809     case Intrinsic::memset:
810     case Intrinsic::memmove:
811     case Intrinsic::memcpy:
812       if (!cast<MemIntrinsic>(II)->isVolatile())
813         return true;
814       return false;
815     default:
816       return false;
817     }
818   }
819   return false;
820 }
821 
822 bool AANoSyncImpl::isVolatile(Instruction *I) {
823   assert(!ImmutableCallSite(I) && !isa<CallBase>(I) &&
824          "Calls should not be checked here");
825 
826   switch (I->getOpcode()) {
827   case Instruction::AtomicRMW:
828     return cast<AtomicRMWInst>(I)->isVolatile();
829   case Instruction::Store:
830     return cast<StoreInst>(I)->isVolatile();
831   case Instruction::Load:
832     return cast<LoadInst>(I)->isVolatile();
833   case Instruction::AtomicCmpXchg:
834     return cast<AtomicCmpXchgInst>(I)->isVolatile();
835   default:
836     return false;
837   }
838 }
839 
840 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A,
841                                       InformationCache &InfoCache) {
842   Function &F = getAnchorScope();
843 
844   auto CheckRWInstForNoSync = [&](Instruction &I) {
845     /// We are looking for volatile instructions or Non-Relaxed atomics.
846     /// FIXME: We should ipmrove the handling of intrinsics.
847 
848     ImmutableCallSite ICS(&I);
849     auto *NoSyncAA = A.getAAFor<AANoSyncImpl>(*this, I);
850 
851     if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I))
852       return true;
853 
854     if (ICS && (!NoSyncAA || !NoSyncAA->isAssumedNoSync()) &&
855         !ICS.hasFnAttr(Attribute::NoSync))
856       return false;
857 
858     if (ICS)
859       return true;
860 
861     if (!isVolatile(&I) && !isNonRelaxedAtomic(&I))
862       return true;
863 
864     return false;
865   };
866 
867   auto CheckForNoSync = [&](Instruction &I) {
868     // At this point we handled all read/write effects and they are all
869     // nosync, so they can be skipped.
870     if (I.mayReadOrWriteMemory())
871       return true;
872 
873     // non-convergent and readnone imply nosync.
874     return !ImmutableCallSite(&I).isConvergent();
875   };
876 
877   if (!A.checkForAllReadWriteInstructions(F, CheckRWInstForNoSync, *this,
878                                           InfoCache) ||
879       !A.checkForAllCallLikeInstructions(F, CheckForNoSync, *this, InfoCache))
880     return indicatePessimisticFixpoint();
881 
882   return ChangeStatus::UNCHANGED;
883 }
884 
885 /// ------------------------ No-Free Attributes ----------------------------
886 
887 struct AANoFreeImpl : public AANoFree {
888   IRPositionConstructorForward(AANoFreeImpl, AANoFree);
889 
890   /// See AbstractAttribute::getAsStr().
891   const std::string getAsStr() const override {
892     return getAssumed() ? "nofree" : "may-free";
893   }
894 
895   /// See AbstractAttribute::updateImpl(...).
896   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
897 };
898 
899 struct AANoFreeFunction final : public AANoFreeImpl {
900   AANoFreeFunction(Function &F) : AANoFreeImpl(F, IRP_FUNCTION) {}
901 
902   /// See AbstractAttribute::trackStatistics()
903   void trackStatistics() const override { STATS_DECL_AND_TRACK_FN_ATTR(nofree) }
904 };
905 
906 ChangeStatus AANoFreeImpl::updateImpl(Attributor &A,
907                                       InformationCache &InfoCache) {
908   Function &F = getAnchorScope();
909 
910   auto CheckForNoFree = [&](Instruction &I) {
911     if (ImmutableCallSite(&I).hasFnAttr(Attribute::NoFree))
912       return true;
913 
914     auto *NoFreeAA = A.getAAFor<AANoFreeImpl>(*this, I);
915     return NoFreeAA && NoFreeAA->isAssumedNoFree();
916   };
917 
918   if (!A.checkForAllCallLikeInstructions(F, CheckForNoFree, *this, InfoCache))
919     return indicatePessimisticFixpoint();
920   return ChangeStatus::UNCHANGED;
921 }
922 
923 /// ------------------------ NonNull Argument Attribute ------------------------
924 struct AANonNullImpl : AANonNull {
925   IRPositionConstructorForward(AANonNullImpl, AANonNull);
926 
927   /// See AbstractAttribute::getAsStr().
928   const std::string getAsStr() const override {
929     return getAssumed() ? "nonnull" : "may-null";
930   }
931 
932   /// Generate a predicate that checks if a given value is assumed nonnull.
933   /// The generated function returns true if a value satisfies any of
934   /// following conditions.
935   /// (i) A value is known nonZero(=nonnull).
936   /// (ii) A value is associated with AANonNull and its isAssumedNonNull() is
937   /// true.
938   std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
939   generatePredicate(Attributor &);
940 };
941 
942 std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
943 AANonNullImpl::generatePredicate(Attributor &A) {
944   // FIXME: The `AAReturnedValues` should provide the predicate with the
945   // `ReturnInst` vector as well such that we can use the control flow sensitive
946   // version of `isKnownNonZero`. This should fix `test11` in
947   // `test/Transforms/FunctionAttrs/nonnull.ll`
948 
949   std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred =
950       [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &RetInsts) -> bool {
951     Function &F = getAnchorScope();
952 
953     if (isKnownNonZero(&RV, F.getParent()->getDataLayout()))
954       return true;
955 
956     auto *NonNullAA = A.getAAFor<AANonNull>(*this, RV);
957 
958     ImmutableCallSite ICS(&RV);
959 
960     if ((!NonNullAA || !NonNullAA->isAssumedNonNull()) &&
961         (!ICS || !ICS.hasRetAttr(Attribute::NonNull)))
962       return false;
963 
964     return true;
965   };
966 
967   return Pred;
968 }
969 
970 /// NonNull attribute for function return value.
971 struct AANonNullReturned final : AANonNullImpl {
972   AANonNullReturned(Function &F) : AANonNullImpl(F, IRP_RETURNED) {}
973 
974   /// See AbstractAttribute::initialize(...).
975   void initialize(Attributor &A, InformationCache &InfoCache) override {
976     Function &F = getAnchorScope();
977 
978     // Already nonnull.
979     if (F.getAttributes().hasAttribute(AttributeList::ReturnIndex,
980                                        Attribute::NonNull) ||
981         F.getAttributes().hasAttribute(AttributeList::ReturnIndex,
982                                        Attribute::Dereferenceable))
983       indicateOptimisticFixpoint();
984   }
985 
986   /// See AbstractAttribute::updateImpl(...).
987   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
988 
989   /// See AbstractAttribute::trackStatistics()
990   void trackStatistics() const override {
991     STATS_DECL_AND_TRACK_FNRET_ATTR(nonnull)
992   }
993 };
994 
995 ChangeStatus AANonNullReturned::updateImpl(Attributor &A,
996                                            InformationCache &InfoCache) {
997   Function &F = getAnchorScope();
998 
999   std::function<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> Pred =
1000       this->generatePredicate(A);
1001 
1002   if (!A.checkForAllReturnedValuesAndReturnInsts(F, Pred, *this))
1003     return indicatePessimisticFixpoint();
1004   return ChangeStatus::UNCHANGED;
1005 }
1006 
1007 /// NonNull attribute for function argument.
1008 struct AANonNullArgument final : AANonNullImpl {
1009   AANonNullArgument(Argument &A) : AANonNullImpl(A) {}
1010 
1011   /// See AbstractAttriubute::initialize(...).
1012   void initialize(Attributor &A, InformationCache &InfoCache) override {
1013     Argument *Arg = cast<Argument>(getAssociatedValue());
1014     if (Arg->hasNonNullAttr())
1015       indicateOptimisticFixpoint();
1016   }
1017 
1018   /// See AbstractAttribute::updateImpl(...).
1019   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
1020 
1021   /// See AbstractAttribute::trackStatistics()
1022   void trackStatistics() const override {
1023     STATS_DECL_AND_TRACK_ARG_ATTR(nonnull)
1024   }
1025 };
1026 
1027 /// NonNull attribute for a call site argument.
1028 struct AANonNullCallSiteArgument final : AANonNullImpl {
1029   AANonNullCallSiteArgument(Instruction &I, unsigned ArgNo)
1030       : AANonNullImpl(CallSite(&I).getArgOperand(ArgNo), I, ArgNo) {}
1031 
1032   /// See AbstractAttribute::initialize(...).
1033   void initialize(Attributor &A, InformationCache &InfoCache) override {
1034     CallSite CS(&getAnchorValue());
1035     if (CS.paramHasAttr(getArgNo(), getAttrKind()) ||
1036         CS.paramHasAttr(getArgNo(), Attribute::Dereferenceable) ||
1037         isKnownNonZero(getAssociatedValue(),
1038                        getAnchorScope().getParent()->getDataLayout()))
1039       indicateOptimisticFixpoint();
1040   }
1041 
1042   /// See AbstractAttribute::updateImpl(Attributor &A).
1043   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
1044 
1045   /// See AbstractAttribute::trackStatistics()
1046   void trackStatistics() const override {
1047     STATS_DECL_AND_TRACK_CSARG_ATTR(nonnull)
1048   }
1049 };
1050 
1051 ChangeStatus AANonNullArgument::updateImpl(Attributor &A,
1052                                            InformationCache &InfoCache) {
1053   Function &F = getAnchorScope();
1054   unsigned ArgNo = getArgNo();
1055 
1056   // Callback function
1057   std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) {
1058     assert(CS && "Sanity check: Call site was not initialized properly!");
1059 
1060     auto *NonNullAA =
1061         A.getAAFor<AANonNullImpl>(*this, *CS.getInstruction(), ArgNo);
1062 
1063     // Check that NonNullAA is AANonNullCallSiteArgument.
1064     if (NonNullAA) {
1065       ImmutableCallSite ICS(&NonNullAA->getAnchorValue());
1066       if (ICS && CS.getInstruction() == ICS.getInstruction())
1067         return NonNullAA->isAssumedNonNull();
1068       return false;
1069     }
1070 
1071     if (CS.paramHasAttr(ArgNo, Attribute::NonNull))
1072       return true;
1073 
1074     Value *V = CS.getArgOperand(ArgNo);
1075     if (isKnownNonZero(V, getAnchorScope().getParent()->getDataLayout()))
1076       return true;
1077 
1078     return false;
1079   };
1080   if (!A.checkForAllCallSites(F, CallSiteCheck, *this, true))
1081     return indicatePessimisticFixpoint();
1082   return ChangeStatus::UNCHANGED;
1083 }
1084 
1085 ChangeStatus
1086 AANonNullCallSiteArgument::updateImpl(Attributor &A,
1087                                       InformationCache &InfoCache) {
1088   // NOTE: Never look at the argument of the callee in this method.
1089   //       If we do this, "nonnull" is always deduced because of the assumption.
1090 
1091   Value &V = *getAssociatedValue();
1092 
1093   auto *NonNullAA = A.getAAFor<AANonNull>(*this, V);
1094 
1095   if (!NonNullAA || !NonNullAA->isAssumedNonNull())
1096     return indicatePessimisticFixpoint();
1097 
1098   return ChangeStatus::UNCHANGED;
1099 }
1100 
1101 /// ------------------------ Will-Return Attributes ----------------------------
1102 
1103 struct AAWillReturnImpl : public AAWillReturn {
1104   IRPositionConstructorForward(AAWillReturnImpl, AAWillReturn);
1105 
1106   /// See AbstractAttribute::getAsStr()
1107   const std::string getAsStr() const override {
1108     return getAssumed() ? "willreturn" : "may-noreturn";
1109   }
1110 };
1111 
1112 struct AAWillReturnFunction final : AAWillReturnImpl {
1113   AAWillReturnFunction(Function &F) : AAWillReturnImpl(F, IRP_FUNCTION) {}
1114 
1115   /// See AbstractAttribute::initialize(...).
1116   void initialize(Attributor &A, InformationCache &InfoCache) override;
1117 
1118   /// See AbstractAttribute::updateImpl(...).
1119   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
1120 
1121   /// See AbstractAttribute::trackStatistics()
1122   void trackStatistics() const override {
1123     STATS_DECL_AND_TRACK_FN_ATTR(willreturn)
1124   }
1125 };
1126 
1127 // Helper function that checks whether a function has any cycle.
1128 // TODO: Replace with more efficent code
1129 bool containsCycle(Function &F) {
1130   SmallPtrSet<BasicBlock *, 32> Visited;
1131 
1132   // Traverse BB by dfs and check whether successor is already visited.
1133   for (BasicBlock *BB : depth_first(&F)) {
1134     Visited.insert(BB);
1135     for (auto *SuccBB : successors(BB)) {
1136       if (Visited.count(SuccBB))
1137         return true;
1138     }
1139   }
1140   return false;
1141 }
1142 
1143 // Helper function that checks the function have a loop which might become an
1144 // endless loop
1145 // FIXME: Any cycle is regarded as endless loop for now.
1146 //        We have to allow some patterns.
1147 bool containsPossiblyEndlessLoop(Function &F) { return containsCycle(F); }
1148 
1149 void AAWillReturnFunction::initialize(Attributor &A,
1150                                       InformationCache &InfoCache) {
1151   Function &F = getAnchorScope();
1152 
1153   if (containsPossiblyEndlessLoop(F))
1154     indicatePessimisticFixpoint();
1155 }
1156 
1157 ChangeStatus AAWillReturnFunction::updateImpl(Attributor &A,
1158                                               InformationCache &InfoCache) {
1159   const Function &F = getAnchorScope();
1160   // The map from instruction opcodes to those instructions in the function.
1161 
1162   auto CheckForWillReturn = [&](Instruction &I) {
1163     ImmutableCallSite ICS(&I);
1164     if (ICS.hasFnAttr(Attribute::WillReturn))
1165       return true;
1166 
1167     auto *WillReturnAA = A.getAAFor<AAWillReturn>(*this, I);
1168     if (!WillReturnAA || !WillReturnAA->isAssumedWillReturn())
1169       return false;
1170 
1171     // FIXME: Prohibit any recursion for now.
1172     if (ICS.hasFnAttr(Attribute::NoRecurse))
1173       return true;
1174 
1175     auto *NoRecurseAA = A.getAAFor<AANoRecurse>(*this, I);
1176     return NoRecurseAA && NoRecurseAA->isAssumedNoRecurse();
1177   };
1178 
1179   if (!A.checkForAllCallLikeInstructions(F, CheckForWillReturn, *this,
1180                                          InfoCache))
1181     return indicatePessimisticFixpoint();
1182 
1183   return ChangeStatus::UNCHANGED;
1184 }
1185 
1186 /// ------------------------ NoAlias Argument Attribute ------------------------
1187 
1188 struct AANoAliasImpl : AANoAlias {
1189   IRPositionConstructorForward(AANoAliasImpl, AANoAlias);
1190 
1191   const std::string getAsStr() const override {
1192     return getAssumed() ? "noalias" : "may-alias";
1193   }
1194 };
1195 
1196 /// NoAlias attribute for function return value.
1197 struct AANoAliasReturned final : AANoAliasImpl {
1198   AANoAliasReturned(Function &F) : AANoAliasImpl(F, IRP_RETURNED) {}
1199 
1200   /// See AbstractAttriubute::initialize(...).
1201   void initialize(Attributor &A, InformationCache &InfoCache) override {
1202     Function &F = getAnchorScope();
1203 
1204     // Already noalias.
1205     if (F.returnDoesNotAlias()) {
1206       indicateOptimisticFixpoint();
1207       return;
1208     }
1209   }
1210 
1211   /// See AbstractAttribute::updateImpl(...).
1212   virtual ChangeStatus updateImpl(Attributor &A,
1213                                   InformationCache &InfoCache) override;
1214 
1215   /// See AbstractAttribute::trackStatistics()
1216   void trackStatistics() const override {
1217     STATS_DECL_AND_TRACK_FNRET_ATTR(noalias)
1218   }
1219 };
1220 
1221 ChangeStatus AANoAliasReturned::updateImpl(Attributor &A,
1222                                            InformationCache &InfoCache) {
1223   Function &F = getAnchorScope();
1224 
1225   auto CheckReturnValue = [&](Value &RV) -> bool {
1226     if (Constant *C = dyn_cast<Constant>(&RV))
1227       if (C->isNullValue() || isa<UndefValue>(C))
1228         return true;
1229 
1230     /// For now, we can only deduce noalias if we have call sites.
1231     /// FIXME: add more support.
1232     ImmutableCallSite ICS(&RV);
1233     if (!ICS)
1234       return false;
1235 
1236     if (!ICS.returnDoesNotAlias()) {
1237       auto *NoAliasAA = A.getAAFor<AANoAlias>(*this, RV);
1238       if (!NoAliasAA || !NoAliasAA->isAssumedNoAlias())
1239         return false;
1240     }
1241 
1242     /// FIXME: We can improve capture check in two ways:
1243     /// 1. Use the AANoCapture facilities.
1244     /// 2. Use the location of return insts for escape queries.
1245     if (PointerMayBeCaptured(&RV, /* ReturnCaptures */ false,
1246                              /* StoreCaptures */ true))
1247       return false;
1248 
1249     return true;
1250   };
1251 
1252   if (!A.checkForAllReturnedValues(F, CheckReturnValue, *this))
1253     return indicatePessimisticFixpoint();
1254 
1255   return ChangeStatus::UNCHANGED;
1256 }
1257 
1258 /// -------------------AAIsDead Function Attribute-----------------------
1259 
1260 struct AAIsDeadImpl : public AAIsDead {
1261   IRPositionConstructorForward(AAIsDeadImpl, AAIsDead);
1262 
1263   void initialize(Attributor &A, InformationCache &InfoCache) override {
1264     const Function &F = getAnchorScope();
1265 
1266     ToBeExploredPaths.insert(&(F.getEntryBlock().front()));
1267     AssumedLiveBlocks.insert(&(F.getEntryBlock()));
1268     for (size_t i = 0; i < ToBeExploredPaths.size(); ++i)
1269       if (const Instruction *NextNoReturnI =
1270               findNextNoReturn(A, ToBeExploredPaths[i]))
1271         NoReturnCalls.insert(NextNoReturnI);
1272   }
1273 
1274   /// Find the next assumed noreturn instruction in the block of \p I starting
1275   /// from, thus including, \p I.
1276   ///
1277   /// The caller is responsible to monitor the ToBeExploredPaths set as new
1278   /// instructions discovered in other basic block will be placed in there.
1279   ///
1280   /// \returns The next assumed noreturn instructions in the block of \p I
1281   ///          starting from, thus including, \p I.
1282   const Instruction *findNextNoReturn(Attributor &A, const Instruction *I);
1283 
1284   /// See AbstractAttribute::getAsStr().
1285   const std::string getAsStr() const override {
1286     return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
1287            std::to_string(getAnchorScope().size()) + "][#NRI " +
1288            std::to_string(NoReturnCalls.size()) + "]";
1289   }
1290 
1291   /// See AbstractAttribute::manifest(...).
1292   ChangeStatus manifest(Attributor &A) override {
1293     assert(getState().isValidState() &&
1294            "Attempted to manifest an invalid state!");
1295 
1296     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1297     const Function &F = getAnchorScope();
1298 
1299     // Flag to determine if we can change an invoke to a call assuming the
1300     // callee is nounwind. This is not possible if the personality of the
1301     // function allows to catch asynchronous exceptions.
1302     bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
1303 
1304     for (const Instruction *NRC : NoReturnCalls) {
1305       Instruction *I = const_cast<Instruction *>(NRC);
1306       BasicBlock *BB = I->getParent();
1307       Instruction *SplitPos = I->getNextNode();
1308 
1309       if (auto *II = dyn_cast<InvokeInst>(I)) {
1310         // If we keep the invoke the split position is at the beginning of the
1311         // normal desitination block (it invokes a noreturn function after all).
1312         BasicBlock *NormalDestBB = II->getNormalDest();
1313         SplitPos = &NormalDestBB->front();
1314 
1315         /// Invoke is replaced with a call and unreachable is placed after it if
1316         /// the callee is nounwind and noreturn. Otherwise, we keep the invoke
1317         /// and only place an unreachable in the normal successor.
1318         if (Invoke2CallAllowed) {
1319           if (Function *Callee = II->getCalledFunction()) {
1320             auto *AANoUnw = A.getAAFor<AANoUnwind>(*this, *Callee);
1321             if (Callee->hasFnAttribute(Attribute::NoUnwind) ||
1322                 (AANoUnw && AANoUnw->isAssumedNoUnwind())) {
1323               LLVM_DEBUG(dbgs()
1324                          << "[AAIsDead] Replace invoke with call inst\n");
1325               // We do not need an invoke (II) but instead want a call followed
1326               // by an unreachable. However, we do not remove II as other
1327               // abstract attributes might have it cached as part of their
1328               // results. Given that we modify the CFG anyway, we simply keep II
1329               // around but in a new dead block. To avoid II being live through
1330               // a different edge we have to ensure the block we place it in is
1331               // only reached from the current block of II and then not reached
1332               // at all when we insert the unreachable.
1333               SplitBlockPredecessors(NormalDestBB, {BB}, ".i2c");
1334               CallInst *CI = createCallMatchingInvoke(II);
1335               CI->insertBefore(II);
1336               CI->takeName(II);
1337               II->replaceAllUsesWith(CI);
1338               SplitPos = CI->getNextNode();
1339             }
1340           }
1341         }
1342       }
1343 
1344       BB = SplitPos->getParent();
1345       SplitBlock(BB, SplitPos);
1346       changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false);
1347       HasChanged = ChangeStatus::CHANGED;
1348     }
1349 
1350     return HasChanged;
1351   }
1352 
1353   /// See AbstractAttribute::updateImpl(...).
1354   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
1355 
1356   /// See AAIsDead::isAssumedDead(BasicBlock *).
1357   bool isAssumedDead(const BasicBlock *BB) const override {
1358     assert(BB->getParent() == &getAnchorScope() &&
1359            "BB must be in the same anchor scope function.");
1360 
1361     if (!getAssumed())
1362       return false;
1363     return !AssumedLiveBlocks.count(BB);
1364   }
1365 
1366   /// See AAIsDead::isKnownDead(BasicBlock *).
1367   bool isKnownDead(const BasicBlock *BB) const override {
1368     return getKnown() && isAssumedDead(BB);
1369   }
1370 
1371   /// See AAIsDead::isAssumed(Instruction *I).
1372   bool isAssumedDead(const Instruction *I) const override {
1373     assert(I->getParent()->getParent() == &getAnchorScope() &&
1374            "Instruction must be in the same anchor scope function.");
1375 
1376     if (!getAssumed())
1377       return false;
1378 
1379     // If it is not in AssumedLiveBlocks then it for sure dead.
1380     // Otherwise, it can still be after noreturn call in a live block.
1381     if (!AssumedLiveBlocks.count(I->getParent()))
1382       return true;
1383 
1384     // If it is not after a noreturn call, than it is live.
1385     return isAfterNoReturn(I);
1386   }
1387 
1388   /// See AAIsDead::isKnownDead(Instruction *I).
1389   bool isKnownDead(const Instruction *I) const override {
1390     return getKnown() && isAssumedDead(I);
1391   }
1392 
1393   /// Check if instruction is after noreturn call, in other words, assumed dead.
1394   bool isAfterNoReturn(const Instruction *I) const;
1395 
1396   /// Determine if \p F might catch asynchronous exceptions.
1397   static bool mayCatchAsynchronousExceptions(const Function &F) {
1398     return F.hasPersonalityFn() && !canSimplifyInvokeNoUnwind(&F);
1399   }
1400 
1401   /// Collection of to be explored paths.
1402   SmallSetVector<const Instruction *, 8> ToBeExploredPaths;
1403 
1404   /// Collection of all assumed live BasicBlocks.
1405   DenseSet<const BasicBlock *> AssumedLiveBlocks;
1406 
1407   /// Collection of calls with noreturn attribute, assumed or knwon.
1408   SmallSetVector<const Instruction *, 4> NoReturnCalls;
1409 };
1410 
1411 struct AAIsDeadFunction final : public AAIsDeadImpl {
1412   AAIsDeadFunction(Function &F) : AAIsDeadImpl(F, IRP_FUNCTION) {}
1413 
1414   /// See AbstractAttribute::trackStatistics()
1415   void trackStatistics() const override {
1416     STATS_DECL(DeadBlocks, Function,
1417                "Number of basic blocks classified as dead");
1418     BUILD_STAT_NAME(DeadBlocks, Function) +=
1419         getAnchorScope().size() - AssumedLiveBlocks.size();
1420     STATS_DECL(PartiallyDeadBlocks, Function,
1421                "Number of basic blocks classified as partially dead");
1422     BUILD_STAT_NAME(PartiallyDeadBlocks, Function) += NoReturnCalls.size();
1423   }
1424 };
1425 
1426 bool AAIsDeadImpl::isAfterNoReturn(const Instruction *I) const {
1427   const Instruction *PrevI = I->getPrevNode();
1428   while (PrevI) {
1429     if (NoReturnCalls.count(PrevI))
1430       return true;
1431     PrevI = PrevI->getPrevNode();
1432   }
1433   return false;
1434 }
1435 
1436 const Instruction *AAIsDeadImpl::findNextNoReturn(Attributor &A,
1437                                                   const Instruction *I) {
1438   const BasicBlock *BB = I->getParent();
1439   const Function &F = *BB->getParent();
1440 
1441   // Flag to determine if we can change an invoke to a call assuming the callee
1442   // is nounwind. This is not possible if the personality of the function allows
1443   // to catch asynchronous exceptions.
1444   bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
1445 
1446   // TODO: We should have a function that determines if an "edge" is dead.
1447   //       Edges could be from an instruction to the next or from a terminator
1448   //       to the successor. For now, we need to special case the unwind block
1449   //       of InvokeInst below.
1450 
1451   while (I) {
1452     ImmutableCallSite ICS(I);
1453 
1454     if (ICS) {
1455       // Regarless of the no-return property of an invoke instruction we only
1456       // learn that the regular successor is not reachable through this
1457       // instruction but the unwind block might still be.
1458       if (auto *Invoke = dyn_cast<InvokeInst>(I)) {
1459         // Use nounwind to justify the unwind block is dead as well.
1460         auto *AANoUnw = A.getAAFor<AANoUnwind>(*this, *Invoke);
1461         if (!Invoke2CallAllowed ||
1462             (!AANoUnw || !AANoUnw->isAssumedNoUnwind())) {
1463           AssumedLiveBlocks.insert(Invoke->getUnwindDest());
1464           ToBeExploredPaths.insert(&Invoke->getUnwindDest()->front());
1465         }
1466       }
1467 
1468       auto *NoReturnAA = A.getAAFor<AANoReturn>(*this, *I);
1469       if (ICS.hasFnAttr(Attribute::NoReturn) ||
1470           (NoReturnAA && NoReturnAA->isAssumedNoReturn()))
1471         return I;
1472     }
1473 
1474     I = I->getNextNode();
1475   }
1476 
1477   // get new paths (reachable blocks).
1478   for (const BasicBlock *SuccBB : successors(BB)) {
1479     AssumedLiveBlocks.insert(SuccBB);
1480     ToBeExploredPaths.insert(&SuccBB->front());
1481   }
1482 
1483   // No noreturn instruction found.
1484   return nullptr;
1485 }
1486 
1487 ChangeStatus AAIsDeadImpl::updateImpl(Attributor &A,
1488                                       InformationCache &InfoCache) {
1489   // Temporary collection to iterate over existing noreturn instructions. This
1490   // will alow easier modification of NoReturnCalls collection
1491   SmallVector<const Instruction *, 8> NoReturnChanged;
1492   ChangeStatus Status = ChangeStatus::UNCHANGED;
1493 
1494   for (const Instruction *I : NoReturnCalls)
1495     NoReturnChanged.push_back(I);
1496 
1497   for (const Instruction *I : NoReturnChanged) {
1498     size_t Size = ToBeExploredPaths.size();
1499 
1500     const Instruction *NextNoReturnI = findNextNoReturn(A, I);
1501     if (NextNoReturnI != I) {
1502       Status = ChangeStatus::CHANGED;
1503       NoReturnCalls.remove(I);
1504       if (NextNoReturnI)
1505         NoReturnCalls.insert(NextNoReturnI);
1506     }
1507 
1508     // Explore new paths.
1509     while (Size != ToBeExploredPaths.size()) {
1510       Status = ChangeStatus::CHANGED;
1511       if (const Instruction *NextNoReturnI =
1512               findNextNoReturn(A, ToBeExploredPaths[Size++]))
1513         NoReturnCalls.insert(NextNoReturnI);
1514     }
1515   }
1516 
1517   LLVM_DEBUG(
1518       dbgs() << "[AAIsDead] AssumedLiveBlocks: " << AssumedLiveBlocks.size()
1519              << " Total number of blocks: " << getAnchorScope().size() << "\n");
1520 
1521   // If we know everything is live there is no need to query for liveness.
1522   if (NoReturnCalls.empty() &&
1523       getAnchorScope().size() == AssumedLiveBlocks.size()) {
1524     // Indicating a pessimistic fixpoint will cause the state to be "invalid"
1525     // which will cause the Attributor to not return the AAIsDead on request,
1526     // which will prevent us from querying isAssumedDead().
1527     indicatePessimisticFixpoint();
1528     assert(!isValidState() && "Expected an invalid state!");
1529   }
1530 
1531   return Status;
1532 }
1533 
1534 /// -------------------- Dereferenceable Argument Attribute --------------------
1535 
1536 struct DerefState : AbstractState {
1537 
1538   /// State representing for dereferenceable bytes.
1539   IntegerState DerefBytesState;
1540 
1541   /// State representing that whether the value is nonnull or global.
1542   IntegerState NonNullGlobalState;
1543 
1544   /// Bits encoding for NonNullGlobalState.
1545   enum {
1546     DEREF_NONNULL = 1 << 0,
1547     DEREF_GLOBAL = 1 << 1,
1548   };
1549 
1550   /// See AbstractState::isValidState()
1551   bool isValidState() const override { return DerefBytesState.isValidState(); }
1552 
1553   /// See AbstractState::isAtFixpoint()
1554   bool isAtFixpoint() const override {
1555     return !isValidState() || (DerefBytesState.isAtFixpoint() &&
1556                                NonNullGlobalState.isAtFixpoint());
1557   }
1558 
1559   /// See AbstractState::indicateOptimisticFixpoint(...)
1560   ChangeStatus indicateOptimisticFixpoint() override {
1561     DerefBytesState.indicateOptimisticFixpoint();
1562     NonNullGlobalState.indicateOptimisticFixpoint();
1563     return ChangeStatus::UNCHANGED;
1564   }
1565 
1566   /// See AbstractState::indicatePessimisticFixpoint(...)
1567   ChangeStatus indicatePessimisticFixpoint() override {
1568     DerefBytesState.indicatePessimisticFixpoint();
1569     NonNullGlobalState.indicatePessimisticFixpoint();
1570     return ChangeStatus::CHANGED;
1571   }
1572 
1573   /// Update known dereferenceable bytes.
1574   void takeKnownDerefBytesMaximum(uint64_t Bytes) {
1575     DerefBytesState.takeKnownMaximum(Bytes);
1576   }
1577 
1578   /// Update assumed dereferenceable bytes.
1579   void takeAssumedDerefBytesMinimum(uint64_t Bytes) {
1580     DerefBytesState.takeAssumedMinimum(Bytes);
1581   }
1582 
1583   /// Update assumed NonNullGlobalState
1584   void updateAssumedNonNullGlobalState(bool IsNonNull, bool IsGlobal) {
1585     if (!IsNonNull)
1586       NonNullGlobalState.removeAssumedBits(DEREF_NONNULL);
1587     if (!IsGlobal)
1588       NonNullGlobalState.removeAssumedBits(DEREF_GLOBAL);
1589   }
1590 
1591   /// Equality for DerefState.
1592   bool operator==(const DerefState &R) {
1593     return this->DerefBytesState == R.DerefBytesState &&
1594            this->NonNullGlobalState == R.NonNullGlobalState;
1595   }
1596 };
1597 
1598 struct AADereferenceableImpl : AADereferenceable, DerefState {
1599   IRPositionConstructorForward(AADereferenceableImpl, AADereferenceable);
1600   using StateType = DerefState;
1601 
1602   /// See AbstractAttribute::getState()
1603   /// {
1604   StateType &getState() override { return *this; }
1605   const StateType &getState() const override { return *this; }
1606   /// }
1607 
1608   /// See AADereferenceable::getAssumedDereferenceableBytes().
1609   uint32_t getAssumedDereferenceableBytes() const override {
1610     return DerefBytesState.getAssumed();
1611   }
1612 
1613   /// See AADereferenceable::getKnownDereferenceableBytes().
1614   uint32_t getKnownDereferenceableBytes() const override {
1615     return DerefBytesState.getKnown();
1616   }
1617 
1618   // Helper function for syncing nonnull state.
1619   void syncNonNull(const AANonNull *NonNullAA) {
1620     if (!NonNullAA) {
1621       NonNullGlobalState.removeAssumedBits(DEREF_NONNULL);
1622       return;
1623     }
1624 
1625     if (NonNullAA->isKnownNonNull())
1626       NonNullGlobalState.addKnownBits(DEREF_NONNULL);
1627 
1628     if (!NonNullAA->isAssumedNonNull())
1629       NonNullGlobalState.removeAssumedBits(DEREF_NONNULL);
1630   }
1631 
1632   /// See AADereferenceable::isAssumedGlobal().
1633   bool isAssumedGlobal() const override {
1634     return NonNullGlobalState.isAssumed(DEREF_GLOBAL);
1635   }
1636 
1637   /// See AADereferenceable::isKnownGlobal().
1638   bool isKnownGlobal() const override {
1639     return NonNullGlobalState.isKnown(DEREF_GLOBAL);
1640   }
1641 
1642   /// See AADereferenceable::isAssumedNonNull().
1643   bool isAssumedNonNull() const override {
1644     return NonNullGlobalState.isAssumed(DEREF_NONNULL);
1645   }
1646 
1647   /// See AADereferenceable::isKnownNonNull().
1648   bool isKnownNonNull() const override {
1649     return NonNullGlobalState.isKnown(DEREF_NONNULL);
1650   }
1651 
1652   void getDeducedAttributes(LLVMContext &Ctx,
1653                             SmallVectorImpl<Attribute> &Attrs) const override {
1654     // TODO: Add *_globally support
1655     if (isAssumedNonNull())
1656       Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
1657           Ctx, getAssumedDereferenceableBytes()));
1658     else
1659       Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
1660           Ctx, getAssumedDereferenceableBytes()));
1661   }
1662   uint64_t computeAssumedDerefenceableBytes(Attributor &A, Value &V,
1663                                             bool &IsNonNull, bool &IsGlobal);
1664 
1665   void initialize(Attributor &A, InformationCache &InfoCache) override {
1666     Function &F = getAnchorScope();
1667     unsigned AttrIdx = getIRPosition().getAttrIdx();
1668 
1669     for (Attribute::AttrKind AK :
1670          {Attribute::Dereferenceable, Attribute::DereferenceableOrNull})
1671       if (F.getAttributes().hasAttribute(AttrIdx, AK))
1672         takeKnownDerefBytesMaximum(F.getAttribute(AttrIdx, AK).getValueAsInt());
1673   }
1674 
1675   /// See AbstractAttribute::getAsStr().
1676   const std::string getAsStr() const override {
1677     if (!getAssumedDereferenceableBytes())
1678       return "unknown-dereferenceable";
1679     return std::string("dereferenceable") +
1680            (isAssumedNonNull() ? "" : "_or_null") +
1681            (isAssumedGlobal() ? "_globally" : "") + "<" +
1682            std::to_string(getKnownDereferenceableBytes()) + "-" +
1683            std::to_string(getAssumedDereferenceableBytes()) + ">";
1684   }
1685 };
1686 
1687 struct AADereferenceableReturned final : AADereferenceableImpl {
1688   AADereferenceableReturned(Function &F)
1689       : AADereferenceableImpl(F, IRP_RETURNED) {}
1690 
1691   /// See AbstractAttribute::updateImpl(...).
1692   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
1693 
1694   /// See AbstractAttribute::trackStatistics()
1695   void trackStatistics() const override {
1696     STATS_DECL_AND_TRACK_FNRET_ATTR(dereferenceable)
1697   }
1698 };
1699 
1700 // Helper function that returns dereferenceable bytes.
1701 static uint64_t calcDifferenceIfBaseIsNonNull(int64_t DerefBytes,
1702                                               int64_t Offset, bool IsNonNull) {
1703   if (!IsNonNull)
1704     return 0;
1705   return std::max((int64_t)0, DerefBytes - Offset);
1706 }
1707 
1708 uint64_t AADereferenceableImpl::computeAssumedDerefenceableBytes(
1709     Attributor &A, Value &V, bool &IsNonNull, bool &IsGlobal) {
1710   // TODO: Tracking the globally flag.
1711   IsGlobal = false;
1712 
1713   // First, we try to get information about V from Attributor.
1714   if (auto *DerefAA = A.getAAFor<AADereferenceable>(*this, V)) {
1715     IsNonNull &= DerefAA->isAssumedNonNull();
1716     return DerefAA->getAssumedDereferenceableBytes();
1717   }
1718 
1719   // Otherwise, we try to compute assumed bytes from base pointer.
1720   const DataLayout &DL = getAnchorScope().getParent()->getDataLayout();
1721   unsigned IdxWidth =
1722       DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
1723   APInt Offset(IdxWidth, 0);
1724   Value *Base = V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1725 
1726   if (auto *BaseDerefAA = A.getAAFor<AADereferenceable>(*this, *Base)) {
1727     IsNonNull &= Offset != 0;
1728     return calcDifferenceIfBaseIsNonNull(
1729         BaseDerefAA->getAssumedDereferenceableBytes(), Offset.getSExtValue(),
1730         Offset != 0 || BaseDerefAA->isAssumedNonNull());
1731   }
1732 
1733   // Then, use IR information.
1734 
1735   if (isDereferenceablePointer(Base, Base->getType(), DL))
1736     return calcDifferenceIfBaseIsNonNull(
1737         DL.getTypeStoreSize(Base->getType()->getPointerElementType()),
1738         Offset.getSExtValue(),
1739         !NullPointerIsDefined(&getAnchorScope(),
1740                               V.getType()->getPointerAddressSpace()));
1741 
1742   IsNonNull = false;
1743   return 0;
1744 }
1745 
1746 ChangeStatus
1747 AADereferenceableReturned::updateImpl(Attributor &A,
1748                                       InformationCache &InfoCache) {
1749   Function &F = getAnchorScope();
1750   auto BeforeState = static_cast<DerefState>(*this);
1751 
1752   syncNonNull(A.getAAFor<AANonNull>(*this, F));
1753 
1754   bool IsNonNull = isAssumedNonNull();
1755   bool IsGlobal = isAssumedGlobal();
1756 
1757   auto CheckReturnValue = [&](Value &RV) -> bool {
1758     takeAssumedDerefBytesMinimum(
1759         computeAssumedDerefenceableBytes(A, RV, IsNonNull, IsGlobal));
1760     return isValidState();
1761   };
1762 
1763   if (A.checkForAllReturnedValues(F, CheckReturnValue, *this)) {
1764     updateAssumedNonNullGlobalState(IsNonNull, IsGlobal);
1765     return BeforeState == static_cast<DerefState>(*this)
1766                ? ChangeStatus::UNCHANGED
1767                : ChangeStatus::CHANGED;
1768   }
1769   return indicatePessimisticFixpoint();
1770 }
1771 
1772 struct AADereferenceableArgument final : AADereferenceableImpl {
1773   AADereferenceableArgument(Argument &A) : AADereferenceableImpl(A) {}
1774 
1775   /// See AbstractAttribute::updateImpl(...).
1776   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
1777 
1778   /// See AbstractAttribute::trackStatistics()
1779   void trackStatistics() const override {
1780     STATS_DECL_AND_TRACK_ARG_ATTR(dereferenceable)
1781   }
1782 };
1783 
1784 ChangeStatus
1785 AADereferenceableArgument::updateImpl(Attributor &A,
1786                                       InformationCache &InfoCache) {
1787   Function &F = getAnchorScope();
1788   Argument &Arg = cast<Argument>(getAnchorValue());
1789 
1790   auto BeforeState = static_cast<DerefState>(*this);
1791 
1792   unsigned ArgNo = Arg.getArgNo();
1793 
1794   syncNonNull(A.getAAFor<AANonNull>(*this, F, ArgNo));
1795 
1796   bool IsNonNull = isAssumedNonNull();
1797   bool IsGlobal = isAssumedGlobal();
1798 
1799   // Callback function
1800   std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) -> bool {
1801     assert(CS && "Sanity check: Call site was not initialized properly!");
1802 
1803     // Check that DereferenceableAA is AADereferenceableCallSiteArgument.
1804     if (auto *DereferenceableAA =
1805             A.getAAFor<AADereferenceable>(*this, *CS.getInstruction(), ArgNo)) {
1806       ImmutableCallSite ICS(
1807           &DereferenceableAA->getIRPosition().getAnchorValue());
1808       if (ICS && CS.getInstruction() == ICS.getInstruction()) {
1809         takeAssumedDerefBytesMinimum(
1810             DereferenceableAA->getAssumedDereferenceableBytes());
1811         IsNonNull &= DereferenceableAA->isAssumedNonNull();
1812         IsGlobal &= DereferenceableAA->isAssumedGlobal();
1813         return isValidState();
1814       }
1815     }
1816 
1817     takeAssumedDerefBytesMinimum(computeAssumedDerefenceableBytes(
1818         A, *CS.getArgOperand(ArgNo), IsNonNull, IsGlobal));
1819 
1820     return isValidState();
1821   };
1822 
1823   if (!A.checkForAllCallSites(F, CallSiteCheck, *this, true))
1824     return indicatePessimisticFixpoint();
1825 
1826   updateAssumedNonNullGlobalState(IsNonNull, IsGlobal);
1827 
1828   return BeforeState == static_cast<DerefState>(*this) ? ChangeStatus::UNCHANGED
1829                                                        : ChangeStatus::CHANGED;
1830 }
1831 
1832 /// Dereferenceable attribute for a call site argument.
1833 struct AADereferenceableCallSiteArgument final : AADereferenceableImpl {
1834   AADereferenceableCallSiteArgument(Instruction &I, unsigned ArgNo)
1835       : AADereferenceableImpl(CallSite(&I).getArgOperand(ArgNo), I, ArgNo) {}
1836 
1837   /// See AbstractAttribute::initialize(...).
1838   void initialize(Attributor &A, InformationCache &InfoCache) override {
1839     CallSite CS(&getAnchorValue());
1840     if (CS.paramHasAttr(getArgNo(), Attribute::Dereferenceable))
1841       takeKnownDerefBytesMaximum(CS.getDereferenceableBytes(getArgNo()));
1842 
1843     if (CS.paramHasAttr(getArgNo(), Attribute::DereferenceableOrNull))
1844       takeKnownDerefBytesMaximum(CS.getDereferenceableOrNullBytes(getArgNo()));
1845   }
1846 
1847   /// See AbstractAttribute::updateImpl(Attributor &A).
1848   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
1849 
1850   /// See AbstractAttribute::trackStatistics()
1851   void trackStatistics() const override {
1852     STATS_DECL_AND_TRACK_CSARG_ATTR(dereferenceable)
1853   }
1854 };
1855 
1856 ChangeStatus
1857 AADereferenceableCallSiteArgument::updateImpl(Attributor &A,
1858                                               InformationCache &InfoCache) {
1859   // NOTE: Never look at the argument of the callee in this method.
1860   //       If we do this, "dereferenceable" is always deduced because of the
1861   //       assumption.
1862 
1863   Value &V = *getAssociatedValue();
1864 
1865   auto BeforeState = static_cast<DerefState>(*this);
1866 
1867   syncNonNull(A.getAAFor<AANonNull>(*this, getAnchorValue(), getArgNo()));
1868   bool IsNonNull = isAssumedNonNull();
1869   bool IsGlobal = isKnownGlobal();
1870 
1871   takeAssumedDerefBytesMinimum(
1872       computeAssumedDerefenceableBytes(A, V, IsNonNull, IsGlobal));
1873   updateAssumedNonNullGlobalState(IsNonNull, IsGlobal);
1874 
1875   return BeforeState == static_cast<DerefState>(*this) ? ChangeStatus::UNCHANGED
1876                                                        : ChangeStatus::CHANGED;
1877 }
1878 
1879 // ------------------------ Align Argument Attribute ------------------------
1880 
1881 struct AAAlignImpl : AAAlign {
1882   IRPositionConstructorForward(AAAlignImpl, AAAlign);
1883 
1884   // Max alignemnt value allowed in IR
1885   static const unsigned MAX_ALIGN = 1U << 29;
1886 
1887   const std::string getAsStr() const override {
1888     return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
1889                                 "-" + std::to_string(getAssumedAlign()) + ">")
1890                              : "unknown-align";
1891   }
1892 
1893   /// See AbstractAttriubute::initialize(...).
1894   void initialize(Attributor &A, InformationCache &InfoCache) override {
1895     takeAssumedMinimum(MAX_ALIGN);
1896 
1897     Function &F = getAnchorScope();
1898 
1899     unsigned AttrIdx = getAttrIdx();
1900     // Already the function has align attribute on return value or argument.
1901     if (F.getAttributes().hasAttribute(AttrIdx, Attribute::Alignment))
1902       addKnownBits(
1903           F.getAttribute(AttrIdx, Attribute::Alignment).getAlignment());
1904   }
1905 
1906   /// See AbstractAttribute::getDeducedAttributes
1907   virtual void
1908   getDeducedAttributes(LLVMContext &Ctx,
1909                        SmallVectorImpl<Attribute> &Attrs) const override {
1910     Attrs.emplace_back(Attribute::getWithAlignment(Ctx, getAssumedAlign()));
1911   }
1912 };
1913 
1914 /// Align attribute for function return value.
1915 struct AAAlignReturned final : AAAlignImpl {
1916   AAAlignReturned(Function &F) : AAAlignImpl(F, IRP_RETURNED) {}
1917 
1918   /// See AbstractAttribute::updateImpl(...).
1919   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
1920 
1921   /// See AbstractAttribute::trackStatistics()
1922   void trackStatistics() const override {
1923     STATS_DECL_AND_TRACK_FNRET_ATTR(aligned)
1924   }
1925 };
1926 
1927 ChangeStatus AAAlignReturned::updateImpl(Attributor &A,
1928                                          InformationCache &InfoCache) {
1929   Function &F = getAnchorScope();
1930 
1931   // Currently, align<n> is deduced if alignments in return values are assumed
1932   // as greater than n. We reach pessimistic fixpoint if any of the return value
1933   // wouldn't have align. If no assumed state was used for reasoning, an
1934   // optimistic fixpoint is reached earlier.
1935 
1936   base_t BeforeState = getAssumed();
1937   auto CheckReturnValue =
1938       [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &RetInsts) -> bool {
1939     auto *AlignAA = A.getAAFor<AAAlign>(*this, RV);
1940 
1941     if (AlignAA)
1942       takeAssumedMinimum(AlignAA->getAssumedAlign());
1943     else
1944       // Use IR information.
1945       takeAssumedMinimum(RV.getPointerAlignment(
1946           getAnchorScope().getParent()->getDataLayout()));
1947 
1948     return isValidState();
1949   };
1950 
1951   if (!A.checkForAllReturnedValuesAndReturnInsts(F, CheckReturnValue, *this))
1952     return indicatePessimisticFixpoint();
1953 
1954   return (getAssumed() != BeforeState) ? ChangeStatus::CHANGED
1955                                        : ChangeStatus::UNCHANGED;
1956 }
1957 
1958 /// Align attribute for function argument.
1959 struct AAAlignArgument final : AAAlignImpl {
1960   AAAlignArgument(Argument &A) : AAAlignImpl(A) {}
1961 
1962   /// See AbstractAttribute::updateImpl(...).
1963   virtual ChangeStatus updateImpl(Attributor &A,
1964                                   InformationCache &InfoCache) override;
1965 
1966   /// See AbstractAttribute::trackStatistics()
1967   void trackStatistics() const override{STATS_DECL_AND_TRACK_ARG_ATTR(aligned)};
1968 };
1969 
1970 ChangeStatus AAAlignArgument::updateImpl(Attributor &A,
1971                                          InformationCache &InfoCache) {
1972 
1973   Function &F = getAnchorScope();
1974   Argument &Arg = cast<Argument>(getAnchorValue());
1975 
1976   unsigned ArgNo = Arg.getArgNo();
1977   const DataLayout &DL = F.getParent()->getDataLayout();
1978 
1979   auto BeforeState = getAssumed();
1980 
1981   // Callback function
1982   std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) {
1983     assert(CS && "Sanity check: Call site was not initialized properly!");
1984 
1985     auto *AlignAA = A.getAAFor<AAAlign>(*this, *CS.getInstruction(), ArgNo);
1986 
1987     // Check that AlignAA is AAAlignCallSiteArgument.
1988     if (AlignAA) {
1989       ImmutableCallSite ICS(&AlignAA->getIRPosition().getAnchorValue());
1990       if (ICS && CS.getInstruction() == ICS.getInstruction()) {
1991         takeAssumedMinimum(AlignAA->getAssumedAlign());
1992         return isValidState();
1993       }
1994     }
1995 
1996     Value *V = CS.getArgOperand(ArgNo);
1997     takeAssumedMinimum(V->getPointerAlignment(DL));
1998     return isValidState();
1999   };
2000 
2001   if (!A.checkForAllCallSites(F, CallSiteCheck, *this, true))
2002     indicatePessimisticFixpoint();
2003 
2004   return BeforeState == getAssumed() ? ChangeStatus::UNCHANGED
2005                                      : ChangeStatus ::CHANGED;
2006 }
2007 
2008 struct AAAlignCallSiteArgument final : AAAlignImpl {
2009   AAAlignCallSiteArgument(Instruction &I, unsigned ArgNo)
2010       : AAAlignImpl(CallSite(&I).getArgOperand(ArgNo), I, ArgNo) {}
2011 
2012   /// See AbstractAttribute::initialize(...).
2013   void initialize(Attributor &A, InformationCache &InfoCache) override {
2014     CallSite CS(&getAnchorValue());
2015     takeKnownMaximum(getAssociatedValue()->getPointerAlignment(
2016         getAnchorScope().getParent()->getDataLayout()));
2017   }
2018 
2019   /// See AbstractAttribute::updateImpl(Attributor &A).
2020   ChangeStatus updateImpl(Attributor &A, InformationCache &InfoCache) override;
2021 
2022   /// See AbstractAttribute::trackStatistics()
2023   void trackStatistics() const override {
2024     STATS_DECL_AND_TRACK_CSARG_ATTR(aligned)
2025   }
2026 };
2027 
2028 ChangeStatus AAAlignCallSiteArgument::updateImpl(Attributor &A,
2029                                                  InformationCache &InfoCache) {
2030   // NOTE: Never look at the argument of the callee in this method.
2031   //       If we do this, "align" is always deduced because of the assumption.
2032 
2033   auto BeforeState = getAssumed();
2034 
2035   Value &V = *getAssociatedValue();
2036 
2037   auto *AlignAA = A.getAAFor<AAAlign>(*this, V);
2038 
2039   if (AlignAA)
2040     takeAssumedMinimum(AlignAA->getAssumedAlign());
2041   else
2042     indicatePessimisticFixpoint();
2043 
2044   return BeforeState == getAssumed() ? ChangeStatus::UNCHANGED
2045                                      : ChangeStatus::CHANGED;
2046 }
2047 
2048 /// ------------------ Function No-Return Attribute ----------------------------
2049 struct AANoReturnImpl : public AANoReturn {
2050   IRPositionConstructorForward(AANoReturnImpl, AANoReturn);
2051 
2052   /// See AbstractAttribute::getAsStr().
2053   const std::string getAsStr() const override {
2054     return getAssumed() ? "noreturn" : "may-return";
2055   }
2056 
2057   /// See AbstractAttribute::initialize(...).
2058   void initialize(Attributor &A, InformationCache &InfoCache) override {
2059     Function &F = getAnchorScope();
2060     if (F.hasFnAttribute(getAttrKind()))
2061       indicateOptimisticFixpoint();
2062   }
2063 
2064   /// See AbstractAttribute::updateImpl(Attributor &A).
2065   virtual ChangeStatus updateImpl(Attributor &A,
2066                                   InformationCache &InfoCache) override {
2067     const Function &F = getAnchorScope();
2068     auto CheckForNoReturn = [](Instruction &) { return false; };
2069     if (!A.checkForAllInstructions(F, CheckForNoReturn, *this, InfoCache,
2070                                    {(unsigned)Instruction::Ret}))
2071       return indicatePessimisticFixpoint();
2072     return ChangeStatus::UNCHANGED;
2073   }
2074 };
2075 
2076 struct AANoReturnFunction final : AANoReturnImpl {
2077   AANoReturnFunction(Function &F) : AANoReturnImpl(F, IRP_FUNCTION) {}
2078 
2079   /// See AbstractAttribute::trackStatistics()
2080   void trackStatistics() const override {
2081     STATS_DECL_AND_TRACK_FN_ATTR(noreturn)
2082   }
2083 };
2084 
2085 /// ----------------------------------------------------------------------------
2086 ///                               Attributor
2087 /// ----------------------------------------------------------------------------
2088 
2089 bool Attributor::checkForAllCallSites(Function &F,
2090                                       std::function<bool(CallSite)> &Pred,
2091                                       const AbstractAttribute &QueryingAA,
2092                                       bool RequireAllCallSites) {
2093   // We can try to determine information from
2094   // the call sites. However, this is only possible all call sites are known,
2095   // hence the function has internal linkage.
2096   if (RequireAllCallSites && !F.hasInternalLinkage()) {
2097     LLVM_DEBUG(
2098         dbgs()
2099         << "Attributor: Function " << F.getName()
2100         << " has no internal linkage, hence not all call sites are known\n");
2101     return false;
2102   }
2103 
2104   for (const Use &U : F.uses()) {
2105     Instruction *I = cast<Instruction>(U.getUser());
2106     Function *AnchorValue = I->getParent()->getParent();
2107 
2108     auto *LivenessAA = getAAFor<AAIsDead>(QueryingAA, *AnchorValue);
2109 
2110     // Skip dead calls.
2111     if (LivenessAA && LivenessAA->isAssumedDead(I))
2112       continue;
2113 
2114     CallSite CS(U.getUser());
2115     if (!CS || !CS.isCallee(&U) || !CS.getCaller()->hasExactDefinition()) {
2116       if (!RequireAllCallSites)
2117         continue;
2118 
2119       LLVM_DEBUG(dbgs() << "Attributor: User " << *U.getUser()
2120                         << " is an invalid use of " << F.getName() << "\n");
2121       return false;
2122     }
2123 
2124     if (Pred(CS))
2125       continue;
2126 
2127     LLVM_DEBUG(dbgs() << "Attributor: Call site callback failed for "
2128                       << *CS.getInstruction() << "\n");
2129     return false;
2130   }
2131 
2132   return true;
2133 }
2134 
2135 bool Attributor::checkForAllReturnedValuesAndReturnInsts(
2136     const Function &F,
2137     const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
2138         &Pred,
2139     const AbstractAttribute &QueryingAA) {
2140 
2141   auto *AARetVal = getAAFor<AAReturnedValues>(QueryingAA, F);
2142   if (!AARetVal)
2143     return false;
2144 
2145   auto *LivenessAA = getAAFor<AAIsDead>(QueryingAA, F);
2146   if (!LivenessAA)
2147     return AARetVal->checkForAllReturnedValuesAndReturnInsts(Pred);
2148 
2149   auto LivenessFilter = [&](Value &RV,
2150                             const SmallPtrSetImpl<ReturnInst *> &ReturnInsts) {
2151     SmallPtrSet<ReturnInst *, 4> FilteredReturnInsts;
2152     for (ReturnInst *RI : ReturnInsts)
2153       if (!LivenessAA->isAssumedDead(RI))
2154         FilteredReturnInsts.insert(RI);
2155     if (!FilteredReturnInsts.empty())
2156       return Pred(RV, FilteredReturnInsts);
2157     return true;
2158   };
2159 
2160   return AARetVal->checkForAllReturnedValuesAndReturnInsts(LivenessFilter);
2161 }
2162 
2163 bool Attributor::checkForAllReturnedValues(
2164     const Function &F, const function_ref<bool(Value &)> &Pred,
2165     const AbstractAttribute &QueryingAA) {
2166 
2167   auto *AARetVal = getAAFor<AAReturnedValues>(QueryingAA, F);
2168   if (!AARetVal)
2169     return false;
2170 
2171   auto *LivenessAA = getAAFor<AAIsDead>(QueryingAA, F);
2172   if (!LivenessAA)
2173     return AARetVal->checkForAllReturnedValuesAndReturnInsts(
2174         [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &) {
2175           return Pred(RV);
2176         });
2177 
2178   auto LivenessFilter = [&](Value &RV,
2179                             const SmallPtrSetImpl<ReturnInst *> &ReturnInsts) {
2180     if (LivenessAA->isLiveInstSet(ReturnInsts.begin(), ReturnInsts.end()))
2181       return Pred(RV);
2182     return true;
2183   };
2184 
2185   return AARetVal->checkForAllReturnedValuesAndReturnInsts(LivenessFilter);
2186 }
2187 
2188 bool Attributor::checkForAllInstructions(
2189     const Function &F, const llvm::function_ref<bool(Instruction &)> &Pred,
2190     const AbstractAttribute &QueryingAA, InformationCache &InfoCache,
2191     const ArrayRef<unsigned> &Opcodes) {
2192 
2193   auto *LivenessAA = getAAFor<AAIsDead>(QueryingAA, F);
2194 
2195   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
2196   for (unsigned Opcode : Opcodes) {
2197     for (Instruction *I : OpcodeInstMap[Opcode]) {
2198       // Skip dead instructions.
2199       if (LivenessAA && LivenessAA->isAssumedDead(I))
2200         continue;
2201 
2202       if (!Pred(*I))
2203         return false;
2204     }
2205   }
2206 
2207   return true;
2208 }
2209 
2210 bool Attributor::checkForAllReadWriteInstructions(
2211     const Function &F, const llvm::function_ref<bool(Instruction &)> &Pred,
2212     AbstractAttribute &QueryingAA, InformationCache &InfoCache) {
2213 
2214   auto *LivenessAA = getAAFor<AAIsDead>(QueryingAA, F);
2215 
2216   for (Instruction *I : InfoCache.getReadOrWriteInstsForFunction(F)) {
2217     // Skip dead instructions.
2218     if (LivenessAA && LivenessAA->isAssumedDead(I))
2219       continue;
2220 
2221     if (!Pred(*I))
2222       return false;
2223   }
2224 
2225   return true;
2226 }
2227 
2228 ChangeStatus Attributor::run(InformationCache &InfoCache) {
2229   // Initialize all abstract attributes.
2230   for (AbstractAttribute *AA : AllAbstractAttributes)
2231     AA->initialize(*this, InfoCache);
2232 
2233   LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
2234                     << AllAbstractAttributes.size()
2235                     << " abstract attributes.\n");
2236 
2237   // Now that all abstract attributes are collected and initialized we start
2238   // the abstract analysis.
2239 
2240   unsigned IterationCounter = 1;
2241 
2242   SmallVector<AbstractAttribute *, 64> ChangedAAs;
2243   SetVector<AbstractAttribute *> Worklist;
2244   Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end());
2245 
2246   do {
2247     LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
2248                       << ", Worklist size: " << Worklist.size() << "\n");
2249 
2250     // Add all abstract attributes that are potentially dependent on one that
2251     // changed to the work list.
2252     for (AbstractAttribute *ChangedAA : ChangedAAs) {
2253       auto &QuerriedAAs = QueryMap[ChangedAA];
2254       Worklist.insert(QuerriedAAs.begin(), QuerriedAAs.end());
2255     }
2256 
2257     // Reset the changed set.
2258     ChangedAAs.clear();
2259 
2260     // Update all abstract attribute in the work list and record the ones that
2261     // changed.
2262     for (AbstractAttribute *AA : Worklist)
2263       if (AA->update(*this, InfoCache) == ChangeStatus::CHANGED)
2264         ChangedAAs.push_back(AA);
2265 
2266     // Reset the work list and repopulate with the changed abstract attributes.
2267     // Note that dependent ones are added above.
2268     Worklist.clear();
2269     Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
2270 
2271   } while (!Worklist.empty() && ++IterationCounter < MaxFixpointIterations);
2272 
2273   LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
2274                     << IterationCounter << "/" << MaxFixpointIterations
2275                     << " iterations\n");
2276 
2277   bool FinishedAtFixpoint = Worklist.empty();
2278 
2279   // Reset abstract arguments not settled in a sound fixpoint by now. This
2280   // happens when we stopped the fixpoint iteration early. Note that only the
2281   // ones marked as "changed" *and* the ones transitively depending on them
2282   // need to be reverted to a pessimistic state. Others might not be in a
2283   // fixpoint state but we can use the optimistic results for them anyway.
2284   SmallPtrSet<AbstractAttribute *, 32> Visited;
2285   for (unsigned u = 0; u < ChangedAAs.size(); u++) {
2286     AbstractAttribute *ChangedAA = ChangedAAs[u];
2287     if (!Visited.insert(ChangedAA).second)
2288       continue;
2289 
2290     AbstractState &State = ChangedAA->getState();
2291     if (!State.isAtFixpoint()) {
2292       State.indicatePessimisticFixpoint();
2293 
2294       NumAttributesTimedOut++;
2295     }
2296 
2297     auto &QuerriedAAs = QueryMap[ChangedAA];
2298     ChangedAAs.append(QuerriedAAs.begin(), QuerriedAAs.end());
2299   }
2300 
2301   LLVM_DEBUG({
2302     if (!Visited.empty())
2303       dbgs() << "\n[Attributor] Finalized " << Visited.size()
2304              << " abstract attributes.\n";
2305   });
2306 
2307   unsigned NumManifested = 0;
2308   unsigned NumAtFixpoint = 0;
2309   ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
2310   for (AbstractAttribute *AA : AllAbstractAttributes) {
2311     AbstractState &State = AA->getState();
2312 
2313     // If there is not already a fixpoint reached, we can now take the
2314     // optimistic state. This is correct because we enforced a pessimistic one
2315     // on abstract attributes that were transitively dependent on a changed one
2316     // already above.
2317     if (!State.isAtFixpoint())
2318       State.indicateOptimisticFixpoint();
2319 
2320     // If the state is invalid, we do not try to manifest it.
2321     if (!State.isValidState())
2322       continue;
2323 
2324     // Manifest the state and record if we changed the IR.
2325     ChangeStatus LocalChange = AA->manifest(*this);
2326     if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
2327       AA->trackStatistics();
2328 
2329     ManifestChange = ManifestChange | LocalChange;
2330 
2331     NumAtFixpoint++;
2332     NumManifested += (LocalChange == ChangeStatus::CHANGED);
2333   }
2334 
2335   (void)NumManifested;
2336   (void)NumAtFixpoint;
2337   LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
2338                     << " arguments while " << NumAtFixpoint
2339                     << " were in a valid fixpoint state\n");
2340 
2341   // If verification is requested, we finished this run at a fixpoint, and the
2342   // IR was changed, we re-run the whole fixpoint analysis, starting at
2343   // re-initialization of the arguments. This re-run should not result in an IR
2344   // change. Though, the (virtual) state of attributes at the end of the re-run
2345   // might be more optimistic than the known state or the IR state if the better
2346   // state cannot be manifested.
2347   if (VerifyAttributor && FinishedAtFixpoint &&
2348       ManifestChange == ChangeStatus::CHANGED) {
2349     VerifyAttributor = false;
2350     ChangeStatus VerifyStatus = run(InfoCache);
2351     if (VerifyStatus != ChangeStatus::UNCHANGED)
2352       llvm_unreachable(
2353           "Attributor verification failed, re-run did result in an IR change "
2354           "even after a fixpoint was reached in the original run. (False "
2355           "positives possible!)");
2356     VerifyAttributor = true;
2357   }
2358 
2359   NumAttributesManifested += NumManifested;
2360   NumAttributesValidFixpoint += NumAtFixpoint;
2361 
2362   return ManifestChange;
2363 }
2364 
2365 /// Helper function that checks if an abstract attribute of type \p AAType
2366 /// should be created for \p V (with argument number \p ArgNo) and if so creates
2367 /// and registers it with the Attributor \p A.
2368 ///
2369 /// This method will look at the provided whitelist. If one is given and the
2370 /// kind \p AAType::ID is not contained, no abstract attribute is created.
2371 ///
2372 /// \returns The created abstract argument, or nullptr if none was created.
2373 template <typename AAType, typename ValueType, typename... ArgsTy>
2374 static AAType *checkAndRegisterAA(const Function &F, Attributor &A,
2375                                   DenseSet<const char *> *Whitelist,
2376                                   ValueType &V, int ArgNo, ArgsTy... Args) {
2377   if (Whitelist && !Whitelist->count(&AAType::ID))
2378     return nullptr;
2379 
2380   return &A.registerAA<AAType>(*new AAType(V, Args...), ArgNo);
2381 }
2382 
2383 void Attributor::identifyDefaultAbstractAttributes(
2384     Function &F, InformationCache &InfoCache,
2385     DenseSet<const char *> *Whitelist) {
2386 
2387   // Check for dead BasicBlocks in every function.
2388   // We need dead instruction detection because we do not want to deal with
2389   // broken IR in which SSA rules do not apply.
2390   checkAndRegisterAA<AAIsDeadFunction>(F, *this, /* Whitelist */ nullptr, F,
2391                                        -1);
2392 
2393   // Every function might be "will-return".
2394   checkAndRegisterAA<AAWillReturnFunction>(F, *this, Whitelist, F, -1);
2395 
2396   // Every function can be nounwind.
2397   checkAndRegisterAA<AANoUnwindFunction>(F, *this, Whitelist, F, -1);
2398 
2399   // Every function might be marked "nosync"
2400   checkAndRegisterAA<AANoSyncFunction>(F, *this, Whitelist, F, -1);
2401 
2402   // Every function might be "no-free".
2403   checkAndRegisterAA<AANoFreeFunction>(F, *this, Whitelist, F, -1);
2404 
2405   // Every function might be "no-return".
2406   checkAndRegisterAA<AANoReturnFunction>(F, *this, Whitelist, F, -1);
2407 
2408   // Return attributes are only appropriate if the return type is non void.
2409   Type *ReturnType = F.getReturnType();
2410   if (!ReturnType->isVoidTy()) {
2411     // Argument attribute "returned" --- Create only one per function even
2412     // though it is an argument attribute.
2413     checkAndRegisterAA<AAReturnedValuesFunction>(F, *this, Whitelist, F, -1);
2414 
2415     if (ReturnType->isPointerTy()) {
2416       // Every function with pointer return type might be marked align.
2417       checkAndRegisterAA<AAAlignReturned>(F, *this, Whitelist, F, -1);
2418 
2419       // Every function with pointer return type might be marked nonnull.
2420       checkAndRegisterAA<AANonNullReturned>(F, *this, Whitelist, F, -1);
2421 
2422       // Every function with pointer return type might be marked noalias.
2423       checkAndRegisterAA<AANoAliasReturned>(F, *this, Whitelist, F, -1);
2424 
2425       // Every function with pointer return type might be marked
2426       // dereferenceable.
2427       checkAndRegisterAA<AADereferenceableReturned>(F, *this, Whitelist, F, -1);
2428     }
2429   }
2430 
2431   for (Argument &Arg : F.args()) {
2432     if (Arg.getType()->isPointerTy()) {
2433       // Every argument with pointer type might be marked nonnull.
2434       checkAndRegisterAA<AANonNullArgument>(F, *this, Whitelist, Arg,
2435                                             Arg.getArgNo());
2436 
2437       // Every argument with pointer type might be marked dereferenceable.
2438       checkAndRegisterAA<AADereferenceableArgument>(F, *this, Whitelist, Arg,
2439                                                     Arg.getArgNo());
2440 
2441       // Every argument with pointer type might be marked align.
2442       checkAndRegisterAA<AAAlignArgument>(F, *this, Whitelist, Arg,
2443                                           Arg.getArgNo());
2444     }
2445   }
2446 
2447   // Walk all instructions to find more attribute opportunities and also
2448   // interesting instructions that might be queried by abstract attributes
2449   // during their initialization or update.
2450   auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&F];
2451   auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&F];
2452 
2453   for (Instruction &I : instructions(&F)) {
2454     bool IsInterestingOpcode = false;
2455 
2456     // To allow easy access to all instructions in a function with a given
2457     // opcode we store them in the InfoCache. As not all opcodes are interesting
2458     // to concrete attributes we only cache the ones that are as identified in
2459     // the following switch.
2460     // Note: There are no concrete attributes now so this is initially empty.
2461     switch (I.getOpcode()) {
2462     default:
2463       assert((!ImmutableCallSite(&I)) && (!isa<CallBase>(&I)) &&
2464              "New call site/base instruction type needs to be known int the "
2465              "attributor.");
2466       break;
2467     case Instruction::Call:
2468     case Instruction::CallBr:
2469     case Instruction::Invoke:
2470     case Instruction::CleanupRet:
2471     case Instruction::CatchSwitch:
2472     case Instruction::Resume:
2473     case Instruction::Ret:
2474       IsInterestingOpcode = true;
2475     }
2476     if (IsInterestingOpcode)
2477       InstOpcodeMap[I.getOpcode()].push_back(&I);
2478     if (I.mayReadOrWriteMemory())
2479       ReadOrWriteInsts.push_back(&I);
2480 
2481     CallSite CS(&I);
2482     if (CS && CS.getCalledFunction()) {
2483       for (int i = 0, e = CS.getCalledFunction()->arg_size(); i < e; i++) {
2484         if (!CS.getArgument(i)->getType()->isPointerTy())
2485           continue;
2486 
2487         // Call site argument attribute "non-null".
2488         checkAndRegisterAA<AANonNullCallSiteArgument>(F, *this, Whitelist, I, i,
2489                                                       i);
2490 
2491         // Call site argument attribute "dereferenceable".
2492         checkAndRegisterAA<AADereferenceableCallSiteArgument>(
2493             F, *this, Whitelist, I, i, i);
2494 
2495         // Call site argument attribute "align".
2496         checkAndRegisterAA<AAAlignCallSiteArgument>(F, *this, Whitelist, I, i,
2497                                                     i);
2498       }
2499     }
2500   }
2501 }
2502 
2503 /// Helpers to ease debugging through output streams and print calls.
2504 ///
2505 ///{
2506 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
2507   return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
2508 }
2509 
2510 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
2511   switch (AP) {
2512   case IRPosition::IRP_ARGUMENT:
2513     return OS << "arg";
2514   case IRPosition::IRP_CALL_SITE_ARGUMENT:
2515     return OS << "cs_arg";
2516   case IRPosition::IRP_FUNCTION:
2517     return OS << "fn";
2518   case IRPosition::IRP_RETURNED:
2519     return OS << "fn_ret";
2520   }
2521   llvm_unreachable("Unknown attribute position!");
2522 }
2523 
2524 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
2525   const Value *AV = Pos.getAssociatedValue();
2526   return OS << "{" << Pos.getPositionKind() << ":"
2527             << (AV ? AV->getName() : "n/a") << " ["
2528             << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}";
2529 }
2530 
2531 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
2532   return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
2533 }
2534 
2535 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
2536   AA.print(OS);
2537   return OS;
2538 }
2539 
2540 void AbstractAttribute::print(raw_ostream &OS) const {
2541   OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState()
2542      << "]";
2543 }
2544 ///}
2545 
2546 /// ----------------------------------------------------------------------------
2547 ///                       Pass (Manager) Boilerplate
2548 /// ----------------------------------------------------------------------------
2549 
2550 static bool runAttributorOnModule(Module &M) {
2551   if (DisableAttributor)
2552     return false;
2553 
2554   LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << M.size()
2555                     << " functions.\n");
2556 
2557   // Create an Attributor and initially empty information cache that is filled
2558   // while we identify default attribute opportunities.
2559   Attributor A;
2560   InformationCache InfoCache;
2561 
2562   for (Function &F : M) {
2563     // TODO: Not all attributes require an exact definition. Find a way to
2564     //       enable deduction for some but not all attributes in case the
2565     //       definition might be changed at runtime, see also
2566     //       http://lists.llvm.org/pipermail/llvm-dev/2018-February/121275.html.
2567     // TODO: We could always determine abstract attributes and if sufficient
2568     //       information was found we could duplicate the functions that do not
2569     //       have an exact definition.
2570     if (!F.hasExactDefinition()) {
2571       NumFnWithoutExactDefinition++;
2572       continue;
2573     }
2574 
2575     // For now we ignore naked and optnone functions.
2576     if (F.hasFnAttribute(Attribute::Naked) ||
2577         F.hasFnAttribute(Attribute::OptimizeNone))
2578       continue;
2579 
2580     NumFnWithExactDefinition++;
2581 
2582     // Populate the Attributor with abstract attribute opportunities in the
2583     // function and the information cache with IR information.
2584     A.identifyDefaultAbstractAttributes(F, InfoCache);
2585   }
2586 
2587   return A.run(InfoCache) == ChangeStatus::CHANGED;
2588 }
2589 
2590 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
2591   if (runAttributorOnModule(M)) {
2592     // FIXME: Think about passes we will preserve and add them here.
2593     return PreservedAnalyses::none();
2594   }
2595   return PreservedAnalyses::all();
2596 }
2597 
2598 namespace {
2599 
2600 struct AttributorLegacyPass : public ModulePass {
2601   static char ID;
2602 
2603   AttributorLegacyPass() : ModulePass(ID) {
2604     initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
2605   }
2606 
2607   bool runOnModule(Module &M) override {
2608     if (skipModule(M))
2609       return false;
2610     return runAttributorOnModule(M);
2611   }
2612 
2613   void getAnalysisUsage(AnalysisUsage &AU) const override {
2614     // FIXME: Think about passes we will preserve and add them here.
2615     AU.setPreservesCFG();
2616   }
2617 };
2618 
2619 } // end anonymous namespace
2620 
2621 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
2622 
2623 char AttributorLegacyPass::ID = 0;
2624 
2625 const char AAReturnedValues::ID = 0;
2626 const char AANoUnwind::ID = 0;
2627 const char AANoSync::ID = 0;
2628 const char AANoFree::ID = 0;
2629 const char AANonNull::ID = 0;
2630 const char AANoRecurse::ID = 0;
2631 const char AAWillReturn::ID = 0;
2632 const char AANoAlias::ID = 0;
2633 const char AANoReturn::ID = 0;
2634 const char AAIsDead::ID = 0;
2635 const char AADereferenceable::ID = 0;
2636 const char AAAlign::ID = 0;
2637 
2638 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
2639                       "Deduce and propagate attributes", false, false)
2640 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
2641                     "Deduce and propagate attributes", false, false)
2642