1 //===- AttributorAttributes.cpp - Attributes for Attributor 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 // See the Attributor.h file comment and the class descriptions in that file for
10 // more information.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/Attributor.h"
15 
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/CaptureTracking.h"
19 #include "llvm/Analysis/LazyValueInfo.h"
20 #include "llvm/Analysis/MemoryBuiltins.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/NoFolder.h"
25 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 
28 #include <cassert>
29 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "attributor"
33 
34 static cl::opt<bool> ManifestInternal(
35     "attributor-manifest-internal", cl::Hidden,
36     cl::desc("Manifest Attributor internal string attributes."),
37     cl::init(false));
38 
39 static cl::opt<int> MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128),
40                                        cl::Hidden);
41 
42 // Some helper macros to deal with statistics tracking.
43 //
44 // Usage:
45 // For simple IR attribute tracking overload trackStatistics in the abstract
46 // attribute and choose the right STATS_DECLTRACK_********* macro,
47 // e.g.,:
48 //  void trackStatistics() const override {
49 //    STATS_DECLTRACK_ARG_ATTR(returned)
50 //  }
51 // If there is a single "increment" side one can use the macro
52 // STATS_DECLTRACK with a custom message. If there are multiple increment
53 // sides, STATS_DECL and STATS_TRACK can also be used separatly.
54 //
55 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME)                                     \
56   ("Number of " #TYPE " marked '" #NAME "'")
57 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
58 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG);
59 #define STATS_DECL(NAME, TYPE, MSG)                                            \
60   STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG);
61 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
62 #define STATS_DECLTRACK(NAME, TYPE, MSG)                                       \
63   {                                                                            \
64     STATS_DECL(NAME, TYPE, MSG)                                                \
65     STATS_TRACK(NAME, TYPE)                                                    \
66   }
67 #define STATS_DECLTRACK_ARG_ATTR(NAME)                                         \
68   STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
69 #define STATS_DECLTRACK_CSARG_ATTR(NAME)                                       \
70   STATS_DECLTRACK(NAME, CSArguments,                                           \
71                   BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
72 #define STATS_DECLTRACK_FN_ATTR(NAME)                                          \
73   STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
74 #define STATS_DECLTRACK_CS_ATTR(NAME)                                          \
75   STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
76 #define STATS_DECLTRACK_FNRET_ATTR(NAME)                                       \
77   STATS_DECLTRACK(NAME, FunctionReturn,                                        \
78                   BUILD_STAT_MSG_IR_ATTR(function returns, NAME))
79 #define STATS_DECLTRACK_CSRET_ATTR(NAME)                                       \
80   STATS_DECLTRACK(NAME, CSReturn,                                              \
81                   BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
82 #define STATS_DECLTRACK_FLOATING_ATTR(NAME)                                    \
83   STATS_DECLTRACK(NAME, Floating,                                              \
84                   ("Number of floating values known to be '" #NAME "'"))
85 
86 // Specialization of the operator<< for abstract attributes subclasses. This
87 // disambiguates situations where multiple operators are applicable.
88 namespace llvm {
89 #define PIPE_OPERATOR(CLASS)                                                   \
90   raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) {                  \
91     return OS << static_cast<const AbstractAttribute &>(AA);                   \
92   }
93 
94 PIPE_OPERATOR(AAIsDead)
95 PIPE_OPERATOR(AANoUnwind)
96 PIPE_OPERATOR(AANoSync)
97 PIPE_OPERATOR(AANoRecurse)
98 PIPE_OPERATOR(AAWillReturn)
99 PIPE_OPERATOR(AANoReturn)
100 PIPE_OPERATOR(AAReturnedValues)
101 PIPE_OPERATOR(AANonNull)
102 PIPE_OPERATOR(AANoAlias)
103 PIPE_OPERATOR(AADereferenceable)
104 PIPE_OPERATOR(AAAlign)
105 PIPE_OPERATOR(AANoCapture)
106 PIPE_OPERATOR(AAValueSimplify)
107 PIPE_OPERATOR(AANoFree)
108 PIPE_OPERATOR(AAHeapToStack)
109 PIPE_OPERATOR(AAReachability)
110 PIPE_OPERATOR(AAMemoryBehavior)
111 PIPE_OPERATOR(AAMemoryLocation)
112 PIPE_OPERATOR(AAValueConstantRange)
113 PIPE_OPERATOR(AAPrivatizablePtr)
114 
115 #undef PIPE_OPERATOR
116 } // namespace llvm
117 
118 namespace {
119 
120 static Optional<ConstantInt *>
121 getAssumedConstantInt(Attributor &A, const Value &V,
122                       const AbstractAttribute &AA,
123                       bool &UsedAssumedInformation) {
124   Optional<Constant *> C = A.getAssumedConstant(V, AA, UsedAssumedInformation);
125   if (C.hasValue())
126     return dyn_cast_or_null<ConstantInt>(C.getValue());
127   return llvm::None;
128 }
129 
130 /// Get pointer operand of memory accessing instruction. If \p I is
131 /// not a memory accessing instruction, return nullptr. If \p AllowVolatile,
132 /// is set to false and the instruction is volatile, return nullptr.
133 static const Value *getPointerOperand(const Instruction *I,
134                                       bool AllowVolatile) {
135   if (auto *LI = dyn_cast<LoadInst>(I)) {
136     if (!AllowVolatile && LI->isVolatile())
137       return nullptr;
138     return LI->getPointerOperand();
139   }
140 
141   if (auto *SI = dyn_cast<StoreInst>(I)) {
142     if (!AllowVolatile && SI->isVolatile())
143       return nullptr;
144     return SI->getPointerOperand();
145   }
146 
147   if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) {
148     if (!AllowVolatile && CXI->isVolatile())
149       return nullptr;
150     return CXI->getPointerOperand();
151   }
152 
153   if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) {
154     if (!AllowVolatile && RMWI->isVolatile())
155       return nullptr;
156     return RMWI->getPointerOperand();
157   }
158 
159   return nullptr;
160 }
161 
162 /// Helper function to create a pointer of type \p ResTy, based on \p Ptr, and
163 /// advanced by \p Offset bytes. To aid later analysis the method tries to build
164 /// getelement pointer instructions that traverse the natural type of \p Ptr if
165 /// possible. If that fails, the remaining offset is adjusted byte-wise, hence
166 /// through a cast to i8*.
167 ///
168 /// TODO: This could probably live somewhere more prominantly if it doesn't
169 ///       already exist.
170 static Value *constructPointer(Type *ResTy, Value *Ptr, int64_t Offset,
171                                IRBuilder<NoFolder> &IRB, const DataLayout &DL) {
172   assert(Offset >= 0 && "Negative offset not supported yet!");
173   LLVM_DEBUG(dbgs() << "Construct pointer: " << *Ptr << " + " << Offset
174                     << "-bytes as " << *ResTy << "\n");
175 
176   // The initial type we are trying to traverse to get nice GEPs.
177   Type *Ty = Ptr->getType();
178 
179   SmallVector<Value *, 4> Indices;
180   std::string GEPName = Ptr->getName().str();
181   while (Offset) {
182     uint64_t Idx, Rem;
183 
184     if (auto *STy = dyn_cast<StructType>(Ty)) {
185       const StructLayout *SL = DL.getStructLayout(STy);
186       if (int64_t(SL->getSizeInBytes()) < Offset)
187         break;
188       Idx = SL->getElementContainingOffset(Offset);
189       assert(Idx < STy->getNumElements() && "Offset calculation error!");
190       Rem = Offset - SL->getElementOffset(Idx);
191       Ty = STy->getElementType(Idx);
192     } else if (auto *PTy = dyn_cast<PointerType>(Ty)) {
193       Ty = PTy->getElementType();
194       if (!Ty->isSized())
195         break;
196       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
197       assert(ElementSize && "Expected type with size!");
198       Idx = Offset / ElementSize;
199       Rem = Offset % ElementSize;
200     } else {
201       // Non-aggregate type, we cast and make byte-wise progress now.
202       break;
203     }
204 
205     LLVM_DEBUG(errs() << "Ty: " << *Ty << " Offset: " << Offset
206                       << " Idx: " << Idx << " Rem: " << Rem << "\n");
207 
208     GEPName += "." + std::to_string(Idx);
209     Indices.push_back(ConstantInt::get(IRB.getInt32Ty(), Idx));
210     Offset = Rem;
211   }
212 
213   // Create a GEP if we collected indices above.
214   if (Indices.size())
215     Ptr = IRB.CreateGEP(Ptr, Indices, GEPName);
216 
217   // If an offset is left we use byte-wise adjustment.
218   if (Offset) {
219     Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy());
220     Ptr = IRB.CreateGEP(Ptr, IRB.getInt32(Offset),
221                         GEPName + ".b" + Twine(Offset));
222   }
223 
224   // Ensure the result has the requested type.
225   Ptr = IRB.CreateBitOrPointerCast(Ptr, ResTy, Ptr->getName() + ".cast");
226 
227   LLVM_DEBUG(dbgs() << "Constructed pointer: " << *Ptr << "\n");
228   return Ptr;
229 }
230 
231 /// Recursively visit all values that might become \p IRP at some point. This
232 /// will be done by looking through cast instructions, selects, phis, and calls
233 /// with the "returned" attribute. Once we cannot look through the value any
234 /// further, the callback \p VisitValueCB is invoked and passed the current
235 /// value, the \p State, and a flag to indicate if we stripped anything.
236 /// Stripped means that we unpacked the value associated with \p IRP at least
237 /// once. Note that the value used for the callback may still be the value
238 /// associated with \p IRP (due to PHIs). To limit how much effort is invested,
239 /// we will never visit more values than specified by \p MaxValues.
240 template <typename AAType, typename StateTy>
241 static bool genericValueTraversal(
242     Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State,
243     function_ref<bool(Value &, const Instruction *, StateTy &, bool)>
244         VisitValueCB,
245     const Instruction *CtxI, int MaxValues = 16,
246     function_ref<Value *(Value *)> StripCB = nullptr) {
247 
248   const AAIsDead *LivenessAA = nullptr;
249   if (IRP.getAnchorScope())
250     LivenessAA = &A.getAAFor<AAIsDead>(
251         QueryingAA, IRPosition::function(*IRP.getAnchorScope()),
252         /* TrackDependence */ false);
253   bool AnyDead = false;
254 
255   using Item = std::pair<Value *, const Instruction *>;
256   SmallSet<Item, 16> Visited;
257   SmallVector<Item, 16> Worklist;
258   Worklist.push_back({&IRP.getAssociatedValue(), CtxI});
259 
260   int Iteration = 0;
261   do {
262     Item I = Worklist.pop_back_val();
263     Value *V = I.first;
264     CtxI = I.second;
265     if (StripCB)
266       V = StripCB(V);
267 
268     // Check if we should process the current value. To prevent endless
269     // recursion keep a record of the values we followed!
270     if (!Visited.insert(I).second)
271       continue;
272 
273     // Make sure we limit the compile time for complex expressions.
274     if (Iteration++ >= MaxValues)
275       return false;
276 
277     // Explicitly look through calls with a "returned" attribute if we do
278     // not have a pointer as stripPointerCasts only works on them.
279     Value *NewV = nullptr;
280     if (V->getType()->isPointerTy()) {
281       NewV = V->stripPointerCasts();
282     } else {
283       CallSite CS(V);
284       if (CS && CS.getCalledFunction()) {
285         for (Argument &Arg : CS.getCalledFunction()->args())
286           if (Arg.hasReturnedAttr()) {
287             NewV = CS.getArgOperand(Arg.getArgNo());
288             break;
289           }
290       }
291     }
292     if (NewV && NewV != V) {
293       Worklist.push_back({NewV, CtxI});
294       continue;
295     }
296 
297     // Look through select instructions, visit both potential values.
298     if (auto *SI = dyn_cast<SelectInst>(V)) {
299       Worklist.push_back({SI->getTrueValue(), CtxI});
300       Worklist.push_back({SI->getFalseValue(), CtxI});
301       continue;
302     }
303 
304     // Look through phi nodes, visit all live operands.
305     if (auto *PHI = dyn_cast<PHINode>(V)) {
306       assert(LivenessAA &&
307              "Expected liveness in the presence of instructions!");
308       for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
309         BasicBlock *IncomingBB = PHI->getIncomingBlock(u);
310         if (A.isAssumedDead(*IncomingBB->getTerminator(), &QueryingAA,
311                             LivenessAA,
312                             /* CheckBBLivenessOnly */ true)) {
313           AnyDead = true;
314           continue;
315         }
316         Worklist.push_back(
317             {PHI->getIncomingValue(u), IncomingBB->getTerminator()});
318       }
319       continue;
320     }
321 
322     // Once a leaf is reached we inform the user through the callback.
323     if (!VisitValueCB(*V, CtxI, State, Iteration > 1))
324       return false;
325   } while (!Worklist.empty());
326 
327   // If we actually used liveness information so we have to record a dependence.
328   if (AnyDead)
329     A.recordDependence(*LivenessAA, QueryingAA, DepClassTy::OPTIONAL);
330 
331   // All values have been visited.
332   return true;
333 }
334 
335 static const Value *
336 getBasePointerOfAccessPointerOperand(const Instruction *I, int64_t &BytesOffset,
337                                      const DataLayout &DL,
338                                      bool AllowNonInbounds = false) {
339   const Value *Ptr = getPointerOperand(I, /* AllowVolatile */ false);
340   if (!Ptr)
341     return nullptr;
342 
343   return GetPointerBaseWithConstantOffset(Ptr, BytesOffset, DL,
344                                           AllowNonInbounds);
345 }
346 
347 /// Helper function to clamp a state \p S of type \p StateType with the
348 /// information in \p R and indicate/return if \p S did change (as-in update is
349 /// required to be run again).
350 template <typename StateType>
351 ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R) {
352   auto Assumed = S.getAssumed();
353   S ^= R;
354   return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
355                                    : ChangeStatus::CHANGED;
356 }
357 
358 /// Clamp the information known for all returned values of a function
359 /// (identified by \p QueryingAA) into \p S.
360 template <typename AAType, typename StateType = typename AAType::StateType>
361 static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA,
362                                      StateType &S) {
363   LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for "
364                     << QueryingAA << " into " << S << "\n");
365 
366   assert((QueryingAA.getIRPosition().getPositionKind() ==
367               IRPosition::IRP_RETURNED ||
368           QueryingAA.getIRPosition().getPositionKind() ==
369               IRPosition::IRP_CALL_SITE_RETURNED) &&
370          "Can only clamp returned value states for a function returned or call "
371          "site returned position!");
372 
373   // Use an optional state as there might not be any return values and we want
374   // to join (IntegerState::operator&) the state of all there are.
375   Optional<StateType> T;
376 
377   // Callback for each possibly returned value.
378   auto CheckReturnValue = [&](Value &RV) -> bool {
379     const IRPosition &RVPos = IRPosition::value(RV);
380     const AAType &AA = A.getAAFor<AAType>(QueryingAA, RVPos);
381     LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr()
382                       << " @ " << RVPos << "\n");
383     const StateType &AAS = static_cast<const StateType &>(AA.getState());
384     if (T.hasValue())
385       *T &= AAS;
386     else
387       T = AAS;
388     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T
389                       << "\n");
390     return T->isValidState();
391   };
392 
393   if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA))
394     S.indicatePessimisticFixpoint();
395   else if (T.hasValue())
396     S ^= *T;
397 }
398 
399 /// Helper class to compose two generic deduction
400 template <typename AAType, typename Base, typename StateType,
401           template <typename...> class F, template <typename...> class G>
402 struct AAComposeTwoGenericDeduction
403     : public F<AAType, G<AAType, Base, StateType>, StateType> {
404   AAComposeTwoGenericDeduction(const IRPosition &IRP)
405       : F<AAType, G<AAType, Base, StateType>, StateType>(IRP) {}
406 
407   void initialize(Attributor &A) override {
408     F<AAType, G<AAType, Base, StateType>, StateType>::initialize(A);
409     G<AAType, Base, StateType>::initialize(A);
410   }
411 
412   /// See AbstractAttribute::updateImpl(...).
413   ChangeStatus updateImpl(Attributor &A) override {
414     ChangeStatus ChangedF =
415         F<AAType, G<AAType, Base, StateType>, StateType>::updateImpl(A);
416     ChangeStatus ChangedG = G<AAType, Base, StateType>::updateImpl(A);
417     return ChangedF | ChangedG;
418   }
419 };
420 
421 /// Helper class for generic deduction: return value -> returned position.
422 template <typename AAType, typename Base,
423           typename StateType = typename Base::StateType>
424 struct AAReturnedFromReturnedValues : public Base {
425   AAReturnedFromReturnedValues(const IRPosition &IRP) : Base(IRP) {}
426 
427   /// See AbstractAttribute::updateImpl(...).
428   ChangeStatus updateImpl(Attributor &A) override {
429     StateType S(StateType::getBestState(this->getState()));
430     clampReturnedValueStates<AAType, StateType>(A, *this, S);
431     // TODO: If we know we visited all returned values, thus no are assumed
432     // dead, we can take the known information from the state T.
433     return clampStateAndIndicateChange<StateType>(this->getState(), S);
434   }
435 };
436 
437 /// Clamp the information known at all call sites for a given argument
438 /// (identified by \p QueryingAA) into \p S.
439 template <typename AAType, typename StateType = typename AAType::StateType>
440 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA,
441                                         StateType &S) {
442   LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for "
443                     << QueryingAA << " into " << S << "\n");
444 
445   assert(QueryingAA.getIRPosition().getPositionKind() ==
446              IRPosition::IRP_ARGUMENT &&
447          "Can only clamp call site argument states for an argument position!");
448 
449   // Use an optional state as there might not be any return values and we want
450   // to join (IntegerState::operator&) the state of all there are.
451   Optional<StateType> T;
452 
453   // The argument number which is also the call site argument number.
454   unsigned ArgNo = QueryingAA.getIRPosition().getArgNo();
455 
456   auto CallSiteCheck = [&](AbstractCallSite ACS) {
457     const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
458     // Check if a coresponding argument was found or if it is on not associated
459     // (which can happen for callback calls).
460     if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
461       return false;
462 
463     const AAType &AA = A.getAAFor<AAType>(QueryingAA, ACSArgPos);
464     LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction()
465                       << " AA: " << AA.getAsStr() << " @" << ACSArgPos << "\n");
466     const StateType &AAS = static_cast<const StateType &>(AA.getState());
467     if (T.hasValue())
468       *T &= AAS;
469     else
470       T = AAS;
471     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T
472                       << "\n");
473     return T->isValidState();
474   };
475 
476   bool AllCallSitesKnown;
477   if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true,
478                               AllCallSitesKnown))
479     S.indicatePessimisticFixpoint();
480   else if (T.hasValue())
481     S ^= *T;
482 }
483 
484 /// Helper class for generic deduction: call site argument -> argument position.
485 template <typename AAType, typename Base,
486           typename StateType = typename AAType::StateType>
487 struct AAArgumentFromCallSiteArguments : public Base {
488   AAArgumentFromCallSiteArguments(const IRPosition &IRP) : Base(IRP) {}
489 
490   /// See AbstractAttribute::updateImpl(...).
491   ChangeStatus updateImpl(Attributor &A) override {
492     StateType S(StateType::getBestState(this->getState()));
493     clampCallSiteArgumentStates<AAType, StateType>(A, *this, S);
494     // TODO: If we know we visited all incoming values, thus no are assumed
495     // dead, we can take the known information from the state T.
496     return clampStateAndIndicateChange<StateType>(this->getState(), S);
497   }
498 };
499 
500 /// Helper class for generic replication: function returned -> cs returned.
501 template <typename AAType, typename Base,
502           typename StateType = typename Base::StateType>
503 struct AACallSiteReturnedFromReturned : public Base {
504   AACallSiteReturnedFromReturned(const IRPosition &IRP) : Base(IRP) {}
505 
506   /// See AbstractAttribute::updateImpl(...).
507   ChangeStatus updateImpl(Attributor &A) override {
508     assert(this->getIRPosition().getPositionKind() ==
509                IRPosition::IRP_CALL_SITE_RETURNED &&
510            "Can only wrap function returned positions for call site returned "
511            "positions!");
512     auto &S = this->getState();
513 
514     const Function *AssociatedFunction =
515         this->getIRPosition().getAssociatedFunction();
516     if (!AssociatedFunction)
517       return S.indicatePessimisticFixpoint();
518 
519     IRPosition FnPos = IRPosition::returned(*AssociatedFunction);
520     const AAType &AA = A.getAAFor<AAType>(*this, FnPos);
521     return clampStateAndIndicateChange(
522         S, static_cast<const StateType &>(AA.getState()));
523   }
524 };
525 
526 /// Helper class for generic deduction using must-be-executed-context
527 /// Base class is required to have `followUse` method.
528 
529 /// bool followUse(Attributor &A, const Use *U, const Instruction *I)
530 /// U - Underlying use.
531 /// I - The user of the \p U.
532 /// `followUse` returns true if the value should be tracked transitively.
533 
534 template <typename AAType, typename Base,
535           typename StateType = typename AAType::StateType>
536 struct AAFromMustBeExecutedContext : public Base {
537   AAFromMustBeExecutedContext(const IRPosition &IRP) : Base(IRP) {}
538 
539   void initialize(Attributor &A) override {
540     Base::initialize(A);
541     const IRPosition &IRP = this->getIRPosition();
542     Instruction *CtxI = IRP.getCtxI();
543 
544     if (!CtxI)
545       return;
546 
547     for (const Use &U : IRP.getAssociatedValue().uses())
548       Uses.insert(&U);
549   }
550 
551   /// Helper function to accumulate uses.
552   void followUsesInContext(Attributor &A,
553                            MustBeExecutedContextExplorer &Explorer,
554                            const Instruction *CtxI,
555                            SetVector<const Use *> &Uses, StateType &State) {
556     auto EIt = Explorer.begin(CtxI), EEnd = Explorer.end(CtxI);
557     for (unsigned u = 0; u < Uses.size(); ++u) {
558       const Use *U = Uses[u];
559       if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) {
560         bool Found = Explorer.findInContextOf(UserI, EIt, EEnd);
561         if (Found && Base::followUse(A, U, UserI, State))
562           for (const Use &Us : UserI->uses())
563             Uses.insert(&Us);
564       }
565     }
566   }
567 
568   /// See AbstractAttribute::updateImpl(...).
569   ChangeStatus updateImpl(Attributor &A) override {
570     auto BeforeState = this->getState();
571     auto &S = this->getState();
572     Instruction *CtxI = this->getIRPosition().getCtxI();
573     if (!CtxI)
574       return ChangeStatus::UNCHANGED;
575 
576     MustBeExecutedContextExplorer &Explorer =
577         A.getInfoCache().getMustBeExecutedContextExplorer();
578 
579     followUsesInContext(A, Explorer, CtxI, Uses, S);
580 
581     if (this->isAtFixpoint())
582       return ChangeStatus::CHANGED;
583 
584     SmallVector<const BranchInst *, 4> BrInsts;
585     auto Pred = [&](const Instruction *I) {
586       if (const BranchInst *Br = dyn_cast<BranchInst>(I))
587         if (Br->isConditional())
588           BrInsts.push_back(Br);
589       return true;
590     };
591 
592     // Here, accumulate conditional branch instructions in the context. We
593     // explore the child paths and collect the known states. The disjunction of
594     // those states can be merged to its own state. Let ParentState_i be a state
595     // to indicate the known information for an i-th branch instruction in the
596     // context. ChildStates are created for its successors respectively.
597     //
598     // ParentS_1 = ChildS_{1, 1} /\ ChildS_{1, 2} /\ ... /\ ChildS_{1, n_1}
599     // ParentS_2 = ChildS_{2, 1} /\ ChildS_{2, 2} /\ ... /\ ChildS_{2, n_2}
600     //      ...
601     // ParentS_m = ChildS_{m, 1} /\ ChildS_{m, 2} /\ ... /\ ChildS_{m, n_m}
602     //
603     // Known State |= ParentS_1 \/ ParentS_2 \/... \/ ParentS_m
604     //
605     // FIXME: Currently, recursive branches are not handled. For example, we
606     // can't deduce that ptr must be dereferenced in below function.
607     //
608     // void f(int a, int c, int *ptr) {
609     //    if(a)
610     //      if (b) {
611     //        *ptr = 0;
612     //      } else {
613     //        *ptr = 1;
614     //      }
615     //    else {
616     //      if (b) {
617     //        *ptr = 0;
618     //      } else {
619     //        *ptr = 1;
620     //      }
621     //    }
622     // }
623 
624     Explorer.checkForAllContext(CtxI, Pred);
625     for (const BranchInst *Br : BrInsts) {
626       StateType ParentState;
627 
628       // The known state of the parent state is a conjunction of children's
629       // known states so it is initialized with a best state.
630       ParentState.indicateOptimisticFixpoint();
631 
632       for (const BasicBlock *BB : Br->successors()) {
633         StateType ChildState;
634 
635         size_t BeforeSize = Uses.size();
636         followUsesInContext(A, Explorer, &BB->front(), Uses, ChildState);
637 
638         // Erase uses which only appear in the child.
639         for (auto It = Uses.begin() + BeforeSize; It != Uses.end();)
640           It = Uses.erase(It);
641 
642         ParentState &= ChildState;
643       }
644 
645       // Use only known state.
646       S += ParentState;
647     }
648 
649     return BeforeState == S ? ChangeStatus::UNCHANGED : ChangeStatus::CHANGED;
650   }
651 
652 private:
653   /// Container for (transitive) uses of the associated value.
654   SetVector<const Use *> Uses;
655 };
656 
657 template <typename AAType, typename Base,
658           typename StateType = typename AAType::StateType>
659 using AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext =
660     AAComposeTwoGenericDeduction<AAType, Base, StateType,
661                                  AAFromMustBeExecutedContext,
662                                  AAArgumentFromCallSiteArguments>;
663 
664 template <typename AAType, typename Base,
665           typename StateType = typename AAType::StateType>
666 using AACallSiteReturnedFromReturnedAndMustBeExecutedContext =
667     AAComposeTwoGenericDeduction<AAType, Base, StateType,
668                                  AAFromMustBeExecutedContext,
669                                  AACallSiteReturnedFromReturned>;
670 
671 /// -----------------------NoUnwind Function Attribute--------------------------
672 
673 struct AANoUnwindImpl : AANoUnwind {
674   AANoUnwindImpl(const IRPosition &IRP) : AANoUnwind(IRP) {}
675 
676   const std::string getAsStr() const override {
677     return getAssumed() ? "nounwind" : "may-unwind";
678   }
679 
680   /// See AbstractAttribute::updateImpl(...).
681   ChangeStatus updateImpl(Attributor &A) override {
682     auto Opcodes = {
683         (unsigned)Instruction::Invoke,      (unsigned)Instruction::CallBr,
684         (unsigned)Instruction::Call,        (unsigned)Instruction::CleanupRet,
685         (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
686 
687     auto CheckForNoUnwind = [&](Instruction &I) {
688       if (!I.mayThrow())
689         return true;
690 
691       if (ImmutableCallSite ICS = ImmutableCallSite(&I)) {
692         const auto &NoUnwindAA =
693             A.getAAFor<AANoUnwind>(*this, IRPosition::callsite_function(ICS));
694         return NoUnwindAA.isAssumedNoUnwind();
695       }
696       return false;
697     };
698 
699     if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes))
700       return indicatePessimisticFixpoint();
701 
702     return ChangeStatus::UNCHANGED;
703   }
704 };
705 
706 struct AANoUnwindFunction final : public AANoUnwindImpl {
707   AANoUnwindFunction(const IRPosition &IRP) : AANoUnwindImpl(IRP) {}
708 
709   /// See AbstractAttribute::trackStatistics()
710   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
711 };
712 
713 /// NoUnwind attribute deduction for a call sites.
714 struct AANoUnwindCallSite final : AANoUnwindImpl {
715   AANoUnwindCallSite(const IRPosition &IRP) : AANoUnwindImpl(IRP) {}
716 
717   /// See AbstractAttribute::initialize(...).
718   void initialize(Attributor &A) override {
719     AANoUnwindImpl::initialize(A);
720     Function *F = getAssociatedFunction();
721     if (!F)
722       indicatePessimisticFixpoint();
723   }
724 
725   /// See AbstractAttribute::updateImpl(...).
726   ChangeStatus updateImpl(Attributor &A) override {
727     // TODO: Once we have call site specific value information we can provide
728     //       call site specific liveness information and then it makes
729     //       sense to specialize attributes for call sites arguments instead of
730     //       redirecting requests to the callee argument.
731     Function *F = getAssociatedFunction();
732     const IRPosition &FnPos = IRPosition::function(*F);
733     auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos);
734     return clampStateAndIndicateChange(
735         getState(),
736         static_cast<const AANoUnwind::StateType &>(FnAA.getState()));
737   }
738 
739   /// See AbstractAttribute::trackStatistics()
740   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); }
741 };
742 
743 /// --------------------- Function Return Values -------------------------------
744 
745 /// "Attribute" that collects all potential returned values and the return
746 /// instructions that they arise from.
747 ///
748 /// If there is a unique returned value R, the manifest method will:
749 ///   - mark R with the "returned" attribute, if R is an argument.
750 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState {
751 
752   /// Mapping of values potentially returned by the associated function to the
753   /// return instructions that might return them.
754   MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues;
755 
756   /// Mapping to remember the number of returned values for a call site such
757   /// that we can avoid updates if nothing changed.
758   DenseMap<const CallBase *, unsigned> NumReturnedValuesPerKnownAA;
759 
760   /// Set of unresolved calls returned by the associated function.
761   SmallSetVector<CallBase *, 4> UnresolvedCalls;
762 
763   /// State flags
764   ///
765   ///{
766   bool IsFixed = false;
767   bool IsValidState = true;
768   ///}
769 
770 public:
771   AAReturnedValuesImpl(const IRPosition &IRP) : AAReturnedValues(IRP) {}
772 
773   /// See AbstractAttribute::initialize(...).
774   void initialize(Attributor &A) override {
775     // Reset the state.
776     IsFixed = false;
777     IsValidState = true;
778     ReturnedValues.clear();
779 
780     Function *F = getAssociatedFunction();
781     if (!F) {
782       indicatePessimisticFixpoint();
783       return;
784     }
785     assert(!F->getReturnType()->isVoidTy() &&
786            "Did not expect a void return type!");
787 
788     // The map from instruction opcodes to those instructions in the function.
789     auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F);
790 
791     // Look through all arguments, if one is marked as returned we are done.
792     for (Argument &Arg : F->args()) {
793       if (Arg.hasReturnedAttr()) {
794         auto &ReturnInstSet = ReturnedValues[&Arg];
795         for (Instruction *RI : OpcodeInstMap[Instruction::Ret])
796           ReturnInstSet.insert(cast<ReturnInst>(RI));
797 
798         indicateOptimisticFixpoint();
799         return;
800       }
801     }
802 
803     if (!A.isFunctionIPOAmendable(*F))
804       indicatePessimisticFixpoint();
805   }
806 
807   /// See AbstractAttribute::manifest(...).
808   ChangeStatus manifest(Attributor &A) override;
809 
810   /// See AbstractAttribute::getState(...).
811   AbstractState &getState() override { return *this; }
812 
813   /// See AbstractAttribute::getState(...).
814   const AbstractState &getState() const override { return *this; }
815 
816   /// See AbstractAttribute::updateImpl(Attributor &A).
817   ChangeStatus updateImpl(Attributor &A) override;
818 
819   llvm::iterator_range<iterator> returned_values() override {
820     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
821   }
822 
823   llvm::iterator_range<const_iterator> returned_values() const override {
824     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
825   }
826 
827   const SmallSetVector<CallBase *, 4> &getUnresolvedCalls() const override {
828     return UnresolvedCalls;
829   }
830 
831   /// Return the number of potential return values, -1 if unknown.
832   size_t getNumReturnValues() const override {
833     return isValidState() ? ReturnedValues.size() : -1;
834   }
835 
836   /// Return an assumed unique return value if a single candidate is found. If
837   /// there cannot be one, return a nullptr. If it is not clear yet, return the
838   /// Optional::NoneType.
839   Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const;
840 
841   /// See AbstractState::checkForAllReturnedValues(...).
842   bool checkForAllReturnedValuesAndReturnInsts(
843       function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
844       const override;
845 
846   /// Pretty print the attribute similar to the IR representation.
847   const std::string getAsStr() const override;
848 
849   /// See AbstractState::isAtFixpoint().
850   bool isAtFixpoint() const override { return IsFixed; }
851 
852   /// See AbstractState::isValidState().
853   bool isValidState() const override { return IsValidState; }
854 
855   /// See AbstractState::indicateOptimisticFixpoint(...).
856   ChangeStatus indicateOptimisticFixpoint() override {
857     IsFixed = true;
858     return ChangeStatus::UNCHANGED;
859   }
860 
861   ChangeStatus indicatePessimisticFixpoint() override {
862     IsFixed = true;
863     IsValidState = false;
864     return ChangeStatus::CHANGED;
865   }
866 };
867 
868 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
869   ChangeStatus Changed = ChangeStatus::UNCHANGED;
870 
871   // Bookkeeping.
872   assert(isValidState());
873   STATS_DECLTRACK(KnownReturnValues, FunctionReturn,
874                   "Number of function with known return values");
875 
876   // Check if we have an assumed unique return value that we could manifest.
877   Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
878 
879   if (!UniqueRV.hasValue() || !UniqueRV.getValue())
880     return Changed;
881 
882   // Bookkeeping.
883   STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
884                   "Number of function with unique return");
885 
886   // Callback to replace the uses of CB with the constant C.
887   auto ReplaceCallSiteUsersWith = [&A](CallBase &CB, Constant &C) {
888     if (CB.getNumUses() == 0)
889       return ChangeStatus::UNCHANGED;
890     if (A.changeValueAfterManifest(CB, C))
891       return ChangeStatus::CHANGED;
892     return ChangeStatus::UNCHANGED;
893   };
894 
895   // If the assumed unique return value is an argument, annotate it.
896   if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
897     // TODO: This should be handled differently!
898     this->AnchorVal = UniqueRVArg;
899     this->KindOrArgNo = UniqueRVArg->getArgNo();
900     Changed = IRAttribute::manifest(A);
901   } else if (auto *RVC = dyn_cast<Constant>(UniqueRV.getValue())) {
902     // We can replace the returned value with the unique returned constant.
903     Value &AnchorValue = getAnchorValue();
904     if (Function *F = dyn_cast<Function>(&AnchorValue)) {
905       for (const Use &U : F->uses())
906         if (CallBase *CB = dyn_cast<CallBase>(U.getUser()))
907           if (CB->isCallee(&U)) {
908             Constant *RVCCast =
909                 CB->getType() == RVC->getType()
910                     ? RVC
911                     : ConstantExpr::getTruncOrBitCast(RVC, CB->getType());
912             Changed = ReplaceCallSiteUsersWith(*CB, *RVCCast) | Changed;
913           }
914     } else {
915       assert(isa<CallBase>(AnchorValue) &&
916              "Expcected a function or call base anchor!");
917       Constant *RVCCast =
918           AnchorValue.getType() == RVC->getType()
919               ? RVC
920               : ConstantExpr::getTruncOrBitCast(RVC, AnchorValue.getType());
921       Changed = ReplaceCallSiteUsersWith(cast<CallBase>(AnchorValue), *RVCCast);
922     }
923     if (Changed == ChangeStatus::CHANGED)
924       STATS_DECLTRACK(UniqueConstantReturnValue, FunctionReturn,
925                       "Number of function returns replaced by constant return");
926   }
927 
928   return Changed;
929 }
930 
931 const std::string AAReturnedValuesImpl::getAsStr() const {
932   return (isAtFixpoint() ? "returns(#" : "may-return(#") +
933          (isValidState() ? std::to_string(getNumReturnValues()) : "?") +
934          ")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]";
935 }
936 
937 Optional<Value *>
938 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const {
939   // If checkForAllReturnedValues provides a unique value, ignoring potential
940   // undef values that can also be present, it is assumed to be the actual
941   // return value and forwarded to the caller of this method. If there are
942   // multiple, a nullptr is returned indicating there cannot be a unique
943   // returned value.
944   Optional<Value *> UniqueRV;
945 
946   auto Pred = [&](Value &RV) -> bool {
947     // If we found a second returned value and neither the current nor the saved
948     // one is an undef, there is no unique returned value. Undefs are special
949     // since we can pretend they have any value.
950     if (UniqueRV.hasValue() && UniqueRV != &RV &&
951         !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) {
952       UniqueRV = nullptr;
953       return false;
954     }
955 
956     // Do not overwrite a value with an undef.
957     if (!UniqueRV.hasValue() || !isa<UndefValue>(RV))
958       UniqueRV = &RV;
959 
960     return true;
961   };
962 
963   if (!A.checkForAllReturnedValues(Pred, *this))
964     UniqueRV = nullptr;
965 
966   return UniqueRV;
967 }
968 
969 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
970     function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
971     const {
972   if (!isValidState())
973     return false;
974 
975   // Check all returned values but ignore call sites as long as we have not
976   // encountered an overdefined one during an update.
977   for (auto &It : ReturnedValues) {
978     Value *RV = It.first;
979 
980     CallBase *CB = dyn_cast<CallBase>(RV);
981     if (CB && !UnresolvedCalls.count(CB))
982       continue;
983 
984     if (!Pred(*RV, It.second))
985       return false;
986   }
987 
988   return true;
989 }
990 
991 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) {
992   size_t NumUnresolvedCalls = UnresolvedCalls.size();
993   bool Changed = false;
994 
995   // State used in the value traversals starting in returned values.
996   struct RVState {
997     // The map in which we collect return values -> return instrs.
998     decltype(ReturnedValues) &RetValsMap;
999     // The flag to indicate a change.
1000     bool &Changed;
1001     // The return instrs we come from.
1002     SmallSetVector<ReturnInst *, 4> RetInsts;
1003   };
1004 
1005   // Callback for a leaf value returned by the associated function.
1006   auto VisitValueCB = [](Value &Val, const Instruction *, RVState &RVS,
1007                          bool) -> bool {
1008     auto Size = RVS.RetValsMap[&Val].size();
1009     RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end());
1010     bool Inserted = RVS.RetValsMap[&Val].size() != Size;
1011     RVS.Changed |= Inserted;
1012     LLVM_DEBUG({
1013       if (Inserted)
1014         dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val
1015                << " => " << RVS.RetInsts.size() << "\n";
1016     });
1017     return true;
1018   };
1019 
1020   // Helper method to invoke the generic value traversal.
1021   auto VisitReturnedValue = [&](Value &RV, RVState &RVS,
1022                                 const Instruction *CtxI) {
1023     IRPosition RetValPos = IRPosition::value(RV);
1024     return genericValueTraversal<AAReturnedValues, RVState>(
1025         A, RetValPos, *this, RVS, VisitValueCB, CtxI);
1026   };
1027 
1028   // Callback for all "return intructions" live in the associated function.
1029   auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) {
1030     ReturnInst &Ret = cast<ReturnInst>(I);
1031     RVState RVS({ReturnedValues, Changed, {}});
1032     RVS.RetInsts.insert(&Ret);
1033     return VisitReturnedValue(*Ret.getReturnValue(), RVS, &I);
1034   };
1035 
1036   // Start by discovering returned values from all live returned instructions in
1037   // the associated function.
1038   if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret}))
1039     return indicatePessimisticFixpoint();
1040 
1041   // Once returned values "directly" present in the code are handled we try to
1042   // resolve returned calls.
1043   decltype(ReturnedValues) NewRVsMap;
1044   for (auto &It : ReturnedValues) {
1045     LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *It.first
1046                       << " by #" << It.second.size() << " RIs\n");
1047     CallBase *CB = dyn_cast<CallBase>(It.first);
1048     if (!CB || UnresolvedCalls.count(CB))
1049       continue;
1050 
1051     if (!CB->getCalledFunction()) {
1052       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB
1053                         << "\n");
1054       UnresolvedCalls.insert(CB);
1055       continue;
1056     }
1057 
1058     // TODO: use the function scope once we have call site AAReturnedValues.
1059     const auto &RetValAA = A.getAAFor<AAReturnedValues>(
1060         *this, IRPosition::function(*CB->getCalledFunction()));
1061     LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: "
1062                       << RetValAA << "\n");
1063 
1064     // Skip dead ends, thus if we do not know anything about the returned
1065     // call we mark it as unresolved and it will stay that way.
1066     if (!RetValAA.getState().isValidState()) {
1067       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB
1068                         << "\n");
1069       UnresolvedCalls.insert(CB);
1070       continue;
1071     }
1072 
1073     // Do not try to learn partial information. If the callee has unresolved
1074     // return values we will treat the call as unresolved/opaque.
1075     auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls();
1076     if (!RetValAAUnresolvedCalls.empty()) {
1077       UnresolvedCalls.insert(CB);
1078       continue;
1079     }
1080 
1081     // Now check if we can track transitively returned values. If possible, thus
1082     // if all return value can be represented in the current scope, do so.
1083     bool Unresolved = false;
1084     for (auto &RetValAAIt : RetValAA.returned_values()) {
1085       Value *RetVal = RetValAAIt.first;
1086       if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) ||
1087           isa<Constant>(RetVal))
1088         continue;
1089       // Anything that did not fit in the above categories cannot be resolved,
1090       // mark the call as unresolved.
1091       LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value "
1092                            "cannot be translated: "
1093                         << *RetVal << "\n");
1094       UnresolvedCalls.insert(CB);
1095       Unresolved = true;
1096       break;
1097     }
1098 
1099     if (Unresolved)
1100       continue;
1101 
1102     // Now track transitively returned values.
1103     unsigned &NumRetAA = NumReturnedValuesPerKnownAA[CB];
1104     if (NumRetAA == RetValAA.getNumReturnValues()) {
1105       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Skip call as it has not "
1106                            "changed since it was seen last\n");
1107       continue;
1108     }
1109     NumRetAA = RetValAA.getNumReturnValues();
1110 
1111     for (auto &RetValAAIt : RetValAA.returned_values()) {
1112       Value *RetVal = RetValAAIt.first;
1113       if (Argument *Arg = dyn_cast<Argument>(RetVal)) {
1114         // Arguments are mapped to call site operands and we begin the traversal
1115         // again.
1116         bool Unused = false;
1117         RVState RVS({NewRVsMap, Unused, RetValAAIt.second});
1118         VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS, CB);
1119         continue;
1120       } else if (isa<CallBase>(RetVal)) {
1121         // Call sites are resolved by the callee attribute over time, no need to
1122         // do anything for us.
1123         continue;
1124       } else if (isa<Constant>(RetVal)) {
1125         // Constants are valid everywhere, we can simply take them.
1126         NewRVsMap[RetVal].insert(It.second.begin(), It.second.end());
1127         continue;
1128       }
1129     }
1130   }
1131 
1132   // To avoid modifications to the ReturnedValues map while we iterate over it
1133   // we kept record of potential new entries in a copy map, NewRVsMap.
1134   for (auto &It : NewRVsMap) {
1135     assert(!It.second.empty() && "Entry does not add anything.");
1136     auto &ReturnInsts = ReturnedValues[It.first];
1137     for (ReturnInst *RI : It.second)
1138       if (ReturnInsts.insert(RI)) {
1139         LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value "
1140                           << *It.first << " => " << *RI << "\n");
1141         Changed = true;
1142       }
1143   }
1144 
1145   Changed |= (NumUnresolvedCalls != UnresolvedCalls.size());
1146   return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
1147 }
1148 
1149 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl {
1150   AAReturnedValuesFunction(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {}
1151 
1152   /// See AbstractAttribute::trackStatistics()
1153   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) }
1154 };
1155 
1156 /// Returned values information for a call sites.
1157 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl {
1158   AAReturnedValuesCallSite(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {}
1159 
1160   /// See AbstractAttribute::initialize(...).
1161   void initialize(Attributor &A) override {
1162     // TODO: Once we have call site specific value information we can provide
1163     //       call site specific liveness information and then it makes
1164     //       sense to specialize attributes for call sites instead of
1165     //       redirecting requests to the callee.
1166     llvm_unreachable("Abstract attributes for returned values are not "
1167                      "supported for call sites yet!");
1168   }
1169 
1170   /// See AbstractAttribute::updateImpl(...).
1171   ChangeStatus updateImpl(Attributor &A) override {
1172     return indicatePessimisticFixpoint();
1173   }
1174 
1175   /// See AbstractAttribute::trackStatistics()
1176   void trackStatistics() const override {}
1177 };
1178 
1179 /// ------------------------ NoSync Function Attribute -------------------------
1180 
1181 struct AANoSyncImpl : AANoSync {
1182   AANoSyncImpl(const IRPosition &IRP) : AANoSync(IRP) {}
1183 
1184   const std::string getAsStr() const override {
1185     return getAssumed() ? "nosync" : "may-sync";
1186   }
1187 
1188   /// See AbstractAttribute::updateImpl(...).
1189   ChangeStatus updateImpl(Attributor &A) override;
1190 
1191   /// Helper function used to determine whether an instruction is non-relaxed
1192   /// atomic. In other words, if an atomic instruction does not have unordered
1193   /// or monotonic ordering
1194   static bool isNonRelaxedAtomic(Instruction *I);
1195 
1196   /// Helper function used to determine whether an instruction is volatile.
1197   static bool isVolatile(Instruction *I);
1198 
1199   /// Helper function uset to check if intrinsic is volatile (memcpy, memmove,
1200   /// memset).
1201   static bool isNoSyncIntrinsic(Instruction *I);
1202 };
1203 
1204 bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) {
1205   if (!I->isAtomic())
1206     return false;
1207 
1208   AtomicOrdering Ordering;
1209   switch (I->getOpcode()) {
1210   case Instruction::AtomicRMW:
1211     Ordering = cast<AtomicRMWInst>(I)->getOrdering();
1212     break;
1213   case Instruction::Store:
1214     Ordering = cast<StoreInst>(I)->getOrdering();
1215     break;
1216   case Instruction::Load:
1217     Ordering = cast<LoadInst>(I)->getOrdering();
1218     break;
1219   case Instruction::Fence: {
1220     auto *FI = cast<FenceInst>(I);
1221     if (FI->getSyncScopeID() == SyncScope::SingleThread)
1222       return false;
1223     Ordering = FI->getOrdering();
1224     break;
1225   }
1226   case Instruction::AtomicCmpXchg: {
1227     AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering();
1228     AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering();
1229     // Only if both are relaxed, than it can be treated as relaxed.
1230     // Otherwise it is non-relaxed.
1231     if (Success != AtomicOrdering::Unordered &&
1232         Success != AtomicOrdering::Monotonic)
1233       return true;
1234     if (Failure != AtomicOrdering::Unordered &&
1235         Failure != AtomicOrdering::Monotonic)
1236       return true;
1237     return false;
1238   }
1239   default:
1240     llvm_unreachable(
1241         "New atomic operations need to be known in the attributor.");
1242   }
1243 
1244   // Relaxed.
1245   if (Ordering == AtomicOrdering::Unordered ||
1246       Ordering == AtomicOrdering::Monotonic)
1247     return false;
1248   return true;
1249 }
1250 
1251 /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics.
1252 /// FIXME: We should ipmrove the handling of intrinsics.
1253 bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) {
1254   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1255     switch (II->getIntrinsicID()) {
1256     /// Element wise atomic memory intrinsics are can only be unordered,
1257     /// therefore nosync.
1258     case Intrinsic::memset_element_unordered_atomic:
1259     case Intrinsic::memmove_element_unordered_atomic:
1260     case Intrinsic::memcpy_element_unordered_atomic:
1261       return true;
1262     case Intrinsic::memset:
1263     case Intrinsic::memmove:
1264     case Intrinsic::memcpy:
1265       if (!cast<MemIntrinsic>(II)->isVolatile())
1266         return true;
1267       return false;
1268     default:
1269       return false;
1270     }
1271   }
1272   return false;
1273 }
1274 
1275 bool AANoSyncImpl::isVolatile(Instruction *I) {
1276   assert(!ImmutableCallSite(I) && !isa<CallBase>(I) &&
1277          "Calls should not be checked here");
1278 
1279   switch (I->getOpcode()) {
1280   case Instruction::AtomicRMW:
1281     return cast<AtomicRMWInst>(I)->isVolatile();
1282   case Instruction::Store:
1283     return cast<StoreInst>(I)->isVolatile();
1284   case Instruction::Load:
1285     return cast<LoadInst>(I)->isVolatile();
1286   case Instruction::AtomicCmpXchg:
1287     return cast<AtomicCmpXchgInst>(I)->isVolatile();
1288   default:
1289     return false;
1290   }
1291 }
1292 
1293 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
1294 
1295   auto CheckRWInstForNoSync = [&](Instruction &I) {
1296     /// We are looking for volatile instructions or Non-Relaxed atomics.
1297     /// FIXME: We should improve the handling of intrinsics.
1298 
1299     if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I))
1300       return true;
1301 
1302     if (ImmutableCallSite ICS = ImmutableCallSite(&I)) {
1303       if (ICS.hasFnAttr(Attribute::NoSync))
1304         return true;
1305 
1306       const auto &NoSyncAA =
1307           A.getAAFor<AANoSync>(*this, IRPosition::callsite_function(ICS));
1308       if (NoSyncAA.isAssumedNoSync())
1309         return true;
1310       return false;
1311     }
1312 
1313     if (!isVolatile(&I) && !isNonRelaxedAtomic(&I))
1314       return true;
1315 
1316     return false;
1317   };
1318 
1319   auto CheckForNoSync = [&](Instruction &I) {
1320     // At this point we handled all read/write effects and they are all
1321     // nosync, so they can be skipped.
1322     if (I.mayReadOrWriteMemory())
1323       return true;
1324 
1325     // non-convergent and readnone imply nosync.
1326     return !ImmutableCallSite(&I).isConvergent();
1327   };
1328 
1329   if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) ||
1330       !A.checkForAllCallLikeInstructions(CheckForNoSync, *this))
1331     return indicatePessimisticFixpoint();
1332 
1333   return ChangeStatus::UNCHANGED;
1334 }
1335 
1336 struct AANoSyncFunction final : public AANoSyncImpl {
1337   AANoSyncFunction(const IRPosition &IRP) : AANoSyncImpl(IRP) {}
1338 
1339   /// See AbstractAttribute::trackStatistics()
1340   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
1341 };
1342 
1343 /// NoSync attribute deduction for a call sites.
1344 struct AANoSyncCallSite final : AANoSyncImpl {
1345   AANoSyncCallSite(const IRPosition &IRP) : AANoSyncImpl(IRP) {}
1346 
1347   /// See AbstractAttribute::initialize(...).
1348   void initialize(Attributor &A) override {
1349     AANoSyncImpl::initialize(A);
1350     Function *F = getAssociatedFunction();
1351     if (!F)
1352       indicatePessimisticFixpoint();
1353   }
1354 
1355   /// See AbstractAttribute::updateImpl(...).
1356   ChangeStatus updateImpl(Attributor &A) override {
1357     // TODO: Once we have call site specific value information we can provide
1358     //       call site specific liveness information and then it makes
1359     //       sense to specialize attributes for call sites arguments instead of
1360     //       redirecting requests to the callee argument.
1361     Function *F = getAssociatedFunction();
1362     const IRPosition &FnPos = IRPosition::function(*F);
1363     auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos);
1364     return clampStateAndIndicateChange(
1365         getState(), static_cast<const AANoSync::StateType &>(FnAA.getState()));
1366   }
1367 
1368   /// See AbstractAttribute::trackStatistics()
1369   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); }
1370 };
1371 
1372 /// ------------------------ No-Free Attributes ----------------------------
1373 
1374 struct AANoFreeImpl : public AANoFree {
1375   AANoFreeImpl(const IRPosition &IRP) : AANoFree(IRP) {}
1376 
1377   /// See AbstractAttribute::updateImpl(...).
1378   ChangeStatus updateImpl(Attributor &A) override {
1379     auto CheckForNoFree = [&](Instruction &I) {
1380       ImmutableCallSite ICS(&I);
1381       if (ICS.hasFnAttr(Attribute::NoFree))
1382         return true;
1383 
1384       const auto &NoFreeAA =
1385           A.getAAFor<AANoFree>(*this, IRPosition::callsite_function(ICS));
1386       return NoFreeAA.isAssumedNoFree();
1387     };
1388 
1389     if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this))
1390       return indicatePessimisticFixpoint();
1391     return ChangeStatus::UNCHANGED;
1392   }
1393 
1394   /// See AbstractAttribute::getAsStr().
1395   const std::string getAsStr() const override {
1396     return getAssumed() ? "nofree" : "may-free";
1397   }
1398 };
1399 
1400 struct AANoFreeFunction final : public AANoFreeImpl {
1401   AANoFreeFunction(const IRPosition &IRP) : AANoFreeImpl(IRP) {}
1402 
1403   /// See AbstractAttribute::trackStatistics()
1404   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
1405 };
1406 
1407 /// NoFree attribute deduction for a call sites.
1408 struct AANoFreeCallSite final : AANoFreeImpl {
1409   AANoFreeCallSite(const IRPosition &IRP) : AANoFreeImpl(IRP) {}
1410 
1411   /// See AbstractAttribute::initialize(...).
1412   void initialize(Attributor &A) override {
1413     AANoFreeImpl::initialize(A);
1414     Function *F = getAssociatedFunction();
1415     if (!F)
1416       indicatePessimisticFixpoint();
1417   }
1418 
1419   /// See AbstractAttribute::updateImpl(...).
1420   ChangeStatus updateImpl(Attributor &A) override {
1421     // TODO: Once we have call site specific value information we can provide
1422     //       call site specific liveness information and then it makes
1423     //       sense to specialize attributes for call sites arguments instead of
1424     //       redirecting requests to the callee argument.
1425     Function *F = getAssociatedFunction();
1426     const IRPosition &FnPos = IRPosition::function(*F);
1427     auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos);
1428     return clampStateAndIndicateChange(
1429         getState(), static_cast<const AANoFree::StateType &>(FnAA.getState()));
1430   }
1431 
1432   /// See AbstractAttribute::trackStatistics()
1433   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); }
1434 };
1435 
1436 /// NoFree attribute for floating values.
1437 struct AANoFreeFloating : AANoFreeImpl {
1438   AANoFreeFloating(const IRPosition &IRP) : AANoFreeImpl(IRP) {}
1439 
1440   /// See AbstractAttribute::trackStatistics()
1441   void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)}
1442 
1443   /// See Abstract Attribute::updateImpl(...).
1444   ChangeStatus updateImpl(Attributor &A) override {
1445     const IRPosition &IRP = getIRPosition();
1446 
1447     const auto &NoFreeAA =
1448         A.getAAFor<AANoFree>(*this, IRPosition::function_scope(IRP));
1449     if (NoFreeAA.isAssumedNoFree())
1450       return ChangeStatus::UNCHANGED;
1451 
1452     Value &AssociatedValue = getIRPosition().getAssociatedValue();
1453     auto Pred = [&](const Use &U, bool &Follow) -> bool {
1454       Instruction *UserI = cast<Instruction>(U.getUser());
1455       if (auto *CB = dyn_cast<CallBase>(UserI)) {
1456         if (CB->isBundleOperand(&U))
1457           return false;
1458         if (!CB->isArgOperand(&U))
1459           return true;
1460         unsigned ArgNo = CB->getArgOperandNo(&U);
1461 
1462         const auto &NoFreeArg = A.getAAFor<AANoFree>(
1463             *this, IRPosition::callsite_argument(*CB, ArgNo));
1464         return NoFreeArg.isAssumedNoFree();
1465       }
1466 
1467       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
1468           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
1469         Follow = true;
1470         return true;
1471       }
1472       if (isa<ReturnInst>(UserI))
1473         return true;
1474 
1475       // Unknown user.
1476       return false;
1477     };
1478     if (!A.checkForAllUses(Pred, *this, AssociatedValue))
1479       return indicatePessimisticFixpoint();
1480 
1481     return ChangeStatus::UNCHANGED;
1482   }
1483 };
1484 
1485 /// NoFree attribute for a call site argument.
1486 struct AANoFreeArgument final : AANoFreeFloating {
1487   AANoFreeArgument(const IRPosition &IRP) : AANoFreeFloating(IRP) {}
1488 
1489   /// See AbstractAttribute::trackStatistics()
1490   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) }
1491 };
1492 
1493 /// NoFree attribute for call site arguments.
1494 struct AANoFreeCallSiteArgument final : AANoFreeFloating {
1495   AANoFreeCallSiteArgument(const IRPosition &IRP) : AANoFreeFloating(IRP) {}
1496 
1497   /// See AbstractAttribute::updateImpl(...).
1498   ChangeStatus updateImpl(Attributor &A) override {
1499     // TODO: Once we have call site specific value information we can provide
1500     //       call site specific liveness information and then it makes
1501     //       sense to specialize attributes for call sites arguments instead of
1502     //       redirecting requests to the callee argument.
1503     Argument *Arg = getAssociatedArgument();
1504     if (!Arg)
1505       return indicatePessimisticFixpoint();
1506     const IRPosition &ArgPos = IRPosition::argument(*Arg);
1507     auto &ArgAA = A.getAAFor<AANoFree>(*this, ArgPos);
1508     return clampStateAndIndicateChange(
1509         getState(), static_cast<const AANoFree::StateType &>(ArgAA.getState()));
1510   }
1511 
1512   /// See AbstractAttribute::trackStatistics()
1513   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nofree)};
1514 };
1515 
1516 /// NoFree attribute for function return value.
1517 struct AANoFreeReturned final : AANoFreeFloating {
1518   AANoFreeReturned(const IRPosition &IRP) : AANoFreeFloating(IRP) {
1519     llvm_unreachable("NoFree is not applicable to function returns!");
1520   }
1521 
1522   /// See AbstractAttribute::initialize(...).
1523   void initialize(Attributor &A) override {
1524     llvm_unreachable("NoFree is not applicable to function returns!");
1525   }
1526 
1527   /// See AbstractAttribute::updateImpl(...).
1528   ChangeStatus updateImpl(Attributor &A) override {
1529     llvm_unreachable("NoFree is not applicable to function returns!");
1530   }
1531 
1532   /// See AbstractAttribute::trackStatistics()
1533   void trackStatistics() const override {}
1534 };
1535 
1536 /// NoFree attribute deduction for a call site return value.
1537 struct AANoFreeCallSiteReturned final : AANoFreeFloating {
1538   AANoFreeCallSiteReturned(const IRPosition &IRP) : AANoFreeFloating(IRP) {}
1539 
1540   ChangeStatus manifest(Attributor &A) override {
1541     return ChangeStatus::UNCHANGED;
1542   }
1543   /// See AbstractAttribute::trackStatistics()
1544   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) }
1545 };
1546 
1547 /// ------------------------ NonNull Argument Attribute ------------------------
1548 static int64_t getKnownNonNullAndDerefBytesForUse(
1549     Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue,
1550     const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) {
1551   TrackUse = false;
1552 
1553   const Value *UseV = U->get();
1554   if (!UseV->getType()->isPointerTy())
1555     return 0;
1556 
1557   Type *PtrTy = UseV->getType();
1558   const Function *F = I->getFunction();
1559   bool NullPointerIsDefined =
1560       F ? llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()) : true;
1561   const DataLayout &DL = A.getInfoCache().getDL();
1562   if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
1563     if (ICS.isBundleOperand(U))
1564       return 0;
1565 
1566     if (ICS.isCallee(U)) {
1567       IsNonNull |= !NullPointerIsDefined;
1568       return 0;
1569     }
1570 
1571     unsigned ArgNo = ICS.getArgumentNo(U);
1572     IRPosition IRP = IRPosition::callsite_argument(ICS, ArgNo);
1573     // As long as we only use known information there is no need to track
1574     // dependences here.
1575     auto &DerefAA = A.getAAFor<AADereferenceable>(QueryingAA, IRP,
1576                                                   /* TrackDependence */ false);
1577     IsNonNull |= DerefAA.isKnownNonNull();
1578     return DerefAA.getKnownDereferenceableBytes();
1579   }
1580 
1581   // We need to follow common pointer manipulation uses to the accesses they
1582   // feed into. We can try to be smart to avoid looking through things we do not
1583   // like for now, e.g., non-inbounds GEPs.
1584   if (isa<CastInst>(I)) {
1585     TrackUse = true;
1586     return 0;
1587   }
1588   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
1589     if (GEP->hasAllConstantIndices()) {
1590       TrackUse = true;
1591       return 0;
1592     }
1593 
1594   int64_t Offset;
1595   if (const Value *Base = getBasePointerOfAccessPointerOperand(I, Offset, DL)) {
1596     if (Base == &AssociatedValue &&
1597         getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
1598       int64_t DerefBytes =
1599           (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType()) + Offset;
1600 
1601       IsNonNull |= !NullPointerIsDefined;
1602       return std::max(int64_t(0), DerefBytes);
1603     }
1604   }
1605 
1606   /// Corner case when an offset is 0.
1607   if (const Value *Base = getBasePointerOfAccessPointerOperand(
1608           I, Offset, DL, /*AllowNonInbounds*/ true)) {
1609     if (Offset == 0 && Base == &AssociatedValue &&
1610         getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
1611       int64_t DerefBytes =
1612           (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType());
1613       IsNonNull |= !NullPointerIsDefined;
1614       return std::max(int64_t(0), DerefBytes);
1615     }
1616   }
1617 
1618   return 0;
1619 }
1620 
1621 struct AANonNullImpl : AANonNull {
1622   AANonNullImpl(const IRPosition &IRP)
1623       : AANonNull(IRP),
1624         NullIsDefined(NullPointerIsDefined(
1625             getAnchorScope(),
1626             getAssociatedValue().getType()->getPointerAddressSpace())) {}
1627 
1628   /// See AbstractAttribute::initialize(...).
1629   void initialize(Attributor &A) override {
1630     if (!NullIsDefined &&
1631         hasAttr({Attribute::NonNull, Attribute::Dereferenceable},
1632                 /* IgnoreSubsumingPositions */ false, &A))
1633       indicateOptimisticFixpoint();
1634     else if (isa<ConstantPointerNull>(getAssociatedValue()))
1635       indicatePessimisticFixpoint();
1636     else
1637       AANonNull::initialize(A);
1638   }
1639 
1640   /// See AAFromMustBeExecutedContext
1641   bool followUse(Attributor &A, const Use *U, const Instruction *I,
1642                  AANonNull::StateType &State) {
1643     bool IsNonNull = false;
1644     bool TrackUse = false;
1645     getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I,
1646                                        IsNonNull, TrackUse);
1647     State.setKnown(IsNonNull);
1648     return TrackUse;
1649   }
1650 
1651   /// See AbstractAttribute::getAsStr().
1652   const std::string getAsStr() const override {
1653     return getAssumed() ? "nonnull" : "may-null";
1654   }
1655 
1656   /// Flag to determine if the underlying value can be null and still allow
1657   /// valid accesses.
1658   const bool NullIsDefined;
1659 };
1660 
1661 /// NonNull attribute for a floating value.
1662 struct AANonNullFloating
1663     : AAFromMustBeExecutedContext<AANonNull, AANonNullImpl> {
1664   using Base = AAFromMustBeExecutedContext<AANonNull, AANonNullImpl>;
1665   AANonNullFloating(const IRPosition &IRP) : Base(IRP) {}
1666 
1667   /// See AbstractAttribute::updateImpl(...).
1668   ChangeStatus updateImpl(Attributor &A) override {
1669     ChangeStatus Change = Base::updateImpl(A);
1670     if (isKnownNonNull())
1671       return Change;
1672 
1673     if (!NullIsDefined) {
1674       const auto &DerefAA =
1675           A.getAAFor<AADereferenceable>(*this, getIRPosition());
1676       if (DerefAA.getAssumedDereferenceableBytes())
1677         return Change;
1678     }
1679 
1680     const DataLayout &DL = A.getDataLayout();
1681 
1682     DominatorTree *DT = nullptr;
1683     AssumptionCache *AC = nullptr;
1684     InformationCache &InfoCache = A.getInfoCache();
1685     if (const Function *Fn = getAnchorScope()) {
1686       DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Fn);
1687       AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*Fn);
1688     }
1689 
1690     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
1691                             AANonNull::StateType &T, bool Stripped) -> bool {
1692       const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V));
1693       if (!Stripped && this == &AA) {
1694         if (!isKnownNonZero(&V, DL, 0, AC, CtxI, DT))
1695           T.indicatePessimisticFixpoint();
1696       } else {
1697         // Use abstract attribute information.
1698         const AANonNull::StateType &NS =
1699             static_cast<const AANonNull::StateType &>(AA.getState());
1700         T ^= NS;
1701       }
1702       return T.isValidState();
1703     };
1704 
1705     StateType T;
1706     if (!genericValueTraversal<AANonNull, StateType>(
1707             A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
1708       return indicatePessimisticFixpoint();
1709 
1710     return clampStateAndIndicateChange(getState(), T);
1711   }
1712 
1713   /// See AbstractAttribute::trackStatistics()
1714   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
1715 };
1716 
1717 /// NonNull attribute for function return value.
1718 struct AANonNullReturned final
1719     : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl> {
1720   AANonNullReturned(const IRPosition &IRP)
1721       : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl>(IRP) {}
1722 
1723   /// See AbstractAttribute::trackStatistics()
1724   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
1725 };
1726 
1727 /// NonNull attribute for function argument.
1728 struct AANonNullArgument final
1729     : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AANonNull,
1730                                                               AANonNullImpl> {
1731   AANonNullArgument(const IRPosition &IRP)
1732       : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AANonNull,
1733                                                                 AANonNullImpl>(
1734             IRP) {}
1735 
1736   /// See AbstractAttribute::trackStatistics()
1737   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
1738 };
1739 
1740 struct AANonNullCallSiteArgument final : AANonNullFloating {
1741   AANonNullCallSiteArgument(const IRPosition &IRP) : AANonNullFloating(IRP) {}
1742 
1743   /// See AbstractAttribute::trackStatistics()
1744   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) }
1745 };
1746 
1747 /// NonNull attribute for a call site return position.
1748 struct AANonNullCallSiteReturned final
1749     : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AANonNull,
1750                                                              AANonNullImpl> {
1751   AANonNullCallSiteReturned(const IRPosition &IRP)
1752       : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AANonNull,
1753                                                                AANonNullImpl>(
1754             IRP) {}
1755 
1756   /// See AbstractAttribute::trackStatistics()
1757   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) }
1758 };
1759 
1760 /// ------------------------ No-Recurse Attributes ----------------------------
1761 
1762 struct AANoRecurseImpl : public AANoRecurse {
1763   AANoRecurseImpl(const IRPosition &IRP) : AANoRecurse(IRP) {}
1764 
1765   /// See AbstractAttribute::getAsStr()
1766   const std::string getAsStr() const override {
1767     return getAssumed() ? "norecurse" : "may-recurse";
1768   }
1769 };
1770 
1771 struct AANoRecurseFunction final : AANoRecurseImpl {
1772   AANoRecurseFunction(const IRPosition &IRP) : AANoRecurseImpl(IRP) {}
1773 
1774   /// See AbstractAttribute::initialize(...).
1775   void initialize(Attributor &A) override {
1776     AANoRecurseImpl::initialize(A);
1777     if (const Function *F = getAnchorScope())
1778       if (A.getInfoCache().getSccSize(*F) != 1)
1779         indicatePessimisticFixpoint();
1780   }
1781 
1782   /// See AbstractAttribute::updateImpl(...).
1783   ChangeStatus updateImpl(Attributor &A) override {
1784 
1785     // If all live call sites are known to be no-recurse, we are as well.
1786     auto CallSitePred = [&](AbstractCallSite ACS) {
1787       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
1788           *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
1789           /* TrackDependence */ false, DepClassTy::OPTIONAL);
1790       return NoRecurseAA.isKnownNoRecurse();
1791     };
1792     bool AllCallSitesKnown;
1793     if (A.checkForAllCallSites(CallSitePred, *this, true, AllCallSitesKnown)) {
1794       // If we know all call sites and all are known no-recurse, we are done.
1795       // If all known call sites, which might not be all that exist, are known
1796       // to be no-recurse, we are not done but we can continue to assume
1797       // no-recurse. If one of the call sites we have not visited will become
1798       // live, another update is triggered.
1799       if (AllCallSitesKnown)
1800         indicateOptimisticFixpoint();
1801       return ChangeStatus::UNCHANGED;
1802     }
1803 
1804     // If the above check does not hold anymore we look at the calls.
1805     auto CheckForNoRecurse = [&](Instruction &I) {
1806       ImmutableCallSite ICS(&I);
1807       if (ICS.hasFnAttr(Attribute::NoRecurse))
1808         return true;
1809 
1810       const auto &NoRecurseAA =
1811           A.getAAFor<AANoRecurse>(*this, IRPosition::callsite_function(ICS));
1812       if (!NoRecurseAA.isAssumedNoRecurse())
1813         return false;
1814 
1815       // Recursion to the same function
1816       if (ICS.getCalledFunction() == getAnchorScope())
1817         return false;
1818 
1819       return true;
1820     };
1821 
1822     if (!A.checkForAllCallLikeInstructions(CheckForNoRecurse, *this))
1823       return indicatePessimisticFixpoint();
1824     return ChangeStatus::UNCHANGED;
1825   }
1826 
1827   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
1828 };
1829 
1830 /// NoRecurse attribute deduction for a call sites.
1831 struct AANoRecurseCallSite final : AANoRecurseImpl {
1832   AANoRecurseCallSite(const IRPosition &IRP) : AANoRecurseImpl(IRP) {}
1833 
1834   /// See AbstractAttribute::initialize(...).
1835   void initialize(Attributor &A) override {
1836     AANoRecurseImpl::initialize(A);
1837     Function *F = getAssociatedFunction();
1838     if (!F)
1839       indicatePessimisticFixpoint();
1840   }
1841 
1842   /// See AbstractAttribute::updateImpl(...).
1843   ChangeStatus updateImpl(Attributor &A) override {
1844     // TODO: Once we have call site specific value information we can provide
1845     //       call site specific liveness information and then it makes
1846     //       sense to specialize attributes for call sites arguments instead of
1847     //       redirecting requests to the callee argument.
1848     Function *F = getAssociatedFunction();
1849     const IRPosition &FnPos = IRPosition::function(*F);
1850     auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos);
1851     return clampStateAndIndicateChange(
1852         getState(),
1853         static_cast<const AANoRecurse::StateType &>(FnAA.getState()));
1854   }
1855 
1856   /// See AbstractAttribute::trackStatistics()
1857   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); }
1858 };
1859 
1860 /// -------------------- Undefined-Behavior Attributes ------------------------
1861 
1862 struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
1863   AAUndefinedBehaviorImpl(const IRPosition &IRP) : AAUndefinedBehavior(IRP) {}
1864 
1865   /// See AbstractAttribute::updateImpl(...).
1866   // through a pointer (i.e. also branches etc.)
1867   ChangeStatus updateImpl(Attributor &A) override {
1868     const size_t UBPrevSize = KnownUBInsts.size();
1869     const size_t NoUBPrevSize = AssumedNoUBInsts.size();
1870 
1871     auto InspectMemAccessInstForUB = [&](Instruction &I) {
1872       // Skip instructions that are already saved.
1873       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
1874         return true;
1875 
1876       // If we reach here, we know we have an instruction
1877       // that accesses memory through a pointer operand,
1878       // for which getPointerOperand() should give it to us.
1879       const Value *PtrOp = getPointerOperand(&I, /* AllowVolatile */ true);
1880       assert(PtrOp &&
1881              "Expected pointer operand of memory accessing instruction");
1882 
1883       // Either we stopped and the appropriate action was taken,
1884       // or we got back a simplified value to continue.
1885       Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I);
1886       if (!SimplifiedPtrOp.hasValue())
1887         return true;
1888       const Value *PtrOpVal = SimplifiedPtrOp.getValue();
1889 
1890       // A memory access through a pointer is considered UB
1891       // only if the pointer has constant null value.
1892       // TODO: Expand it to not only check constant values.
1893       if (!isa<ConstantPointerNull>(PtrOpVal)) {
1894         AssumedNoUBInsts.insert(&I);
1895         return true;
1896       }
1897       const Type *PtrTy = PtrOpVal->getType();
1898 
1899       // Because we only consider instructions inside functions,
1900       // assume that a parent function exists.
1901       const Function *F = I.getFunction();
1902 
1903       // A memory access using constant null pointer is only considered UB
1904       // if null pointer is _not_ defined for the target platform.
1905       if (llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()))
1906         AssumedNoUBInsts.insert(&I);
1907       else
1908         KnownUBInsts.insert(&I);
1909       return true;
1910     };
1911 
1912     auto InspectBrInstForUB = [&](Instruction &I) {
1913       // A conditional branch instruction is considered UB if it has `undef`
1914       // condition.
1915 
1916       // Skip instructions that are already saved.
1917       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
1918         return true;
1919 
1920       // We know we have a branch instruction.
1921       auto BrInst = cast<BranchInst>(&I);
1922 
1923       // Unconditional branches are never considered UB.
1924       if (BrInst->isUnconditional())
1925         return true;
1926 
1927       // Either we stopped and the appropriate action was taken,
1928       // or we got back a simplified value to continue.
1929       Optional<Value *> SimplifiedCond =
1930           stopOnUndefOrAssumed(A, BrInst->getCondition(), BrInst);
1931       if (!SimplifiedCond.hasValue())
1932         return true;
1933       AssumedNoUBInsts.insert(&I);
1934       return true;
1935     };
1936 
1937     A.checkForAllInstructions(InspectMemAccessInstForUB, *this,
1938                               {Instruction::Load, Instruction::Store,
1939                                Instruction::AtomicCmpXchg,
1940                                Instruction::AtomicRMW},
1941                               /* CheckBBLivenessOnly */ true);
1942     A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::Br},
1943                               /* CheckBBLivenessOnly */ true);
1944     if (NoUBPrevSize != AssumedNoUBInsts.size() ||
1945         UBPrevSize != KnownUBInsts.size())
1946       return ChangeStatus::CHANGED;
1947     return ChangeStatus::UNCHANGED;
1948   }
1949 
1950   bool isKnownToCauseUB(Instruction *I) const override {
1951     return KnownUBInsts.count(I);
1952   }
1953 
1954   bool isAssumedToCauseUB(Instruction *I) const override {
1955     // In simple words, if an instruction is not in the assumed to _not_
1956     // cause UB, then it is assumed UB (that includes those
1957     // in the KnownUBInsts set). The rest is boilerplate
1958     // is to ensure that it is one of the instructions we test
1959     // for UB.
1960 
1961     switch (I->getOpcode()) {
1962     case Instruction::Load:
1963     case Instruction::Store:
1964     case Instruction::AtomicCmpXchg:
1965     case Instruction::AtomicRMW:
1966       return !AssumedNoUBInsts.count(I);
1967     case Instruction::Br: {
1968       auto BrInst = cast<BranchInst>(I);
1969       if (BrInst->isUnconditional())
1970         return false;
1971       return !AssumedNoUBInsts.count(I);
1972     } break;
1973     default:
1974       return false;
1975     }
1976     return false;
1977   }
1978 
1979   ChangeStatus manifest(Attributor &A) override {
1980     if (KnownUBInsts.empty())
1981       return ChangeStatus::UNCHANGED;
1982     for (Instruction *I : KnownUBInsts)
1983       A.changeToUnreachableAfterManifest(I);
1984     return ChangeStatus::CHANGED;
1985   }
1986 
1987   /// See AbstractAttribute::getAsStr()
1988   const std::string getAsStr() const override {
1989     return getAssumed() ? "undefined-behavior" : "no-ub";
1990   }
1991 
1992   /// Note: The correctness of this analysis depends on the fact that the
1993   /// following 2 sets will stop changing after some point.
1994   /// "Change" here means that their size changes.
1995   /// The size of each set is monotonically increasing
1996   /// (we only add items to them) and it is upper bounded by the number of
1997   /// instructions in the processed function (we can never save more
1998   /// elements in either set than this number). Hence, at some point,
1999   /// they will stop increasing.
2000   /// Consequently, at some point, both sets will have stopped
2001   /// changing, effectively making the analysis reach a fixpoint.
2002 
2003   /// Note: These 2 sets are disjoint and an instruction can be considered
2004   /// one of 3 things:
2005   /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in
2006   ///    the KnownUBInsts set.
2007   /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior
2008   ///    has a reason to assume it).
2009   /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior
2010   ///    could not find a reason to assume or prove that it can cause UB,
2011   ///    hence it assumes it doesn't. We have a set for these instructions
2012   ///    so that we don't reprocess them in every update.
2013   ///    Note however that instructions in this set may cause UB.
2014 
2015 protected:
2016   /// A set of all live instructions _known_ to cause UB.
2017   SmallPtrSet<Instruction *, 8> KnownUBInsts;
2018 
2019 private:
2020   /// A set of all the (live) instructions that are assumed to _not_ cause UB.
2021   SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
2022 
2023   // Should be called on updates in which if we're processing an instruction
2024   // \p I that depends on a value \p V, one of the following has to happen:
2025   // - If the value is assumed, then stop.
2026   // - If the value is known but undef, then consider it UB.
2027   // - Otherwise, do specific processing with the simplified value.
2028   // We return None in the first 2 cases to signify that an appropriate
2029   // action was taken and the caller should stop.
2030   // Otherwise, we return the simplified value that the caller should
2031   // use for specific processing.
2032   Optional<Value *> stopOnUndefOrAssumed(Attributor &A, const Value *V,
2033                                          Instruction *I) {
2034     const auto &ValueSimplifyAA =
2035         A.getAAFor<AAValueSimplify>(*this, IRPosition::value(*V));
2036     Optional<Value *> SimplifiedV =
2037         ValueSimplifyAA.getAssumedSimplifiedValue(A);
2038     if (!ValueSimplifyAA.isKnown()) {
2039       // Don't depend on assumed values.
2040       return llvm::None;
2041     }
2042     if (!SimplifiedV.hasValue()) {
2043       // If it is known (which we tested above) but it doesn't have a value,
2044       // then we can assume `undef` and hence the instruction is UB.
2045       KnownUBInsts.insert(I);
2046       return llvm::None;
2047     }
2048     Value *Val = SimplifiedV.getValue();
2049     if (isa<UndefValue>(Val)) {
2050       KnownUBInsts.insert(I);
2051       return llvm::None;
2052     }
2053     return Val;
2054   }
2055 };
2056 
2057 struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
2058   AAUndefinedBehaviorFunction(const IRPosition &IRP)
2059       : AAUndefinedBehaviorImpl(IRP) {}
2060 
2061   /// See AbstractAttribute::trackStatistics()
2062   void trackStatistics() const override {
2063     STATS_DECL(UndefinedBehaviorInstruction, Instruction,
2064                "Number of instructions known to have UB");
2065     BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) +=
2066         KnownUBInsts.size();
2067   }
2068 };
2069 
2070 /// ------------------------ Will-Return Attributes ----------------------------
2071 
2072 // Helper function that checks whether a function has any cycle which we don't
2073 // know if it is bounded or not.
2074 // Loops with maximum trip count are considered bounded, any other cycle not.
2075 static bool mayContainUnboundedCycle(Function &F, Attributor &A) {
2076   ScalarEvolution *SE =
2077       A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F);
2078   LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F);
2079   // If either SCEV or LoopInfo is not available for the function then we assume
2080   // any cycle to be unbounded cycle.
2081   // We use scc_iterator which uses Tarjan algorithm to find all the maximal
2082   // SCCs.To detect if there's a cycle, we only need to find the maximal ones.
2083   if (!SE || !LI) {
2084     for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI)
2085       if (SCCI.hasCycle())
2086         return true;
2087     return false;
2088   }
2089 
2090   // If there's irreducible control, the function may contain non-loop cycles.
2091   if (mayContainIrreducibleControl(F, LI))
2092     return true;
2093 
2094   // Any loop that does not have a max trip count is considered unbounded cycle.
2095   for (auto *L : LI->getLoopsInPreorder()) {
2096     if (!SE->getSmallConstantMaxTripCount(L))
2097       return true;
2098   }
2099   return false;
2100 }
2101 
2102 struct AAWillReturnImpl : public AAWillReturn {
2103   AAWillReturnImpl(const IRPosition &IRP) : AAWillReturn(IRP) {}
2104 
2105   /// See AbstractAttribute::initialize(...).
2106   void initialize(Attributor &A) override {
2107     AAWillReturn::initialize(A);
2108 
2109     Function *F = getAnchorScope();
2110     if (!F || !A.isFunctionIPOAmendable(*F) || mayContainUnboundedCycle(*F, A))
2111       indicatePessimisticFixpoint();
2112   }
2113 
2114   /// See AbstractAttribute::updateImpl(...).
2115   ChangeStatus updateImpl(Attributor &A) override {
2116     auto CheckForWillReturn = [&](Instruction &I) {
2117       IRPosition IPos = IRPosition::callsite_function(ImmutableCallSite(&I));
2118       const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos);
2119       if (WillReturnAA.isKnownWillReturn())
2120         return true;
2121       if (!WillReturnAA.isAssumedWillReturn())
2122         return false;
2123       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos);
2124       return NoRecurseAA.isAssumedNoRecurse();
2125     };
2126 
2127     if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this))
2128       return indicatePessimisticFixpoint();
2129 
2130     return ChangeStatus::UNCHANGED;
2131   }
2132 
2133   /// See AbstractAttribute::getAsStr()
2134   const std::string getAsStr() const override {
2135     return getAssumed() ? "willreturn" : "may-noreturn";
2136   }
2137 };
2138 
2139 struct AAWillReturnFunction final : AAWillReturnImpl {
2140   AAWillReturnFunction(const IRPosition &IRP) : AAWillReturnImpl(IRP) {}
2141 
2142   /// See AbstractAttribute::trackStatistics()
2143   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
2144 };
2145 
2146 /// WillReturn attribute deduction for a call sites.
2147 struct AAWillReturnCallSite final : AAWillReturnImpl {
2148   AAWillReturnCallSite(const IRPosition &IRP) : AAWillReturnImpl(IRP) {}
2149 
2150   /// See AbstractAttribute::initialize(...).
2151   void initialize(Attributor &A) override {
2152     AAWillReturnImpl::initialize(A);
2153     Function *F = getAssociatedFunction();
2154     if (!F)
2155       indicatePessimisticFixpoint();
2156   }
2157 
2158   /// See AbstractAttribute::updateImpl(...).
2159   ChangeStatus updateImpl(Attributor &A) override {
2160     // TODO: Once we have call site specific value information we can provide
2161     //       call site specific liveness information and then it makes
2162     //       sense to specialize attributes for call sites arguments instead of
2163     //       redirecting requests to the callee argument.
2164     Function *F = getAssociatedFunction();
2165     const IRPosition &FnPos = IRPosition::function(*F);
2166     auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos);
2167     return clampStateAndIndicateChange(
2168         getState(),
2169         static_cast<const AAWillReturn::StateType &>(FnAA.getState()));
2170   }
2171 
2172   /// See AbstractAttribute::trackStatistics()
2173   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); }
2174 };
2175 
2176 /// -------------------AAReachability Attribute--------------------------
2177 
2178 struct AAReachabilityImpl : AAReachability {
2179   AAReachabilityImpl(const IRPosition &IRP) : AAReachability(IRP) {}
2180 
2181   const std::string getAsStr() const override {
2182     // TODO: Return the number of reachable queries.
2183     return "reachable";
2184   }
2185 
2186   /// See AbstractAttribute::initialize(...).
2187   void initialize(Attributor &A) override { indicatePessimisticFixpoint(); }
2188 
2189   /// See AbstractAttribute::updateImpl(...).
2190   ChangeStatus updateImpl(Attributor &A) override {
2191     return indicatePessimisticFixpoint();
2192   }
2193 };
2194 
2195 struct AAReachabilityFunction final : public AAReachabilityImpl {
2196   AAReachabilityFunction(const IRPosition &IRP) : AAReachabilityImpl(IRP) {}
2197 
2198   /// See AbstractAttribute::trackStatistics()
2199   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(reachable); }
2200 };
2201 
2202 /// ------------------------ NoAlias Argument Attribute ------------------------
2203 
2204 struct AANoAliasImpl : AANoAlias {
2205   AANoAliasImpl(const IRPosition &IRP) : AANoAlias(IRP) {
2206     assert(getAssociatedType()->isPointerTy() &&
2207            "Noalias is a pointer attribute");
2208   }
2209 
2210   const std::string getAsStr() const override {
2211     return getAssumed() ? "noalias" : "may-alias";
2212   }
2213 };
2214 
2215 /// NoAlias attribute for a floating value.
2216 struct AANoAliasFloating final : AANoAliasImpl {
2217   AANoAliasFloating(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
2218 
2219   /// See AbstractAttribute::initialize(...).
2220   void initialize(Attributor &A) override {
2221     AANoAliasImpl::initialize(A);
2222     Value *Val = &getAssociatedValue();
2223     do {
2224       CastInst *CI = dyn_cast<CastInst>(Val);
2225       if (!CI)
2226         break;
2227       Value *Base = CI->getOperand(0);
2228       if (Base->getNumUses() != 1)
2229         break;
2230       Val = Base;
2231     } while (true);
2232 
2233     if (!Val->getType()->isPointerTy()) {
2234       indicatePessimisticFixpoint();
2235       return;
2236     }
2237 
2238     if (isa<AllocaInst>(Val))
2239       indicateOptimisticFixpoint();
2240     else if (isa<ConstantPointerNull>(Val) &&
2241              !NullPointerIsDefined(getAnchorScope(),
2242                                    Val->getType()->getPointerAddressSpace()))
2243       indicateOptimisticFixpoint();
2244     else if (Val != &getAssociatedValue()) {
2245       const auto &ValNoAliasAA =
2246           A.getAAFor<AANoAlias>(*this, IRPosition::value(*Val));
2247       if (ValNoAliasAA.isKnownNoAlias())
2248         indicateOptimisticFixpoint();
2249     }
2250   }
2251 
2252   /// See AbstractAttribute::updateImpl(...).
2253   ChangeStatus updateImpl(Attributor &A) override {
2254     // TODO: Implement this.
2255     return indicatePessimisticFixpoint();
2256   }
2257 
2258   /// See AbstractAttribute::trackStatistics()
2259   void trackStatistics() const override {
2260     STATS_DECLTRACK_FLOATING_ATTR(noalias)
2261   }
2262 };
2263 
2264 /// NoAlias attribute for an argument.
2265 struct AANoAliasArgument final
2266     : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
2267   using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
2268   AANoAliasArgument(const IRPosition &IRP) : Base(IRP) {}
2269 
2270   /// See AbstractAttribute::initialize(...).
2271   void initialize(Attributor &A) override {
2272     Base::initialize(A);
2273     // See callsite argument attribute and callee argument attribute.
2274     if (hasAttr({Attribute::ByVal}))
2275       indicateOptimisticFixpoint();
2276   }
2277 
2278   /// See AbstractAttribute::update(...).
2279   ChangeStatus updateImpl(Attributor &A) override {
2280     // We have to make sure no-alias on the argument does not break
2281     // synchronization when this is a callback argument, see also [1] below.
2282     // If synchronization cannot be affected, we delegate to the base updateImpl
2283     // function, otherwise we give up for now.
2284 
2285     // If the function is no-sync, no-alias cannot break synchronization.
2286     const auto &NoSyncAA = A.getAAFor<AANoSync>(
2287         *this, IRPosition::function_scope(getIRPosition()));
2288     if (NoSyncAA.isAssumedNoSync())
2289       return Base::updateImpl(A);
2290 
2291     // If the argument is read-only, no-alias cannot break synchronization.
2292     const auto &MemBehaviorAA =
2293         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition());
2294     if (MemBehaviorAA.isAssumedReadOnly())
2295       return Base::updateImpl(A);
2296 
2297     // If the argument is never passed through callbacks, no-alias cannot break
2298     // synchronization.
2299     bool AllCallSitesKnown;
2300     if (A.checkForAllCallSites(
2301             [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this,
2302             true, AllCallSitesKnown))
2303       return Base::updateImpl(A);
2304 
2305     // TODO: add no-alias but make sure it doesn't break synchronization by
2306     // introducing fake uses. See:
2307     // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel,
2308     //     International Workshop on OpenMP 2018,
2309     //     http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf
2310 
2311     return indicatePessimisticFixpoint();
2312   }
2313 
2314   /// See AbstractAttribute::trackStatistics()
2315   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
2316 };
2317 
2318 struct AANoAliasCallSiteArgument final : AANoAliasImpl {
2319   AANoAliasCallSiteArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
2320 
2321   /// See AbstractAttribute::initialize(...).
2322   void initialize(Attributor &A) override {
2323     // See callsite argument attribute and callee argument attribute.
2324     ImmutableCallSite ICS(&getAnchorValue());
2325     if (ICS.paramHasAttr(getArgNo(), Attribute::NoAlias))
2326       indicateOptimisticFixpoint();
2327     Value &Val = getAssociatedValue();
2328     if (isa<ConstantPointerNull>(Val) &&
2329         !NullPointerIsDefined(getAnchorScope(),
2330                               Val.getType()->getPointerAddressSpace()))
2331       indicateOptimisticFixpoint();
2332   }
2333 
2334   /// Determine if the underlying value may alias with the call site argument
2335   /// \p OtherArgNo of \p ICS (= the underlying call site).
2336   bool mayAliasWithArgument(Attributor &A, AAResults *&AAR,
2337                             const AAMemoryBehavior &MemBehaviorAA,
2338                             ImmutableCallSite ICS, unsigned OtherArgNo) {
2339     // We do not need to worry about aliasing with the underlying IRP.
2340     if (this->getArgNo() == (int)OtherArgNo)
2341       return false;
2342 
2343     // If it is not a pointer or pointer vector we do not alias.
2344     const Value *ArgOp = ICS.getArgOperand(OtherArgNo);
2345     if (!ArgOp->getType()->isPtrOrPtrVectorTy())
2346       return false;
2347 
2348     auto &ICSArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
2349         *this, IRPosition::callsite_argument(ICS, OtherArgNo),
2350         /* TrackDependence */ false);
2351 
2352     // If the argument is readnone, there is no read-write aliasing.
2353     if (ICSArgMemBehaviorAA.isAssumedReadNone()) {
2354       A.recordDependence(ICSArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
2355       return false;
2356     }
2357 
2358     // If the argument is readonly and the underlying value is readonly, there
2359     // is no read-write aliasing.
2360     bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly();
2361     if (ICSArgMemBehaviorAA.isAssumedReadOnly() && IsReadOnly) {
2362       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
2363       A.recordDependence(ICSArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
2364       return false;
2365     }
2366 
2367     // We have to utilize actual alias analysis queries so we need the object.
2368     if (!AAR)
2369       AAR = A.getInfoCache().getAAResultsForFunction(*getAnchorScope());
2370 
2371     // Try to rule it out at the call site.
2372     bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp);
2373     LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between "
2374                          "callsite arguments: "
2375                       << getAssociatedValue() << " " << *ArgOp << " => "
2376                       << (IsAliasing ? "" : "no-") << "alias \n");
2377 
2378     return IsAliasing;
2379   }
2380 
2381   bool
2382   isKnownNoAliasDueToNoAliasPreservation(Attributor &A, AAResults *&AAR,
2383                                          const AAMemoryBehavior &MemBehaviorAA,
2384                                          const AANoAlias &NoAliasAA) {
2385     // We can deduce "noalias" if the following conditions hold.
2386     // (i)   Associated value is assumed to be noalias in the definition.
2387     // (ii)  Associated value is assumed to be no-capture in all the uses
2388     //       possibly executed before this callsite.
2389     // (iii) There is no other pointer argument which could alias with the
2390     //       value.
2391 
2392     bool AssociatedValueIsNoAliasAtDef = NoAliasAA.isAssumedNoAlias();
2393     if (!AssociatedValueIsNoAliasAtDef) {
2394       LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue()
2395                         << " is not no-alias at the definition\n");
2396       return false;
2397     }
2398 
2399     A.recordDependence(NoAliasAA, *this, DepClassTy::OPTIONAL);
2400 
2401     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
2402     auto &NoCaptureAA =
2403         A.getAAFor<AANoCapture>(*this, VIRP, /* TrackDependence */ false);
2404     // Check whether the value is captured in the scope using AANoCapture.
2405     //      Look at CFG and check only uses possibly executed before this
2406     //      callsite.
2407     auto UsePred = [&](const Use &U, bool &Follow) -> bool {
2408       Instruction *UserI = cast<Instruction>(U.getUser());
2409 
2410       // If user if curr instr and only use.
2411       if ((UserI == getCtxI()) && (UserI->getNumUses() == 1))
2412         return true;
2413 
2414       const Function *ScopeFn = VIRP.getAnchorScope();
2415       if (ScopeFn) {
2416         const auto &ReachabilityAA =
2417             A.getAAFor<AAReachability>(*this, IRPosition::function(*ScopeFn));
2418 
2419         if (!ReachabilityAA.isAssumedReachable(UserI, getCtxI()))
2420           return true;
2421 
2422         if (auto *CB = dyn_cast<CallBase>(UserI)) {
2423           if (CB->isArgOperand(&U)) {
2424 
2425             unsigned ArgNo = CB->getArgOperandNo(&U);
2426 
2427             const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
2428                 *this, IRPosition::callsite_argument(*CB, ArgNo));
2429 
2430             if (NoCaptureAA.isAssumedNoCapture())
2431               return true;
2432           }
2433         }
2434       }
2435 
2436       // For cases which can potentially have more users
2437       if (isa<GetElementPtrInst>(U) || isa<BitCastInst>(U) || isa<PHINode>(U) ||
2438           isa<SelectInst>(U)) {
2439         Follow = true;
2440         return true;
2441       }
2442 
2443       LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *U << "\n");
2444       return false;
2445     };
2446 
2447     if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
2448       if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) {
2449         LLVM_DEBUG(
2450             dbgs() << "[AANoAliasCSArg] " << getAssociatedValue()
2451                    << " cannot be noalias as it is potentially captured\n");
2452         return false;
2453       }
2454     }
2455     A.recordDependence(NoCaptureAA, *this, DepClassTy::OPTIONAL);
2456 
2457     // Check there is no other pointer argument which could alias with the
2458     // value passed at this call site.
2459     // TODO: AbstractCallSite
2460     ImmutableCallSite ICS(&getAnchorValue());
2461     for (unsigned OtherArgNo = 0; OtherArgNo < ICS.getNumArgOperands();
2462          OtherArgNo++)
2463       if (mayAliasWithArgument(A, AAR, MemBehaviorAA, ICS, OtherArgNo))
2464         return false;
2465 
2466     return true;
2467   }
2468 
2469   /// See AbstractAttribute::updateImpl(...).
2470   ChangeStatus updateImpl(Attributor &A) override {
2471     // If the argument is readnone we are done as there are no accesses via the
2472     // argument.
2473     auto &MemBehaviorAA =
2474         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(),
2475                                      /* TrackDependence */ false);
2476     if (MemBehaviorAA.isAssumedReadNone()) {
2477       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
2478       return ChangeStatus::UNCHANGED;
2479     }
2480 
2481     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
2482     const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, VIRP,
2483                                                   /* TrackDependence */ false);
2484 
2485     AAResults *AAR = nullptr;
2486     if (isKnownNoAliasDueToNoAliasPreservation(A, AAR, MemBehaviorAA,
2487                                                NoAliasAA)) {
2488       LLVM_DEBUG(
2489           dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n");
2490       return ChangeStatus::UNCHANGED;
2491     }
2492 
2493     return indicatePessimisticFixpoint();
2494   }
2495 
2496   /// See AbstractAttribute::trackStatistics()
2497   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) }
2498 };
2499 
2500 /// NoAlias attribute for function return value.
2501 struct AANoAliasReturned final : AANoAliasImpl {
2502   AANoAliasReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
2503 
2504   /// See AbstractAttribute::updateImpl(...).
2505   virtual ChangeStatus updateImpl(Attributor &A) override {
2506 
2507     auto CheckReturnValue = [&](Value &RV) -> bool {
2508       if (Constant *C = dyn_cast<Constant>(&RV))
2509         if (C->isNullValue() || isa<UndefValue>(C))
2510           return true;
2511 
2512       /// For now, we can only deduce noalias if we have call sites.
2513       /// FIXME: add more support.
2514       ImmutableCallSite ICS(&RV);
2515       if (!ICS)
2516         return false;
2517 
2518       const IRPosition &RVPos = IRPosition::value(RV);
2519       const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, RVPos);
2520       if (!NoAliasAA.isAssumedNoAlias())
2521         return false;
2522 
2523       const auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, RVPos);
2524       return NoCaptureAA.isAssumedNoCaptureMaybeReturned();
2525     };
2526 
2527     if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
2528       return indicatePessimisticFixpoint();
2529 
2530     return ChangeStatus::UNCHANGED;
2531   }
2532 
2533   /// See AbstractAttribute::trackStatistics()
2534   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
2535 };
2536 
2537 /// NoAlias attribute deduction for a call site return value.
2538 struct AANoAliasCallSiteReturned final : AANoAliasImpl {
2539   AANoAliasCallSiteReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
2540 
2541   /// See AbstractAttribute::initialize(...).
2542   void initialize(Attributor &A) override {
2543     AANoAliasImpl::initialize(A);
2544     Function *F = getAssociatedFunction();
2545     if (!F)
2546       indicatePessimisticFixpoint();
2547   }
2548 
2549   /// See AbstractAttribute::updateImpl(...).
2550   ChangeStatus updateImpl(Attributor &A) override {
2551     // TODO: Once we have call site specific value information we can provide
2552     //       call site specific liveness information and then it makes
2553     //       sense to specialize attributes for call sites arguments instead of
2554     //       redirecting requests to the callee argument.
2555     Function *F = getAssociatedFunction();
2556     const IRPosition &FnPos = IRPosition::returned(*F);
2557     auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos);
2558     return clampStateAndIndicateChange(
2559         getState(), static_cast<const AANoAlias::StateType &>(FnAA.getState()));
2560   }
2561 
2562   /// See AbstractAttribute::trackStatistics()
2563   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); }
2564 };
2565 
2566 /// -------------------AAIsDead Function Attribute-----------------------
2567 
2568 struct AAIsDeadValueImpl : public AAIsDead {
2569   AAIsDeadValueImpl(const IRPosition &IRP) : AAIsDead(IRP) {}
2570 
2571   /// See AAIsDead::isAssumedDead().
2572   bool isAssumedDead() const override { return getAssumed(); }
2573 
2574   /// See AAIsDead::isKnownDead().
2575   bool isKnownDead() const override { return getKnown(); }
2576 
2577   /// See AAIsDead::isAssumedDead(BasicBlock *).
2578   bool isAssumedDead(const BasicBlock *BB) const override { return false; }
2579 
2580   /// See AAIsDead::isKnownDead(BasicBlock *).
2581   bool isKnownDead(const BasicBlock *BB) const override { return false; }
2582 
2583   /// See AAIsDead::isAssumedDead(Instruction *I).
2584   bool isAssumedDead(const Instruction *I) const override {
2585     return I == getCtxI() && isAssumedDead();
2586   }
2587 
2588   /// See AAIsDead::isKnownDead(Instruction *I).
2589   bool isKnownDead(const Instruction *I) const override {
2590     return isAssumedDead(I) && getKnown();
2591   }
2592 
2593   /// See AbstractAttribute::getAsStr().
2594   const std::string getAsStr() const override {
2595     return isAssumedDead() ? "assumed-dead" : "assumed-live";
2596   }
2597 
2598   /// Check if all uses are assumed dead.
2599   bool areAllUsesAssumedDead(Attributor &A, Value &V) {
2600     auto UsePred = [&](const Use &U, bool &Follow) { return false; };
2601     // Explicitly set the dependence class to required because we want a long
2602     // chain of N dependent instructions to be considered live as soon as one is
2603     // without going through N update cycles. This is not required for
2604     // correctness.
2605     return A.checkForAllUses(UsePred, *this, V, DepClassTy::REQUIRED);
2606   }
2607 
2608   /// Determine if \p I is assumed to be side-effect free.
2609   bool isAssumedSideEffectFree(Attributor &A, Instruction *I) {
2610     if (!I || wouldInstructionBeTriviallyDead(I))
2611       return true;
2612 
2613     auto *CB = dyn_cast<CallBase>(I);
2614     if (!CB || isa<IntrinsicInst>(CB))
2615       return false;
2616 
2617     const IRPosition &CallIRP = IRPosition::callsite_function(*CB);
2618     const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(*this, CallIRP);
2619     if (!NoUnwindAA.isAssumedNoUnwind())
2620       return false;
2621 
2622     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(*this, CallIRP);
2623     if (!MemBehaviorAA.isAssumedReadOnly())
2624       return false;
2625 
2626     return true;
2627   }
2628 };
2629 
2630 struct AAIsDeadFloating : public AAIsDeadValueImpl {
2631   AAIsDeadFloating(const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {}
2632 
2633   /// See AbstractAttribute::initialize(...).
2634   void initialize(Attributor &A) override {
2635     if (isa<UndefValue>(getAssociatedValue())) {
2636       indicatePessimisticFixpoint();
2637       return;
2638     }
2639 
2640     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
2641     if (!isAssumedSideEffectFree(A, I))
2642       indicatePessimisticFixpoint();
2643   }
2644 
2645   /// See AbstractAttribute::updateImpl(...).
2646   ChangeStatus updateImpl(Attributor &A) override {
2647     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
2648     if (!isAssumedSideEffectFree(A, I))
2649       return indicatePessimisticFixpoint();
2650 
2651     if (!areAllUsesAssumedDead(A, getAssociatedValue()))
2652       return indicatePessimisticFixpoint();
2653     return ChangeStatus::UNCHANGED;
2654   }
2655 
2656   /// See AbstractAttribute::manifest(...).
2657   ChangeStatus manifest(Attributor &A) override {
2658     Value &V = getAssociatedValue();
2659     if (auto *I = dyn_cast<Instruction>(&V)) {
2660       // If we get here we basically know the users are all dead. We check if
2661       // isAssumedSideEffectFree returns true here again because it might not be
2662       // the case and only the users are dead but the instruction (=call) is
2663       // still needed.
2664       if (isAssumedSideEffectFree(A, I) && !isa<InvokeInst>(I)) {
2665         A.deleteAfterManifest(*I);
2666         return ChangeStatus::CHANGED;
2667       }
2668     }
2669     if (V.use_empty())
2670       return ChangeStatus::UNCHANGED;
2671 
2672     bool UsedAssumedInformation = false;
2673     Optional<Constant *> C =
2674         A.getAssumedConstant(V, *this, UsedAssumedInformation);
2675     if (C.hasValue() && C.getValue())
2676       return ChangeStatus::UNCHANGED;
2677 
2678     // Replace the value with undef as it is dead but keep droppable uses around
2679     // as they provide information we don't want to give up on just yet.
2680     UndefValue &UV = *UndefValue::get(V.getType());
2681     bool AnyChange =
2682         A.changeValueAfterManifest(V, UV, /* ChangeDropppable */ false);
2683     return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
2684   }
2685 
2686   /// See AbstractAttribute::trackStatistics()
2687   void trackStatistics() const override {
2688     STATS_DECLTRACK_FLOATING_ATTR(IsDead)
2689   }
2690 };
2691 
2692 struct AAIsDeadArgument : public AAIsDeadFloating {
2693   AAIsDeadArgument(const IRPosition &IRP) : AAIsDeadFloating(IRP) {}
2694 
2695   /// See AbstractAttribute::initialize(...).
2696   void initialize(Attributor &A) override {
2697     if (!A.isFunctionIPOAmendable(*getAnchorScope()))
2698       indicatePessimisticFixpoint();
2699   }
2700 
2701   /// See AbstractAttribute::manifest(...).
2702   ChangeStatus manifest(Attributor &A) override {
2703     ChangeStatus Changed = AAIsDeadFloating::manifest(A);
2704     Argument &Arg = *getAssociatedArgument();
2705     if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {}))
2706       if (A.registerFunctionSignatureRewrite(
2707               Arg, /* ReplacementTypes */ {},
2708               Attributor::ArgumentReplacementInfo::CalleeRepairCBTy{},
2709               Attributor::ArgumentReplacementInfo::ACSRepairCBTy{})) {
2710         Arg.dropDroppableUses();
2711         return ChangeStatus::CHANGED;
2712       }
2713     return Changed;
2714   }
2715 
2716   /// See AbstractAttribute::trackStatistics()
2717   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) }
2718 };
2719 
2720 struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl {
2721   AAIsDeadCallSiteArgument(const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {}
2722 
2723   /// See AbstractAttribute::initialize(...).
2724   void initialize(Attributor &A) override {
2725     if (isa<UndefValue>(getAssociatedValue()))
2726       indicatePessimisticFixpoint();
2727   }
2728 
2729   /// See AbstractAttribute::updateImpl(...).
2730   ChangeStatus updateImpl(Attributor &A) override {
2731     // TODO: Once we have call site specific value information we can provide
2732     //       call site specific liveness information and then it makes
2733     //       sense to specialize attributes for call sites arguments instead of
2734     //       redirecting requests to the callee argument.
2735     Argument *Arg = getAssociatedArgument();
2736     if (!Arg)
2737       return indicatePessimisticFixpoint();
2738     const IRPosition &ArgPos = IRPosition::argument(*Arg);
2739     auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos);
2740     return clampStateAndIndicateChange(
2741         getState(), static_cast<const AAIsDead::StateType &>(ArgAA.getState()));
2742   }
2743 
2744   /// See AbstractAttribute::manifest(...).
2745   ChangeStatus manifest(Attributor &A) override {
2746     CallBase &CB = cast<CallBase>(getAnchorValue());
2747     Use &U = CB.getArgOperandUse(getArgNo());
2748     assert(!isa<UndefValue>(U.get()) &&
2749            "Expected undef values to be filtered out!");
2750     UndefValue &UV = *UndefValue::get(U->getType());
2751     if (A.changeUseAfterManifest(U, UV))
2752       return ChangeStatus::CHANGED;
2753     return ChangeStatus::UNCHANGED;
2754   }
2755 
2756   /// See AbstractAttribute::trackStatistics()
2757   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) }
2758 };
2759 
2760 struct AAIsDeadCallSiteReturned : public AAIsDeadFloating {
2761   AAIsDeadCallSiteReturned(const IRPosition &IRP)
2762       : AAIsDeadFloating(IRP), IsAssumedSideEffectFree(true) {}
2763 
2764   /// See AAIsDead::isAssumedDead().
2765   bool isAssumedDead() const override {
2766     return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
2767   }
2768 
2769   /// See AbstractAttribute::initialize(...).
2770   void initialize(Attributor &A) override {
2771     if (isa<UndefValue>(getAssociatedValue())) {
2772       indicatePessimisticFixpoint();
2773       return;
2774     }
2775 
2776     // We track this separately as a secondary state.
2777     IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI());
2778   }
2779 
2780   /// See AbstractAttribute::updateImpl(...).
2781   ChangeStatus updateImpl(Attributor &A) override {
2782     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2783     if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) {
2784       IsAssumedSideEffectFree = false;
2785       Changed = ChangeStatus::CHANGED;
2786     }
2787 
2788     if (!areAllUsesAssumedDead(A, getAssociatedValue()))
2789       return indicatePessimisticFixpoint();
2790     return Changed;
2791   }
2792 
2793   /// See AbstractAttribute::trackStatistics()
2794   void trackStatistics() const override {
2795     if (IsAssumedSideEffectFree)
2796       STATS_DECLTRACK_CSRET_ATTR(IsDead)
2797     else
2798       STATS_DECLTRACK_CSRET_ATTR(UnusedResult)
2799   }
2800 
2801   /// See AbstractAttribute::getAsStr().
2802   const std::string getAsStr() const override {
2803     return isAssumedDead()
2804                ? "assumed-dead"
2805                : (getAssumed() ? "assumed-dead-users" : "assumed-live");
2806   }
2807 
2808 private:
2809   bool IsAssumedSideEffectFree;
2810 };
2811 
2812 struct AAIsDeadReturned : public AAIsDeadValueImpl {
2813   AAIsDeadReturned(const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {}
2814 
2815   /// See AbstractAttribute::updateImpl(...).
2816   ChangeStatus updateImpl(Attributor &A) override {
2817 
2818     A.checkForAllInstructions([](Instruction &) { return true; }, *this,
2819                               {Instruction::Ret});
2820 
2821     auto PredForCallSite = [&](AbstractCallSite ACS) {
2822       if (ACS.isCallbackCall() || !ACS.getInstruction())
2823         return false;
2824       return areAllUsesAssumedDead(A, *ACS.getInstruction());
2825     };
2826 
2827     bool AllCallSitesKnown;
2828     if (!A.checkForAllCallSites(PredForCallSite, *this, true,
2829                                 AllCallSitesKnown))
2830       return indicatePessimisticFixpoint();
2831 
2832     return ChangeStatus::UNCHANGED;
2833   }
2834 
2835   /// See AbstractAttribute::manifest(...).
2836   ChangeStatus manifest(Attributor &A) override {
2837     // TODO: Rewrite the signature to return void?
2838     bool AnyChange = false;
2839     UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType());
2840     auto RetInstPred = [&](Instruction &I) {
2841       ReturnInst &RI = cast<ReturnInst>(I);
2842       if (!isa<UndefValue>(RI.getReturnValue()))
2843         AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV);
2844       return true;
2845     };
2846     A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret});
2847     return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
2848   }
2849 
2850   /// See AbstractAttribute::trackStatistics()
2851   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) }
2852 };
2853 
2854 struct AAIsDeadFunction : public AAIsDead {
2855   AAIsDeadFunction(const IRPosition &IRP) : AAIsDead(IRP) {}
2856 
2857   /// See AbstractAttribute::initialize(...).
2858   void initialize(Attributor &A) override {
2859     const Function *F = getAnchorScope();
2860     if (F && !F->isDeclaration()) {
2861       ToBeExploredFrom.insert(&F->getEntryBlock().front());
2862       assumeLive(A, F->getEntryBlock());
2863     }
2864   }
2865 
2866   /// See AbstractAttribute::getAsStr().
2867   const std::string getAsStr() const override {
2868     return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
2869            std::to_string(getAnchorScope()->size()) + "][#TBEP " +
2870            std::to_string(ToBeExploredFrom.size()) + "][#KDE " +
2871            std::to_string(KnownDeadEnds.size()) + "]";
2872   }
2873 
2874   /// See AbstractAttribute::manifest(...).
2875   ChangeStatus manifest(Attributor &A) override {
2876     assert(getState().isValidState() &&
2877            "Attempted to manifest an invalid state!");
2878 
2879     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
2880     Function &F = *getAnchorScope();
2881 
2882     if (AssumedLiveBlocks.empty()) {
2883       A.deleteAfterManifest(F);
2884       return ChangeStatus::CHANGED;
2885     }
2886 
2887     // Flag to determine if we can change an invoke to a call assuming the
2888     // callee is nounwind. This is not possible if the personality of the
2889     // function allows to catch asynchronous exceptions.
2890     bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
2891 
2892     KnownDeadEnds.set_union(ToBeExploredFrom);
2893     for (const Instruction *DeadEndI : KnownDeadEnds) {
2894       auto *CB = dyn_cast<CallBase>(DeadEndI);
2895       if (!CB)
2896         continue;
2897       const auto &NoReturnAA =
2898           A.getAAFor<AANoReturn>(*this, IRPosition::callsite_function(*CB));
2899       bool MayReturn = !NoReturnAA.isAssumedNoReturn();
2900       if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
2901         continue;
2902 
2903       if (auto *II = dyn_cast<InvokeInst>(DeadEndI))
2904         A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II));
2905       else
2906         A.changeToUnreachableAfterManifest(
2907             const_cast<Instruction *>(DeadEndI->getNextNode()));
2908       HasChanged = ChangeStatus::CHANGED;
2909     }
2910 
2911     STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted.");
2912     for (BasicBlock &BB : F)
2913       if (!AssumedLiveBlocks.count(&BB)) {
2914         A.deleteAfterManifest(BB);
2915         ++BUILD_STAT_NAME(AAIsDead, BasicBlock);
2916       }
2917 
2918     return HasChanged;
2919   }
2920 
2921   /// See AbstractAttribute::updateImpl(...).
2922   ChangeStatus updateImpl(Attributor &A) override;
2923 
2924   /// See AbstractAttribute::trackStatistics()
2925   void trackStatistics() const override {}
2926 
2927   /// Returns true if the function is assumed dead.
2928   bool isAssumedDead() const override { return false; }
2929 
2930   /// See AAIsDead::isKnownDead().
2931   bool isKnownDead() const override { return false; }
2932 
2933   /// See AAIsDead::isAssumedDead(BasicBlock *).
2934   bool isAssumedDead(const BasicBlock *BB) const override {
2935     assert(BB->getParent() == getAnchorScope() &&
2936            "BB must be in the same anchor scope function.");
2937 
2938     if (!getAssumed())
2939       return false;
2940     return !AssumedLiveBlocks.count(BB);
2941   }
2942 
2943   /// See AAIsDead::isKnownDead(BasicBlock *).
2944   bool isKnownDead(const BasicBlock *BB) const override {
2945     return getKnown() && isAssumedDead(BB);
2946   }
2947 
2948   /// See AAIsDead::isAssumed(Instruction *I).
2949   bool isAssumedDead(const Instruction *I) const override {
2950     assert(I->getParent()->getParent() == getAnchorScope() &&
2951            "Instruction must be in the same anchor scope function.");
2952 
2953     if (!getAssumed())
2954       return false;
2955 
2956     // If it is not in AssumedLiveBlocks then it for sure dead.
2957     // Otherwise, it can still be after noreturn call in a live block.
2958     if (!AssumedLiveBlocks.count(I->getParent()))
2959       return true;
2960 
2961     // If it is not after a liveness barrier it is live.
2962     const Instruction *PrevI = I->getPrevNode();
2963     while (PrevI) {
2964       if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
2965         return true;
2966       PrevI = PrevI->getPrevNode();
2967     }
2968     return false;
2969   }
2970 
2971   /// See AAIsDead::isKnownDead(Instruction *I).
2972   bool isKnownDead(const Instruction *I) const override {
2973     return getKnown() && isAssumedDead(I);
2974   }
2975 
2976   /// Assume \p BB is (partially) live now and indicate to the Attributor \p A
2977   /// that internal function called from \p BB should now be looked at.
2978   bool assumeLive(Attributor &A, const BasicBlock &BB) {
2979     if (!AssumedLiveBlocks.insert(&BB).second)
2980       return false;
2981 
2982     // We assume that all of BB is (probably) live now and if there are calls to
2983     // internal functions we will assume that those are now live as well. This
2984     // is a performance optimization for blocks with calls to a lot of internal
2985     // functions. It can however cause dead functions to be treated as live.
2986     for (const Instruction &I : BB)
2987       if (ImmutableCallSite ICS = ImmutableCallSite(&I))
2988         if (const Function *F = ICS.getCalledFunction())
2989           if (F->hasLocalLinkage())
2990             A.markLiveInternalFunction(*F);
2991     return true;
2992   }
2993 
2994   /// Collection of instructions that need to be explored again, e.g., we
2995   /// did assume they do not transfer control to (one of their) successors.
2996   SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
2997 
2998   /// Collection of instructions that are known to not transfer control.
2999   SmallSetVector<const Instruction *, 8> KnownDeadEnds;
3000 
3001   /// Collection of all assumed live BasicBlocks.
3002   DenseSet<const BasicBlock *> AssumedLiveBlocks;
3003 };
3004 
3005 static bool
3006 identifyAliveSuccessors(Attributor &A, const CallBase &CB,
3007                         AbstractAttribute &AA,
3008                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3009   const IRPosition &IPos = IRPosition::callsite_function(CB);
3010 
3011   const auto &NoReturnAA = A.getAAFor<AANoReturn>(AA, IPos);
3012   if (NoReturnAA.isAssumedNoReturn())
3013     return !NoReturnAA.isKnownNoReturn();
3014   if (CB.isTerminator())
3015     AliveSuccessors.push_back(&CB.getSuccessor(0)->front());
3016   else
3017     AliveSuccessors.push_back(CB.getNextNode());
3018   return false;
3019 }
3020 
3021 static bool
3022 identifyAliveSuccessors(Attributor &A, const InvokeInst &II,
3023                         AbstractAttribute &AA,
3024                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3025   bool UsedAssumedInformation =
3026       identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
3027 
3028   // First, determine if we can change an invoke to a call assuming the
3029   // callee is nounwind. This is not possible if the personality of the
3030   // function allows to catch asynchronous exceptions.
3031   if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) {
3032     AliveSuccessors.push_back(&II.getUnwindDest()->front());
3033   } else {
3034     const IRPosition &IPos = IRPosition::callsite_function(II);
3035     const auto &AANoUnw = A.getAAFor<AANoUnwind>(AA, IPos);
3036     if (AANoUnw.isAssumedNoUnwind()) {
3037       UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind();
3038     } else {
3039       AliveSuccessors.push_back(&II.getUnwindDest()->front());
3040     }
3041   }
3042   return UsedAssumedInformation;
3043 }
3044 
3045 static bool
3046 identifyAliveSuccessors(Attributor &A, const BranchInst &BI,
3047                         AbstractAttribute &AA,
3048                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3049   bool UsedAssumedInformation = false;
3050   if (BI.getNumSuccessors() == 1) {
3051     AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
3052   } else {
3053     Optional<ConstantInt *> CI = getAssumedConstantInt(
3054         A, *BI.getCondition(), AA, UsedAssumedInformation);
3055     if (!CI.hasValue()) {
3056       // No value yet, assume both edges are dead.
3057     } else if (CI.getValue()) {
3058       const BasicBlock *SuccBB =
3059           BI.getSuccessor(1 - CI.getValue()->getZExtValue());
3060       AliveSuccessors.push_back(&SuccBB->front());
3061     } else {
3062       AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
3063       AliveSuccessors.push_back(&BI.getSuccessor(1)->front());
3064       UsedAssumedInformation = false;
3065     }
3066   }
3067   return UsedAssumedInformation;
3068 }
3069 
3070 static bool
3071 identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
3072                         AbstractAttribute &AA,
3073                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3074   bool UsedAssumedInformation = false;
3075   Optional<ConstantInt *> CI =
3076       getAssumedConstantInt(A, *SI.getCondition(), AA, UsedAssumedInformation);
3077   if (!CI.hasValue()) {
3078     // No value yet, assume all edges are dead.
3079   } else if (CI.getValue()) {
3080     for (auto &CaseIt : SI.cases()) {
3081       if (CaseIt.getCaseValue() == CI.getValue()) {
3082         AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
3083         return UsedAssumedInformation;
3084       }
3085     }
3086     AliveSuccessors.push_back(&SI.getDefaultDest()->front());
3087     return UsedAssumedInformation;
3088   } else {
3089     for (const BasicBlock *SuccBB : successors(SI.getParent()))
3090       AliveSuccessors.push_back(&SuccBB->front());
3091   }
3092   return UsedAssumedInformation;
3093 }
3094 
3095 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
3096   ChangeStatus Change = ChangeStatus::UNCHANGED;
3097 
3098   LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/"
3099                     << getAnchorScope()->size() << "] BBs and "
3100                     << ToBeExploredFrom.size() << " exploration points and "
3101                     << KnownDeadEnds.size() << " known dead ends\n");
3102 
3103   // Copy and clear the list of instructions we need to explore from. It is
3104   // refilled with instructions the next update has to look at.
3105   SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(),
3106                                                ToBeExploredFrom.end());
3107   decltype(ToBeExploredFrom) NewToBeExploredFrom;
3108 
3109   SmallVector<const Instruction *, 8> AliveSuccessors;
3110   while (!Worklist.empty()) {
3111     const Instruction *I = Worklist.pop_back_val();
3112     LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n");
3113 
3114     AliveSuccessors.clear();
3115 
3116     bool UsedAssumedInformation = false;
3117     switch (I->getOpcode()) {
3118     // TODO: look for (assumed) UB to backwards propagate "deadness".
3119     default:
3120       if (I->isTerminator()) {
3121         for (const BasicBlock *SuccBB : successors(I->getParent()))
3122           AliveSuccessors.push_back(&SuccBB->front());
3123       } else {
3124         AliveSuccessors.push_back(I->getNextNode());
3125       }
3126       break;
3127     case Instruction::Call:
3128       UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
3129                                                        *this, AliveSuccessors);
3130       break;
3131     case Instruction::Invoke:
3132       UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
3133                                                        *this, AliveSuccessors);
3134       break;
3135     case Instruction::Br:
3136       UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I),
3137                                                        *this, AliveSuccessors);
3138       break;
3139     case Instruction::Switch:
3140       UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
3141                                                        *this, AliveSuccessors);
3142       break;
3143     }
3144 
3145     if (UsedAssumedInformation) {
3146       NewToBeExploredFrom.insert(I);
3147     } else {
3148       Change = ChangeStatus::CHANGED;
3149       if (AliveSuccessors.empty() ||
3150           (I->isTerminator() && AliveSuccessors.size() < I->getNumSuccessors()))
3151         KnownDeadEnds.insert(I);
3152     }
3153 
3154     LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: "
3155                       << AliveSuccessors.size() << " UsedAssumedInformation: "
3156                       << UsedAssumedInformation << "\n");
3157 
3158     for (const Instruction *AliveSuccessor : AliveSuccessors) {
3159       if (!I->isTerminator()) {
3160         assert(AliveSuccessors.size() == 1 &&
3161                "Non-terminator expected to have a single successor!");
3162         Worklist.push_back(AliveSuccessor);
3163       } else {
3164         if (assumeLive(A, *AliveSuccessor->getParent()))
3165           Worklist.push_back(AliveSuccessor);
3166       }
3167     }
3168   }
3169 
3170   ToBeExploredFrom = std::move(NewToBeExploredFrom);
3171 
3172   // If we know everything is live there is no need to query for liveness.
3173   // Instead, indicating a pessimistic fixpoint will cause the state to be
3174   // "invalid" and all queries to be answered conservatively without lookups.
3175   // To be in this state we have to (1) finished the exploration and (3) not
3176   // discovered any non-trivial dead end and (2) not ruled unreachable code
3177   // dead.
3178   if (ToBeExploredFrom.empty() &&
3179       getAnchorScope()->size() == AssumedLiveBlocks.size() &&
3180       llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) {
3181         return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
3182       }))
3183     return indicatePessimisticFixpoint();
3184   return Change;
3185 }
3186 
3187 /// Liveness information for a call sites.
3188 struct AAIsDeadCallSite final : AAIsDeadFunction {
3189   AAIsDeadCallSite(const IRPosition &IRP) : AAIsDeadFunction(IRP) {}
3190 
3191   /// See AbstractAttribute::initialize(...).
3192   void initialize(Attributor &A) override {
3193     // TODO: Once we have call site specific value information we can provide
3194     //       call site specific liveness information and then it makes
3195     //       sense to specialize attributes for call sites instead of
3196     //       redirecting requests to the callee.
3197     llvm_unreachable("Abstract attributes for liveness are not "
3198                      "supported for call sites yet!");
3199   }
3200 
3201   /// See AbstractAttribute::updateImpl(...).
3202   ChangeStatus updateImpl(Attributor &A) override {
3203     return indicatePessimisticFixpoint();
3204   }
3205 
3206   /// See AbstractAttribute::trackStatistics()
3207   void trackStatistics() const override {}
3208 };
3209 
3210 /// -------------------- Dereferenceable Argument Attribute --------------------
3211 
3212 template <>
3213 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S,
3214                                                      const DerefState &R) {
3215   ChangeStatus CS0 =
3216       clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState);
3217   ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState);
3218   return CS0 | CS1;
3219 }
3220 
3221 struct AADereferenceableImpl : AADereferenceable {
3222   AADereferenceableImpl(const IRPosition &IRP) : AADereferenceable(IRP) {}
3223   using StateType = DerefState;
3224 
3225   void initialize(Attributor &A) override {
3226     SmallVector<Attribute, 4> Attrs;
3227     getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
3228              Attrs, /* IgnoreSubsumingPositions */ false, &A);
3229     for (const Attribute &Attr : Attrs)
3230       takeKnownDerefBytesMaximum(Attr.getValueAsInt());
3231 
3232     NonNullAA = &A.getAAFor<AANonNull>(*this, getIRPosition(),
3233                                        /* TrackDependence */ false);
3234 
3235     const IRPosition &IRP = this->getIRPosition();
3236     bool IsFnInterface = IRP.isFnInterfaceKind();
3237     Function *FnScope = IRP.getAnchorScope();
3238     if (IsFnInterface && (!FnScope || !A.isFunctionIPOAmendable(*FnScope)))
3239       indicatePessimisticFixpoint();
3240   }
3241 
3242   /// See AbstractAttribute::getState()
3243   /// {
3244   StateType &getState() override { return *this; }
3245   const StateType &getState() const override { return *this; }
3246   /// }
3247 
3248   /// Helper function for collecting accessed bytes in must-be-executed-context
3249   void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I,
3250                               DerefState &State) {
3251     const Value *UseV = U->get();
3252     if (!UseV->getType()->isPointerTy())
3253       return;
3254 
3255     Type *PtrTy = UseV->getType();
3256     const DataLayout &DL = A.getDataLayout();
3257     int64_t Offset;
3258     if (const Value *Base = getBasePointerOfAccessPointerOperand(
3259             I, Offset, DL, /*AllowNonInbounds*/ true)) {
3260       if (Base == &getAssociatedValue() &&
3261           getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
3262         uint64_t Size = DL.getTypeStoreSize(PtrTy->getPointerElementType());
3263         State.addAccessedBytes(Offset, Size);
3264       }
3265     }
3266     return;
3267   }
3268 
3269   /// See AAFromMustBeExecutedContext
3270   bool followUse(Attributor &A, const Use *U, const Instruction *I,
3271                  AADereferenceable::StateType &State) {
3272     bool IsNonNull = false;
3273     bool TrackUse = false;
3274     int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
3275         A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse);
3276 
3277     addAccessedBytesForUse(A, U, I, State);
3278     State.takeKnownDerefBytesMaximum(DerefBytes);
3279     return TrackUse;
3280   }
3281 
3282   /// See AbstractAttribute::manifest(...).
3283   ChangeStatus manifest(Attributor &A) override {
3284     ChangeStatus Change = AADereferenceable::manifest(A);
3285     if (isAssumedNonNull() && hasAttr(Attribute::DereferenceableOrNull)) {
3286       removeAttrs({Attribute::DereferenceableOrNull});
3287       return ChangeStatus::CHANGED;
3288     }
3289     return Change;
3290   }
3291 
3292   void getDeducedAttributes(LLVMContext &Ctx,
3293                             SmallVectorImpl<Attribute> &Attrs) const override {
3294     // TODO: Add *_globally support
3295     if (isAssumedNonNull())
3296       Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
3297           Ctx, getAssumedDereferenceableBytes()));
3298     else
3299       Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
3300           Ctx, getAssumedDereferenceableBytes()));
3301   }
3302 
3303   /// See AbstractAttribute::getAsStr().
3304   const std::string getAsStr() const override {
3305     if (!getAssumedDereferenceableBytes())
3306       return "unknown-dereferenceable";
3307     return std::string("dereferenceable") +
3308            (isAssumedNonNull() ? "" : "_or_null") +
3309            (isAssumedGlobal() ? "_globally" : "") + "<" +
3310            std::to_string(getKnownDereferenceableBytes()) + "-" +
3311            std::to_string(getAssumedDereferenceableBytes()) + ">";
3312   }
3313 };
3314 
3315 /// Dereferenceable attribute for a floating value.
3316 struct AADereferenceableFloating
3317     : AAFromMustBeExecutedContext<AADereferenceable, AADereferenceableImpl> {
3318   using Base =
3319       AAFromMustBeExecutedContext<AADereferenceable, AADereferenceableImpl>;
3320   AADereferenceableFloating(const IRPosition &IRP) : Base(IRP) {}
3321 
3322   /// See AbstractAttribute::updateImpl(...).
3323   ChangeStatus updateImpl(Attributor &A) override {
3324     ChangeStatus Change = Base::updateImpl(A);
3325 
3326     const DataLayout &DL = A.getDataLayout();
3327 
3328     auto VisitValueCB = [&](Value &V, const Instruction *, DerefState &T,
3329                             bool Stripped) -> bool {
3330       unsigned IdxWidth =
3331           DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
3332       APInt Offset(IdxWidth, 0);
3333       const Value *Base =
3334           V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
3335 
3336       const auto &AA =
3337           A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base));
3338       int64_t DerefBytes = 0;
3339       if (!Stripped && this == &AA) {
3340         // Use IR information if we did not strip anything.
3341         // TODO: track globally.
3342         bool CanBeNull;
3343         DerefBytes = Base->getPointerDereferenceableBytes(DL, CanBeNull);
3344         T.GlobalState.indicatePessimisticFixpoint();
3345       } else {
3346         const DerefState &DS = static_cast<const DerefState &>(AA.getState());
3347         DerefBytes = DS.DerefBytesState.getAssumed();
3348         T.GlobalState &= DS.GlobalState;
3349       }
3350 
3351       // TODO: Use `AAConstantRange` to infer dereferenceable bytes.
3352 
3353       // For now we do not try to "increase" dereferenceability due to negative
3354       // indices as we first have to come up with code to deal with loops and
3355       // for overflows of the dereferenceable bytes.
3356       int64_t OffsetSExt = Offset.getSExtValue();
3357       if (OffsetSExt < 0)
3358         OffsetSExt = 0;
3359 
3360       T.takeAssumedDerefBytesMinimum(
3361           std::max(int64_t(0), DerefBytes - OffsetSExt));
3362 
3363       if (this == &AA) {
3364         if (!Stripped) {
3365           // If nothing was stripped IR information is all we got.
3366           T.takeKnownDerefBytesMaximum(
3367               std::max(int64_t(0), DerefBytes - OffsetSExt));
3368           T.indicatePessimisticFixpoint();
3369         } else if (OffsetSExt > 0) {
3370           // If something was stripped but there is circular reasoning we look
3371           // for the offset. If it is positive we basically decrease the
3372           // dereferenceable bytes in a circluar loop now, which will simply
3373           // drive them down to the known value in a very slow way which we
3374           // can accelerate.
3375           T.indicatePessimisticFixpoint();
3376         }
3377       }
3378 
3379       return T.isValidState();
3380     };
3381 
3382     DerefState T;
3383     if (!genericValueTraversal<AADereferenceable, DerefState>(
3384             A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
3385       return indicatePessimisticFixpoint();
3386 
3387     return Change | clampStateAndIndicateChange(getState(), T);
3388   }
3389 
3390   /// See AbstractAttribute::trackStatistics()
3391   void trackStatistics() const override {
3392     STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
3393   }
3394 };
3395 
3396 /// Dereferenceable attribute for a return value.
3397 struct AADereferenceableReturned final
3398     : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
3399   AADereferenceableReturned(const IRPosition &IRP)
3400       : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>(
3401             IRP) {}
3402 
3403   /// See AbstractAttribute::trackStatistics()
3404   void trackStatistics() const override {
3405     STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
3406   }
3407 };
3408 
3409 /// Dereferenceable attribute for an argument
3410 struct AADereferenceableArgument final
3411     : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<
3412           AADereferenceable, AADereferenceableImpl> {
3413   using Base = AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<
3414       AADereferenceable, AADereferenceableImpl>;
3415   AADereferenceableArgument(const IRPosition &IRP) : Base(IRP) {}
3416 
3417   /// See AbstractAttribute::trackStatistics()
3418   void trackStatistics() const override {
3419     STATS_DECLTRACK_ARG_ATTR(dereferenceable)
3420   }
3421 };
3422 
3423 /// Dereferenceable attribute for a call site argument.
3424 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
3425   AADereferenceableCallSiteArgument(const IRPosition &IRP)
3426       : AADereferenceableFloating(IRP) {}
3427 
3428   /// See AbstractAttribute::trackStatistics()
3429   void trackStatistics() const override {
3430     STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
3431   }
3432 };
3433 
3434 /// Dereferenceable attribute deduction for a call site return value.
3435 struct AADereferenceableCallSiteReturned final
3436     : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<
3437           AADereferenceable, AADereferenceableImpl> {
3438   using Base = AACallSiteReturnedFromReturnedAndMustBeExecutedContext<
3439       AADereferenceable, AADereferenceableImpl>;
3440   AADereferenceableCallSiteReturned(const IRPosition &IRP) : Base(IRP) {}
3441 
3442   /// See AbstractAttribute::trackStatistics()
3443   void trackStatistics() const override {
3444     STATS_DECLTRACK_CS_ATTR(dereferenceable);
3445   }
3446 };
3447 
3448 // ------------------------ Align Argument Attribute ------------------------
3449 
3450 /// \p Ptr is accessed so we can get alignment information if the ABI requires
3451 /// the element type to be aligned.
3452 static MaybeAlign getKnownAlignmentFromAccessedPtr(const Value *Ptr,
3453                                                    const DataLayout &DL) {
3454   MaybeAlign KnownAlignment = Ptr->getPointerAlignment(DL);
3455   Type *ElementTy = Ptr->getType()->getPointerElementType();
3456   if (ElementTy->isSized())
3457     KnownAlignment = max(KnownAlignment, DL.getABITypeAlign(ElementTy));
3458   return KnownAlignment;
3459 }
3460 
3461 static unsigned getKnownAlignForUse(Attributor &A,
3462                                     AbstractAttribute &QueryingAA,
3463                                     Value &AssociatedValue, const Use *U,
3464                                     const Instruction *I, bool &TrackUse) {
3465   // We need to follow common pointer manipulation uses to the accesses they
3466   // feed into.
3467   if (isa<CastInst>(I)) {
3468     // Follow all but ptr2int casts.
3469     TrackUse = !isa<PtrToIntInst>(I);
3470     return 0;
3471   }
3472   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3473     if (GEP->hasAllConstantIndices()) {
3474       TrackUse = true;
3475       return 0;
3476     }
3477   }
3478 
3479   MaybeAlign MA;
3480   if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
3481     if (ICS.isBundleOperand(U) || ICS.isCallee(U))
3482       return 0;
3483 
3484     unsigned ArgNo = ICS.getArgumentNo(U);
3485     IRPosition IRP = IRPosition::callsite_argument(ICS, ArgNo);
3486     // As long as we only use known information there is no need to track
3487     // dependences here.
3488     auto &AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP,
3489                                         /* TrackDependence */ false);
3490     MA = MaybeAlign(AlignAA.getKnownAlign());
3491   }
3492 
3493   const DataLayout &DL = A.getDataLayout();
3494   const Value *UseV = U->get();
3495   if (auto *SI = dyn_cast<StoreInst>(I)) {
3496     if (SI->getPointerOperand() == UseV) {
3497       if (unsigned SIAlign = SI->getAlignment())
3498         MA = MaybeAlign(SIAlign);
3499       else
3500         MA = getKnownAlignmentFromAccessedPtr(UseV, DL);
3501     }
3502   } else if (auto *LI = dyn_cast<LoadInst>(I)) {
3503     if (LI->getPointerOperand() == UseV) {
3504       if (unsigned LIAlign = LI->getAlignment())
3505         MA = MaybeAlign(LIAlign);
3506       else
3507         MA = getKnownAlignmentFromAccessedPtr(UseV, DL);
3508     }
3509   }
3510 
3511   if (!MA.hasValue() || MA <= 1)
3512     return 0;
3513 
3514   unsigned Alignment = MA->value();
3515   int64_t Offset;
3516 
3517   if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) {
3518     if (Base == &AssociatedValue) {
3519       // BasePointerAddr + Offset = Alignment * Q for some integer Q.
3520       // So we can say that the maximum power of two which is a divisor of
3521       // gcd(Offset, Alignment) is an alignment.
3522 
3523       uint32_t gcd =
3524           greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), Alignment);
3525       Alignment = llvm::PowerOf2Floor(gcd);
3526     }
3527   }
3528 
3529   return Alignment;
3530 }
3531 
3532 struct AAAlignImpl : AAAlign {
3533   AAAlignImpl(const IRPosition &IRP) : AAAlign(IRP) {}
3534 
3535   /// See AbstractAttribute::initialize(...).
3536   void initialize(Attributor &A) override {
3537     SmallVector<Attribute, 4> Attrs;
3538     getAttrs({Attribute::Alignment}, Attrs);
3539     for (const Attribute &Attr : Attrs)
3540       takeKnownMaximum(Attr.getValueAsInt());
3541 
3542     if (getIRPosition().isFnInterfaceKind() &&
3543         (!getAnchorScope() ||
3544          !A.isFunctionIPOAmendable(*getAssociatedFunction())))
3545       indicatePessimisticFixpoint();
3546   }
3547 
3548   /// See AbstractAttribute::manifest(...).
3549   ChangeStatus manifest(Attributor &A) override {
3550     ChangeStatus LoadStoreChanged = ChangeStatus::UNCHANGED;
3551 
3552     // Check for users that allow alignment annotations.
3553     Value &AssociatedValue = getAssociatedValue();
3554     for (const Use &U : AssociatedValue.uses()) {
3555       if (auto *SI = dyn_cast<StoreInst>(U.getUser())) {
3556         if (SI->getPointerOperand() == &AssociatedValue)
3557           if (SI->getAlignment() < getAssumedAlign()) {
3558             STATS_DECLTRACK(AAAlign, Store,
3559                             "Number of times alignment added to a store");
3560             SI->setAlignment(Align(getAssumedAlign()));
3561             LoadStoreChanged = ChangeStatus::CHANGED;
3562           }
3563       } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) {
3564         if (LI->getPointerOperand() == &AssociatedValue)
3565           if (LI->getAlignment() < getAssumedAlign()) {
3566             LI->setAlignment(Align(getAssumedAlign()));
3567             STATS_DECLTRACK(AAAlign, Load,
3568                             "Number of times alignment added to a load");
3569             LoadStoreChanged = ChangeStatus::CHANGED;
3570           }
3571       }
3572     }
3573 
3574     ChangeStatus Changed = AAAlign::manifest(A);
3575 
3576     MaybeAlign InheritAlign =
3577         getAssociatedValue().getPointerAlignment(A.getDataLayout());
3578     if (InheritAlign.valueOrOne() >= getAssumedAlign())
3579       return LoadStoreChanged;
3580     return Changed | LoadStoreChanged;
3581   }
3582 
3583   // TODO: Provide a helper to determine the implied ABI alignment and check in
3584   //       the existing manifest method and a new one for AAAlignImpl that value
3585   //       to avoid making the alignment explicit if it did not improve.
3586 
3587   /// See AbstractAttribute::getDeducedAttributes
3588   virtual void
3589   getDeducedAttributes(LLVMContext &Ctx,
3590                        SmallVectorImpl<Attribute> &Attrs) const override {
3591     if (getAssumedAlign() > 1)
3592       Attrs.emplace_back(
3593           Attribute::getWithAlignment(Ctx, Align(getAssumedAlign())));
3594   }
3595   /// See AAFromMustBeExecutedContext
3596   bool followUse(Attributor &A, const Use *U, const Instruction *I,
3597                  AAAlign::StateType &State) {
3598     bool TrackUse = false;
3599 
3600     unsigned int KnownAlign =
3601         getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse);
3602     State.takeKnownMaximum(KnownAlign);
3603 
3604     return TrackUse;
3605   }
3606 
3607   /// See AbstractAttribute::getAsStr().
3608   const std::string getAsStr() const override {
3609     return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
3610                                 "-" + std::to_string(getAssumedAlign()) + ">")
3611                              : "unknown-align";
3612   }
3613 };
3614 
3615 /// Align attribute for a floating value.
3616 struct AAAlignFloating : AAFromMustBeExecutedContext<AAAlign, AAAlignImpl> {
3617   using Base = AAFromMustBeExecutedContext<AAAlign, AAAlignImpl>;
3618   AAAlignFloating(const IRPosition &IRP) : Base(IRP) {}
3619 
3620   /// See AbstractAttribute::updateImpl(...).
3621   ChangeStatus updateImpl(Attributor &A) override {
3622     Base::updateImpl(A);
3623 
3624     const DataLayout &DL = A.getDataLayout();
3625 
3626     auto VisitValueCB = [&](Value &V, const Instruction *,
3627                             AAAlign::StateType &T, bool Stripped) -> bool {
3628       const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V));
3629       if (!Stripped && this == &AA) {
3630         // Use only IR information if we did not strip anything.
3631         const MaybeAlign PA = V.getPointerAlignment(DL);
3632         T.takeKnownMaximum(PA ? PA->value() : 0);
3633         T.indicatePessimisticFixpoint();
3634       } else {
3635         // Use abstract attribute information.
3636         const AAAlign::StateType &DS =
3637             static_cast<const AAAlign::StateType &>(AA.getState());
3638         T ^= DS;
3639       }
3640       return T.isValidState();
3641     };
3642 
3643     StateType T;
3644     if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T,
3645                                                    VisitValueCB, getCtxI()))
3646       return indicatePessimisticFixpoint();
3647 
3648     // TODO: If we know we visited all incoming values, thus no are assumed
3649     // dead, we can take the known information from the state T.
3650     return clampStateAndIndicateChange(getState(), T);
3651   }
3652 
3653   /// See AbstractAttribute::trackStatistics()
3654   void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
3655 };
3656 
3657 /// Align attribute for function return value.
3658 struct AAAlignReturned final
3659     : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
3660   AAAlignReturned(const IRPosition &IRP)
3661       : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>(IRP) {}
3662 
3663   /// See AbstractAttribute::trackStatistics()
3664   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
3665 };
3666 
3667 /// Align attribute for function argument.
3668 struct AAAlignArgument final
3669     : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AAAlign,
3670                                                               AAAlignImpl> {
3671   using Base =
3672       AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AAAlign,
3673                                                               AAAlignImpl>;
3674   AAAlignArgument(const IRPosition &IRP) : Base(IRP) {}
3675 
3676   /// See AbstractAttribute::manifest(...).
3677   ChangeStatus manifest(Attributor &A) override {
3678     // If the associated argument is involved in a must-tail call we give up
3679     // because we would need to keep the argument alignments of caller and
3680     // callee in-sync. Just does not seem worth the trouble right now.
3681     if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
3682       return ChangeStatus::UNCHANGED;
3683     return Base::manifest(A);
3684   }
3685 
3686   /// See AbstractAttribute::trackStatistics()
3687   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
3688 };
3689 
3690 struct AAAlignCallSiteArgument final : AAAlignFloating {
3691   AAAlignCallSiteArgument(const IRPosition &IRP) : AAAlignFloating(IRP) {}
3692 
3693   /// See AbstractAttribute::manifest(...).
3694   ChangeStatus manifest(Attributor &A) override {
3695     // If the associated argument is involved in a must-tail call we give up
3696     // because we would need to keep the argument alignments of caller and
3697     // callee in-sync. Just does not seem worth the trouble right now.
3698     if (Argument *Arg = getAssociatedArgument())
3699       if (A.getInfoCache().isInvolvedInMustTailCall(*Arg))
3700         return ChangeStatus::UNCHANGED;
3701     ChangeStatus Changed = AAAlignImpl::manifest(A);
3702     MaybeAlign InheritAlign =
3703         getAssociatedValue().getPointerAlignment(A.getDataLayout());
3704     if (InheritAlign.valueOrOne() >= getAssumedAlign())
3705       Changed = ChangeStatus::UNCHANGED;
3706     return Changed;
3707   }
3708 
3709   /// See AbstractAttribute::updateImpl(Attributor &A).
3710   ChangeStatus updateImpl(Attributor &A) override {
3711     ChangeStatus Changed = AAAlignFloating::updateImpl(A);
3712     if (Argument *Arg = getAssociatedArgument()) {
3713       // We only take known information from the argument
3714       // so we do not need to track a dependence.
3715       const auto &ArgAlignAA = A.getAAFor<AAAlign>(
3716           *this, IRPosition::argument(*Arg), /* TrackDependence */ false);
3717       takeKnownMaximum(ArgAlignAA.getKnownAlign());
3718     }
3719     return Changed;
3720   }
3721 
3722   /// See AbstractAttribute::trackStatistics()
3723   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
3724 };
3725 
3726 /// Align attribute deduction for a call site return value.
3727 struct AAAlignCallSiteReturned final
3728     : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AAAlign,
3729                                                              AAAlignImpl> {
3730   using Base =
3731       AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AAAlign,
3732                                                              AAAlignImpl>;
3733   AAAlignCallSiteReturned(const IRPosition &IRP) : Base(IRP) {}
3734 
3735   /// See AbstractAttribute::initialize(...).
3736   void initialize(Attributor &A) override {
3737     Base::initialize(A);
3738     Function *F = getAssociatedFunction();
3739     if (!F)
3740       indicatePessimisticFixpoint();
3741   }
3742 
3743   /// See AbstractAttribute::trackStatistics()
3744   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); }
3745 };
3746 
3747 /// ------------------ Function No-Return Attribute ----------------------------
3748 struct AANoReturnImpl : public AANoReturn {
3749   AANoReturnImpl(const IRPosition &IRP) : AANoReturn(IRP) {}
3750 
3751   /// See AbstractAttribute::initialize(...).
3752   void initialize(Attributor &A) override {
3753     AANoReturn::initialize(A);
3754     Function *F = getAssociatedFunction();
3755     if (!F)
3756       indicatePessimisticFixpoint();
3757   }
3758 
3759   /// See AbstractAttribute::getAsStr().
3760   const std::string getAsStr() const override {
3761     return getAssumed() ? "noreturn" : "may-return";
3762   }
3763 
3764   /// See AbstractAttribute::updateImpl(Attributor &A).
3765   virtual ChangeStatus updateImpl(Attributor &A) override {
3766     auto CheckForNoReturn = [](Instruction &) { return false; };
3767     if (!A.checkForAllInstructions(CheckForNoReturn, *this,
3768                                    {(unsigned)Instruction::Ret}))
3769       return indicatePessimisticFixpoint();
3770     return ChangeStatus::UNCHANGED;
3771   }
3772 };
3773 
3774 struct AANoReturnFunction final : AANoReturnImpl {
3775   AANoReturnFunction(const IRPosition &IRP) : AANoReturnImpl(IRP) {}
3776 
3777   /// See AbstractAttribute::trackStatistics()
3778   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
3779 };
3780 
3781 /// NoReturn attribute deduction for a call sites.
3782 struct AANoReturnCallSite final : AANoReturnImpl {
3783   AANoReturnCallSite(const IRPosition &IRP) : AANoReturnImpl(IRP) {}
3784 
3785   /// See AbstractAttribute::updateImpl(...).
3786   ChangeStatus updateImpl(Attributor &A) override {
3787     // TODO: Once we have call site specific value information we can provide
3788     //       call site specific liveness information and then it makes
3789     //       sense to specialize attributes for call sites arguments instead of
3790     //       redirecting requests to the callee argument.
3791     Function *F = getAssociatedFunction();
3792     const IRPosition &FnPos = IRPosition::function(*F);
3793     auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos);
3794     return clampStateAndIndicateChange(
3795         getState(),
3796         static_cast<const AANoReturn::StateType &>(FnAA.getState()));
3797   }
3798 
3799   /// See AbstractAttribute::trackStatistics()
3800   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); }
3801 };
3802 
3803 /// ----------------------- Variable Capturing ---------------------------------
3804 
3805 /// A class to hold the state of for no-capture attributes.
3806 struct AANoCaptureImpl : public AANoCapture {
3807   AANoCaptureImpl(const IRPosition &IRP) : AANoCapture(IRP) {}
3808 
3809   /// See AbstractAttribute::initialize(...).
3810   void initialize(Attributor &A) override {
3811     if (hasAttr(getAttrKind(), /* IgnoreSubsumingPositions */ true)) {
3812       indicateOptimisticFixpoint();
3813       return;
3814     }
3815     Function *AnchorScope = getAnchorScope();
3816     if (isFnInterfaceKind() &&
3817         (!AnchorScope || !A.isFunctionIPOAmendable(*AnchorScope))) {
3818       indicatePessimisticFixpoint();
3819       return;
3820     }
3821 
3822     // You cannot "capture" null in the default address space.
3823     if (isa<ConstantPointerNull>(getAssociatedValue()) &&
3824         getAssociatedValue().getType()->getPointerAddressSpace() == 0) {
3825       indicateOptimisticFixpoint();
3826       return;
3827     }
3828 
3829     const Function *F = getArgNo() >= 0 ? getAssociatedFunction() : AnchorScope;
3830 
3831     // Check what state the associated function can actually capture.
3832     if (F)
3833       determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
3834     else
3835       indicatePessimisticFixpoint();
3836   }
3837 
3838   /// See AbstractAttribute::updateImpl(...).
3839   ChangeStatus updateImpl(Attributor &A) override;
3840 
3841   /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...).
3842   virtual void
3843   getDeducedAttributes(LLVMContext &Ctx,
3844                        SmallVectorImpl<Attribute> &Attrs) const override {
3845     if (!isAssumedNoCaptureMaybeReturned())
3846       return;
3847 
3848     if (getArgNo() >= 0) {
3849       if (isAssumedNoCapture())
3850         Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture));
3851       else if (ManifestInternal)
3852         Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned"));
3853     }
3854   }
3855 
3856   /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known
3857   /// depending on the ability of the function associated with \p IRP to capture
3858   /// state in memory and through "returning/throwing", respectively.
3859   static void determineFunctionCaptureCapabilities(const IRPosition &IRP,
3860                                                    const Function &F,
3861                                                    BitIntegerState &State) {
3862     // TODO: Once we have memory behavior attributes we should use them here.
3863 
3864     // If we know we cannot communicate or write to memory, we do not care about
3865     // ptr2int anymore.
3866     if (F.onlyReadsMemory() && F.doesNotThrow() &&
3867         F.getReturnType()->isVoidTy()) {
3868       State.addKnownBits(NO_CAPTURE);
3869       return;
3870     }
3871 
3872     // A function cannot capture state in memory if it only reads memory, it can
3873     // however return/throw state and the state might be influenced by the
3874     // pointer value, e.g., loading from a returned pointer might reveal a bit.
3875     if (F.onlyReadsMemory())
3876       State.addKnownBits(NOT_CAPTURED_IN_MEM);
3877 
3878     // A function cannot communicate state back if it does not through
3879     // exceptions and doesn not return values.
3880     if (F.doesNotThrow() && F.getReturnType()->isVoidTy())
3881       State.addKnownBits(NOT_CAPTURED_IN_RET);
3882 
3883     // Check existing "returned" attributes.
3884     int ArgNo = IRP.getArgNo();
3885     if (F.doesNotThrow() && ArgNo >= 0) {
3886       for (unsigned u = 0, e = F.arg_size(); u < e; ++u)
3887         if (F.hasParamAttribute(u, Attribute::Returned)) {
3888           if (u == unsigned(ArgNo))
3889             State.removeAssumedBits(NOT_CAPTURED_IN_RET);
3890           else if (F.onlyReadsMemory())
3891             State.addKnownBits(NO_CAPTURE);
3892           else
3893             State.addKnownBits(NOT_CAPTURED_IN_RET);
3894           break;
3895         }
3896     }
3897   }
3898 
3899   /// See AbstractState::getAsStr().
3900   const std::string getAsStr() const override {
3901     if (isKnownNoCapture())
3902       return "known not-captured";
3903     if (isAssumedNoCapture())
3904       return "assumed not-captured";
3905     if (isKnownNoCaptureMaybeReturned())
3906       return "known not-captured-maybe-returned";
3907     if (isAssumedNoCaptureMaybeReturned())
3908       return "assumed not-captured-maybe-returned";
3909     return "assumed-captured";
3910   }
3911 };
3912 
3913 /// Attributor-aware capture tracker.
3914 struct AACaptureUseTracker final : public CaptureTracker {
3915 
3916   /// Create a capture tracker that can lookup in-flight abstract attributes
3917   /// through the Attributor \p A.
3918   ///
3919   /// If a use leads to a potential capture, \p CapturedInMemory is set and the
3920   /// search is stopped. If a use leads to a return instruction,
3921   /// \p CommunicatedBack is set to true and \p CapturedInMemory is not changed.
3922   /// If a use leads to a ptr2int which may capture the value,
3923   /// \p CapturedInInteger is set. If a use is found that is currently assumed
3924   /// "no-capture-maybe-returned", the user is added to the \p PotentialCopies
3925   /// set. All values in \p PotentialCopies are later tracked as well. For every
3926   /// explored use we decrement \p RemainingUsesToExplore. Once it reaches 0,
3927   /// the search is stopped with \p CapturedInMemory and \p CapturedInInteger
3928   /// conservatively set to true.
3929   AACaptureUseTracker(Attributor &A, AANoCapture &NoCaptureAA,
3930                       const AAIsDead &IsDeadAA, AANoCapture::StateType &State,
3931                       SmallVectorImpl<const Value *> &PotentialCopies,
3932                       unsigned &RemainingUsesToExplore)
3933       : A(A), NoCaptureAA(NoCaptureAA), IsDeadAA(IsDeadAA), State(State),
3934         PotentialCopies(PotentialCopies),
3935         RemainingUsesToExplore(RemainingUsesToExplore) {}
3936 
3937   /// Determine if \p V maybe captured. *Also updates the state!*
3938   bool valueMayBeCaptured(const Value *V) {
3939     if (V->getType()->isPointerTy()) {
3940       PointerMayBeCaptured(V, this);
3941     } else {
3942       State.indicatePessimisticFixpoint();
3943     }
3944     return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
3945   }
3946 
3947   /// See CaptureTracker::tooManyUses().
3948   void tooManyUses() override {
3949     State.removeAssumedBits(AANoCapture::NO_CAPTURE);
3950   }
3951 
3952   bool isDereferenceableOrNull(Value *O, const DataLayout &DL) override {
3953     if (CaptureTracker::isDereferenceableOrNull(O, DL))
3954       return true;
3955     const auto &DerefAA = A.getAAFor<AADereferenceable>(
3956         NoCaptureAA, IRPosition::value(*O), /* TrackDependence */ true,
3957         DepClassTy::OPTIONAL);
3958     return DerefAA.getAssumedDereferenceableBytes();
3959   }
3960 
3961   /// See CaptureTracker::captured(...).
3962   bool captured(const Use *U) override {
3963     Instruction *UInst = cast<Instruction>(U->getUser());
3964     LLVM_DEBUG(dbgs() << "Check use: " << *U->get() << " in " << *UInst
3965                       << "\n");
3966 
3967     // Because we may reuse the tracker multiple times we keep track of the
3968     // number of explored uses ourselves as well.
3969     if (RemainingUsesToExplore-- == 0) {
3970       LLVM_DEBUG(dbgs() << " - too many uses to explore!\n");
3971       return isCapturedIn(/* Memory */ true, /* Integer */ true,
3972                           /* Return */ true);
3973     }
3974 
3975     // Deal with ptr2int by following uses.
3976     if (isa<PtrToIntInst>(UInst)) {
3977       LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n");
3978       return valueMayBeCaptured(UInst);
3979     }
3980 
3981     // Explicitly catch return instructions.
3982     if (isa<ReturnInst>(UInst))
3983       return isCapturedIn(/* Memory */ false, /* Integer */ false,
3984                           /* Return */ true);
3985 
3986     // For now we only use special logic for call sites. However, the tracker
3987     // itself knows about a lot of other non-capturing cases already.
3988     CallSite CS(UInst);
3989     if (!CS || !CS.isArgOperand(U))
3990       return isCapturedIn(/* Memory */ true, /* Integer */ true,
3991                           /* Return */ true);
3992 
3993     unsigned ArgNo = CS.getArgumentNo(U);
3994     const IRPosition &CSArgPos = IRPosition::callsite_argument(CS, ArgNo);
3995     // If we have a abstract no-capture attribute for the argument we can use
3996     // it to justify a non-capture attribute here. This allows recursion!
3997     auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(NoCaptureAA, CSArgPos);
3998     if (ArgNoCaptureAA.isAssumedNoCapture())
3999       return isCapturedIn(/* Memory */ false, /* Integer */ false,
4000                           /* Return */ false);
4001     if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
4002       addPotentialCopy(CS);
4003       return isCapturedIn(/* Memory */ false, /* Integer */ false,
4004                           /* Return */ false);
4005     }
4006 
4007     // Lastly, we could not find a reason no-capture can be assumed so we don't.
4008     return isCapturedIn(/* Memory */ true, /* Integer */ true,
4009                         /* Return */ true);
4010   }
4011 
4012   /// Register \p CS as potential copy of the value we are checking.
4013   void addPotentialCopy(CallSite CS) {
4014     PotentialCopies.push_back(CS.getInstruction());
4015   }
4016 
4017   /// See CaptureTracker::shouldExplore(...).
4018   bool shouldExplore(const Use *U) override {
4019     // Check liveness and ignore droppable users.
4020     return !U->getUser()->isDroppable() &&
4021            !A.isAssumedDead(*U, &NoCaptureAA, &IsDeadAA);
4022   }
4023 
4024   /// Update the state according to \p CapturedInMem, \p CapturedInInt, and
4025   /// \p CapturedInRet, then return the appropriate value for use in the
4026   /// CaptureTracker::captured() interface.
4027   bool isCapturedIn(bool CapturedInMem, bool CapturedInInt,
4028                     bool CapturedInRet) {
4029     LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int "
4030                       << CapturedInInt << "|Ret " << CapturedInRet << "]\n");
4031     if (CapturedInMem)
4032       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM);
4033     if (CapturedInInt)
4034       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT);
4035     if (CapturedInRet)
4036       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET);
4037     return !State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
4038   }
4039 
4040 private:
4041   /// The attributor providing in-flight abstract attributes.
4042   Attributor &A;
4043 
4044   /// The abstract attribute currently updated.
4045   AANoCapture &NoCaptureAA;
4046 
4047   /// The abstract liveness state.
4048   const AAIsDead &IsDeadAA;
4049 
4050   /// The state currently updated.
4051   AANoCapture::StateType &State;
4052 
4053   /// Set of potential copies of the tracked value.
4054   SmallVectorImpl<const Value *> &PotentialCopies;
4055 
4056   /// Global counter to limit the number of explored uses.
4057   unsigned &RemainingUsesToExplore;
4058 };
4059 
4060 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) {
4061   const IRPosition &IRP = getIRPosition();
4062   const Value *V =
4063       getArgNo() >= 0 ? IRP.getAssociatedArgument() : &IRP.getAssociatedValue();
4064   if (!V)
4065     return indicatePessimisticFixpoint();
4066 
4067   const Function *F =
4068       getArgNo() >= 0 ? IRP.getAssociatedFunction() : IRP.getAnchorScope();
4069   assert(F && "Expected a function!");
4070   const IRPosition &FnPos = IRPosition::function(*F);
4071   const auto &IsDeadAA =
4072       A.getAAFor<AAIsDead>(*this, FnPos, /* TrackDependence */ false);
4073 
4074   AANoCapture::StateType T;
4075 
4076   // Readonly means we cannot capture through memory.
4077   const auto &FnMemAA = A.getAAFor<AAMemoryBehavior>(
4078       *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
4079   if (FnMemAA.isAssumedReadOnly()) {
4080     T.addKnownBits(NOT_CAPTURED_IN_MEM);
4081     if (FnMemAA.isKnownReadOnly())
4082       addKnownBits(NOT_CAPTURED_IN_MEM);
4083   }
4084 
4085   // Make sure all returned values are different than the underlying value.
4086   // TODO: we could do this in a more sophisticated way inside
4087   //       AAReturnedValues, e.g., track all values that escape through returns
4088   //       directly somehow.
4089   auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) {
4090     bool SeenConstant = false;
4091     for (auto &It : RVAA.returned_values()) {
4092       if (isa<Constant>(It.first)) {
4093         if (SeenConstant)
4094           return false;
4095         SeenConstant = true;
4096       } else if (!isa<Argument>(It.first) ||
4097                  It.first == getAssociatedArgument())
4098         return false;
4099     }
4100     return true;
4101   };
4102 
4103   const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(
4104       *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
4105   if (NoUnwindAA.isAssumedNoUnwind()) {
4106     bool IsVoidTy = F->getReturnType()->isVoidTy();
4107     const AAReturnedValues *RVAA =
4108         IsVoidTy ? nullptr
4109                  : &A.getAAFor<AAReturnedValues>(*this, FnPos,
4110                                                  /* TrackDependence */ true,
4111                                                  DepClassTy::OPTIONAL);
4112     if (IsVoidTy || CheckReturnedArgs(*RVAA)) {
4113       T.addKnownBits(NOT_CAPTURED_IN_RET);
4114       if (T.isKnown(NOT_CAPTURED_IN_MEM))
4115         return ChangeStatus::UNCHANGED;
4116       if (NoUnwindAA.isKnownNoUnwind() &&
4117           (IsVoidTy || RVAA->getState().isAtFixpoint())) {
4118         addKnownBits(NOT_CAPTURED_IN_RET);
4119         if (isKnown(NOT_CAPTURED_IN_MEM))
4120           return indicateOptimisticFixpoint();
4121       }
4122     }
4123   }
4124 
4125   // Use the CaptureTracker interface and logic with the specialized tracker,
4126   // defined in AACaptureUseTracker, that can look at in-flight abstract
4127   // attributes and directly updates the assumed state.
4128   SmallVector<const Value *, 4> PotentialCopies;
4129   unsigned RemainingUsesToExplore = DefaultMaxUsesToExplore;
4130   AACaptureUseTracker Tracker(A, *this, IsDeadAA, T, PotentialCopies,
4131                               RemainingUsesToExplore);
4132 
4133   // Check all potential copies of the associated value until we can assume
4134   // none will be captured or we have to assume at least one might be.
4135   unsigned Idx = 0;
4136   PotentialCopies.push_back(V);
4137   while (T.isAssumed(NO_CAPTURE_MAYBE_RETURNED) && Idx < PotentialCopies.size())
4138     Tracker.valueMayBeCaptured(PotentialCopies[Idx++]);
4139 
4140   AANoCapture::StateType &S = getState();
4141   auto Assumed = S.getAssumed();
4142   S.intersectAssumedBits(T.getAssumed());
4143   if (!isAssumedNoCaptureMaybeReturned())
4144     return indicatePessimisticFixpoint();
4145   return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
4146                                    : ChangeStatus::CHANGED;
4147 }
4148 
4149 /// NoCapture attribute for function arguments.
4150 struct AANoCaptureArgument final : AANoCaptureImpl {
4151   AANoCaptureArgument(const IRPosition &IRP) : AANoCaptureImpl(IRP) {}
4152 
4153   /// See AbstractAttribute::trackStatistics()
4154   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) }
4155 };
4156 
4157 /// NoCapture attribute for call site arguments.
4158 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
4159   AANoCaptureCallSiteArgument(const IRPosition &IRP) : AANoCaptureImpl(IRP) {}
4160 
4161   /// See AbstractAttribute::initialize(...).
4162   void initialize(Attributor &A) override {
4163     if (Argument *Arg = getAssociatedArgument())
4164       if (Arg->hasByValAttr())
4165         indicateOptimisticFixpoint();
4166     AANoCaptureImpl::initialize(A);
4167   }
4168 
4169   /// See AbstractAttribute::updateImpl(...).
4170   ChangeStatus updateImpl(Attributor &A) override {
4171     // TODO: Once we have call site specific value information we can provide
4172     //       call site specific liveness information and then it makes
4173     //       sense to specialize attributes for call sites arguments instead of
4174     //       redirecting requests to the callee argument.
4175     Argument *Arg = getAssociatedArgument();
4176     if (!Arg)
4177       return indicatePessimisticFixpoint();
4178     const IRPosition &ArgPos = IRPosition::argument(*Arg);
4179     auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos);
4180     return clampStateAndIndicateChange(
4181         getState(),
4182         static_cast<const AANoCapture::StateType &>(ArgAA.getState()));
4183   }
4184 
4185   /// See AbstractAttribute::trackStatistics()
4186   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)};
4187 };
4188 
4189 /// NoCapture attribute for floating values.
4190 struct AANoCaptureFloating final : AANoCaptureImpl {
4191   AANoCaptureFloating(const IRPosition &IRP) : AANoCaptureImpl(IRP) {}
4192 
4193   /// See AbstractAttribute::trackStatistics()
4194   void trackStatistics() const override {
4195     STATS_DECLTRACK_FLOATING_ATTR(nocapture)
4196   }
4197 };
4198 
4199 /// NoCapture attribute for function return value.
4200 struct AANoCaptureReturned final : AANoCaptureImpl {
4201   AANoCaptureReturned(const IRPosition &IRP) : AANoCaptureImpl(IRP) {
4202     llvm_unreachable("NoCapture is not applicable to function returns!");
4203   }
4204 
4205   /// See AbstractAttribute::initialize(...).
4206   void initialize(Attributor &A) override {
4207     llvm_unreachable("NoCapture is not applicable to function returns!");
4208   }
4209 
4210   /// See AbstractAttribute::updateImpl(...).
4211   ChangeStatus updateImpl(Attributor &A) override {
4212     llvm_unreachable("NoCapture is not applicable to function returns!");
4213   }
4214 
4215   /// See AbstractAttribute::trackStatistics()
4216   void trackStatistics() const override {}
4217 };
4218 
4219 /// NoCapture attribute deduction for a call site return value.
4220 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
4221   AANoCaptureCallSiteReturned(const IRPosition &IRP) : AANoCaptureImpl(IRP) {}
4222 
4223   /// See AbstractAttribute::trackStatistics()
4224   void trackStatistics() const override {
4225     STATS_DECLTRACK_CSRET_ATTR(nocapture)
4226   }
4227 };
4228 
4229 /// ------------------ Value Simplify Attribute ----------------------------
4230 struct AAValueSimplifyImpl : AAValueSimplify {
4231   AAValueSimplifyImpl(const IRPosition &IRP) : AAValueSimplify(IRP) {}
4232 
4233   /// See AbstractAttribute::initialize(...).
4234   void initialize(Attributor &A) override {
4235     if (getAssociatedValue().getType()->isVoidTy())
4236       indicatePessimisticFixpoint();
4237   }
4238 
4239   /// See AbstractAttribute::getAsStr().
4240   const std::string getAsStr() const override {
4241     return getAssumed() ? (getKnown() ? "simplified" : "maybe-simple")
4242                         : "not-simple";
4243   }
4244 
4245   /// See AbstractAttribute::trackStatistics()
4246   void trackStatistics() const override {}
4247 
4248   /// See AAValueSimplify::getAssumedSimplifiedValue()
4249   Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override {
4250     if (!getAssumed())
4251       return const_cast<Value *>(&getAssociatedValue());
4252     return SimplifiedAssociatedValue;
4253   }
4254 
4255   /// Helper function for querying AAValueSimplify and updating candicate.
4256   /// \param QueryingValue Value trying to unify with SimplifiedValue
4257   /// \param AccumulatedSimplifiedValue Current simplification result.
4258   static bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA,
4259                              Value &QueryingValue,
4260                              Optional<Value *> &AccumulatedSimplifiedValue) {
4261     // FIXME: Add a typecast support.
4262 
4263     auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>(
4264         QueryingAA, IRPosition::value(QueryingValue));
4265 
4266     Optional<Value *> QueryingValueSimplified =
4267         ValueSimplifyAA.getAssumedSimplifiedValue(A);
4268 
4269     if (!QueryingValueSimplified.hasValue())
4270       return true;
4271 
4272     if (!QueryingValueSimplified.getValue())
4273       return false;
4274 
4275     Value &QueryingValueSimplifiedUnwrapped =
4276         *QueryingValueSimplified.getValue();
4277 
4278     if (AccumulatedSimplifiedValue.hasValue() &&
4279         !isa<UndefValue>(AccumulatedSimplifiedValue.getValue()) &&
4280         !isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
4281       return AccumulatedSimplifiedValue == QueryingValueSimplified;
4282     if (AccumulatedSimplifiedValue.hasValue() &&
4283         isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
4284       return true;
4285 
4286     LLVM_DEBUG(dbgs() << "[ValueSimplify] " << QueryingValue
4287                       << " is assumed to be "
4288                       << QueryingValueSimplifiedUnwrapped << "\n");
4289 
4290     AccumulatedSimplifiedValue = QueryingValueSimplified;
4291     return true;
4292   }
4293 
4294   bool askSimplifiedValueForAAValueConstantRange(Attributor &A) {
4295     if (!getAssociatedValue().getType()->isIntegerTy())
4296       return false;
4297 
4298     const auto &ValueConstantRangeAA =
4299         A.getAAFor<AAValueConstantRange>(*this, getIRPosition());
4300 
4301     Optional<ConstantInt *> COpt =
4302         ValueConstantRangeAA.getAssumedConstantInt(A);
4303     if (COpt.hasValue()) {
4304       if (auto *C = COpt.getValue())
4305         SimplifiedAssociatedValue = C;
4306       else
4307         return false;
4308     } else {
4309       SimplifiedAssociatedValue = llvm::None;
4310     }
4311     return true;
4312   }
4313 
4314   /// See AbstractAttribute::manifest(...).
4315   ChangeStatus manifest(Attributor &A) override {
4316     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4317 
4318     if (SimplifiedAssociatedValue.hasValue() &&
4319         !SimplifiedAssociatedValue.getValue())
4320       return Changed;
4321 
4322     Value &V = getAssociatedValue();
4323     auto *C = SimplifiedAssociatedValue.hasValue()
4324                   ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
4325                   : UndefValue::get(V.getType());
4326     if (C) {
4327       // We can replace the AssociatedValue with the constant.
4328       if (!V.user_empty() && &V != C && V.getType() == C->getType()) {
4329         LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *C
4330                           << " :: " << *this << "\n");
4331         if (A.changeValueAfterManifest(V, *C))
4332           Changed = ChangeStatus::CHANGED;
4333       }
4334     }
4335 
4336     return Changed | AAValueSimplify::manifest(A);
4337   }
4338 
4339   /// See AbstractState::indicatePessimisticFixpoint(...).
4340   ChangeStatus indicatePessimisticFixpoint() override {
4341     // NOTE: Associated value will be returned in a pessimistic fixpoint and is
4342     // regarded as known. That's why`indicateOptimisticFixpoint` is called.
4343     SimplifiedAssociatedValue = &getAssociatedValue();
4344     indicateOptimisticFixpoint();
4345     return ChangeStatus::CHANGED;
4346   }
4347 
4348 protected:
4349   // An assumed simplified value. Initially, it is set to Optional::None, which
4350   // means that the value is not clear under current assumption. If in the
4351   // pessimistic state, getAssumedSimplifiedValue doesn't return this value but
4352   // returns orignal associated value.
4353   Optional<Value *> SimplifiedAssociatedValue;
4354 };
4355 
4356 struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
4357   AAValueSimplifyArgument(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {}
4358 
4359   void initialize(Attributor &A) override {
4360     AAValueSimplifyImpl::initialize(A);
4361     if (!getAnchorScope() || getAnchorScope()->isDeclaration())
4362       indicatePessimisticFixpoint();
4363     if (hasAttr({Attribute::InAlloca, Attribute::StructRet, Attribute::Nest},
4364                 /* IgnoreSubsumingPositions */ true))
4365       indicatePessimisticFixpoint();
4366 
4367     // FIXME: This is a hack to prevent us from propagating function poiner in
4368     // the new pass manager CGSCC pass as it creates call edges the
4369     // CallGraphUpdater cannot handle yet.
4370     Value &V = getAssociatedValue();
4371     if (V.getType()->isPointerTy() &&
4372         V.getType()->getPointerElementType()->isFunctionTy() &&
4373         !A.isModulePass())
4374       indicatePessimisticFixpoint();
4375   }
4376 
4377   /// See AbstractAttribute::updateImpl(...).
4378   ChangeStatus updateImpl(Attributor &A) override {
4379     // Byval is only replacable if it is readonly otherwise we would write into
4380     // the replaced value and not the copy that byval creates implicitly.
4381     Argument *Arg = getAssociatedArgument();
4382     if (Arg->hasByValAttr()) {
4383       // TODO: We probably need to verify synchronization is not an issue, e.g.,
4384       //       there is no race by not copying a constant byval.
4385       const auto &MemAA = A.getAAFor<AAMemoryBehavior>(*this, getIRPosition());
4386       if (!MemAA.isAssumedReadOnly())
4387         return indicatePessimisticFixpoint();
4388     }
4389 
4390     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4391 
4392     auto PredForCallSite = [&](AbstractCallSite ACS) {
4393       const IRPosition &ACSArgPos =
4394           IRPosition::callsite_argument(ACS, getArgNo());
4395       // Check if a coresponding argument was found or if it is on not
4396       // associated (which can happen for callback calls).
4397       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
4398         return false;
4399 
4400       // We can only propagate thread independent values through callbacks.
4401       // This is different to direct/indirect call sites because for them we
4402       // know the thread executing the caller and callee is the same. For
4403       // callbacks this is not guaranteed, thus a thread dependent value could
4404       // be different for the caller and callee, making it invalid to propagate.
4405       Value &ArgOp = ACSArgPos.getAssociatedValue();
4406       if (ACS.isCallbackCall())
4407         if (auto *C = dyn_cast<Constant>(&ArgOp))
4408           if (C->isThreadDependent())
4409             return false;
4410       return checkAndUpdate(A, *this, ArgOp, SimplifiedAssociatedValue);
4411     };
4412 
4413     bool AllCallSitesKnown;
4414     if (!A.checkForAllCallSites(PredForCallSite, *this, true,
4415                                 AllCallSitesKnown))
4416       if (!askSimplifiedValueForAAValueConstantRange(A))
4417         return indicatePessimisticFixpoint();
4418 
4419     // If a candicate was found in this update, return CHANGED.
4420     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4421                ? ChangeStatus::UNCHANGED
4422                : ChangeStatus ::CHANGED;
4423   }
4424 
4425   /// See AbstractAttribute::trackStatistics()
4426   void trackStatistics() const override {
4427     STATS_DECLTRACK_ARG_ATTR(value_simplify)
4428   }
4429 };
4430 
4431 struct AAValueSimplifyReturned : AAValueSimplifyImpl {
4432   AAValueSimplifyReturned(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {}
4433 
4434   /// See AbstractAttribute::updateImpl(...).
4435   ChangeStatus updateImpl(Attributor &A) override {
4436     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4437 
4438     auto PredForReturned = [&](Value &V) {
4439       return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue);
4440     };
4441 
4442     if (!A.checkForAllReturnedValues(PredForReturned, *this))
4443       if (!askSimplifiedValueForAAValueConstantRange(A))
4444         return indicatePessimisticFixpoint();
4445 
4446     // If a candicate was found in this update, return CHANGED.
4447     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4448                ? ChangeStatus::UNCHANGED
4449                : ChangeStatus ::CHANGED;
4450   }
4451 
4452   ChangeStatus manifest(Attributor &A) override {
4453     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4454 
4455     if (SimplifiedAssociatedValue.hasValue() &&
4456         !SimplifiedAssociatedValue.getValue())
4457       return Changed;
4458 
4459     Value &V = getAssociatedValue();
4460     auto *C = SimplifiedAssociatedValue.hasValue()
4461                   ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
4462                   : UndefValue::get(V.getType());
4463     if (C) {
4464       auto PredForReturned =
4465           [&](Value &V, const SmallSetVector<ReturnInst *, 4> &RetInsts) {
4466             // We can replace the AssociatedValue with the constant.
4467             if (&V == C || V.getType() != C->getType() || isa<UndefValue>(V))
4468               return true;
4469 
4470             for (ReturnInst *RI : RetInsts) {
4471               if (RI->getFunction() != getAnchorScope())
4472                 continue;
4473               LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *C
4474                                 << " in " << *RI << " :: " << *this << "\n");
4475               if (A.changeUseAfterManifest(RI->getOperandUse(0), *C))
4476                 Changed = ChangeStatus::CHANGED;
4477             }
4478             return true;
4479           };
4480       A.checkForAllReturnedValuesAndReturnInsts(PredForReturned, *this);
4481     }
4482 
4483     return Changed | AAValueSimplify::manifest(A);
4484   }
4485 
4486   /// See AbstractAttribute::trackStatistics()
4487   void trackStatistics() const override {
4488     STATS_DECLTRACK_FNRET_ATTR(value_simplify)
4489   }
4490 };
4491 
4492 struct AAValueSimplifyFloating : AAValueSimplifyImpl {
4493   AAValueSimplifyFloating(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {}
4494 
4495   /// See AbstractAttribute::initialize(...).
4496   void initialize(Attributor &A) override {
4497     // FIXME: This might have exposed a SCC iterator update bug in the old PM.
4498     //        Needs investigation.
4499     // AAValueSimplifyImpl::initialize(A);
4500     Value &V = getAnchorValue();
4501 
4502     // TODO: add other stuffs
4503     if (isa<Constant>(V))
4504       indicatePessimisticFixpoint();
4505   }
4506 
4507   /// See AbstractAttribute::updateImpl(...).
4508   ChangeStatus updateImpl(Attributor &A) override {
4509     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4510 
4511     auto VisitValueCB = [&](Value &V, const Instruction *CtxI, bool &,
4512                             bool Stripped) -> bool {
4513       auto &AA = A.getAAFor<AAValueSimplify>(*this, IRPosition::value(V));
4514       if (!Stripped && this == &AA) {
4515         // TODO: Look the instruction and check recursively.
4516 
4517         LLVM_DEBUG(dbgs() << "[ValueSimplify] Can't be stripped more : " << V
4518                           << "\n");
4519         return false;
4520       }
4521       return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue);
4522     };
4523 
4524     bool Dummy = false;
4525     if (!genericValueTraversal<AAValueSimplify, bool>(
4526             A, getIRPosition(), *this, Dummy, VisitValueCB, getCtxI()))
4527       if (!askSimplifiedValueForAAValueConstantRange(A))
4528         return indicatePessimisticFixpoint();
4529 
4530     // If a candicate was found in this update, return CHANGED.
4531 
4532     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4533                ? ChangeStatus::UNCHANGED
4534                : ChangeStatus ::CHANGED;
4535   }
4536 
4537   /// See AbstractAttribute::trackStatistics()
4538   void trackStatistics() const override {
4539     STATS_DECLTRACK_FLOATING_ATTR(value_simplify)
4540   }
4541 };
4542 
4543 struct AAValueSimplifyFunction : AAValueSimplifyImpl {
4544   AAValueSimplifyFunction(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {}
4545 
4546   /// See AbstractAttribute::initialize(...).
4547   void initialize(Attributor &A) override {
4548     SimplifiedAssociatedValue = &getAnchorValue();
4549     indicateOptimisticFixpoint();
4550   }
4551   /// See AbstractAttribute::initialize(...).
4552   ChangeStatus updateImpl(Attributor &A) override {
4553     llvm_unreachable(
4554         "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
4555   }
4556   /// See AbstractAttribute::trackStatistics()
4557   void trackStatistics() const override {
4558     STATS_DECLTRACK_FN_ATTR(value_simplify)
4559   }
4560 };
4561 
4562 struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
4563   AAValueSimplifyCallSite(const IRPosition &IRP)
4564       : AAValueSimplifyFunction(IRP) {}
4565   /// See AbstractAttribute::trackStatistics()
4566   void trackStatistics() const override {
4567     STATS_DECLTRACK_CS_ATTR(value_simplify)
4568   }
4569 };
4570 
4571 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyReturned {
4572   AAValueSimplifyCallSiteReturned(const IRPosition &IRP)
4573       : AAValueSimplifyReturned(IRP) {}
4574 
4575   /// See AbstractAttribute::manifest(...).
4576   ChangeStatus manifest(Attributor &A) override {
4577     return AAValueSimplifyImpl::manifest(A);
4578   }
4579 
4580   void trackStatistics() const override {
4581     STATS_DECLTRACK_CSRET_ATTR(value_simplify)
4582   }
4583 };
4584 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
4585   AAValueSimplifyCallSiteArgument(const IRPosition &IRP)
4586       : AAValueSimplifyFloating(IRP) {}
4587 
4588   void trackStatistics() const override {
4589     STATS_DECLTRACK_CSARG_ATTR(value_simplify)
4590   }
4591 };
4592 
4593 /// ----------------------- Heap-To-Stack Conversion ---------------------------
4594 struct AAHeapToStackImpl : public AAHeapToStack {
4595   AAHeapToStackImpl(const IRPosition &IRP) : AAHeapToStack(IRP) {}
4596 
4597   const std::string getAsStr() const override {
4598     return "[H2S] Mallocs: " + std::to_string(MallocCalls.size());
4599   }
4600 
4601   ChangeStatus manifest(Attributor &A) override {
4602     assert(getState().isValidState() &&
4603            "Attempted to manifest an invalid state!");
4604 
4605     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
4606     Function *F = getAnchorScope();
4607     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
4608 
4609     for (Instruction *MallocCall : MallocCalls) {
4610       // This malloc cannot be replaced.
4611       if (BadMallocCalls.count(MallocCall))
4612         continue;
4613 
4614       for (Instruction *FreeCall : FreesForMalloc[MallocCall]) {
4615         LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n");
4616         A.deleteAfterManifest(*FreeCall);
4617         HasChanged = ChangeStatus::CHANGED;
4618       }
4619 
4620       LLVM_DEBUG(dbgs() << "H2S: Removing malloc call: " << *MallocCall
4621                         << "\n");
4622 
4623       MaybeAlign Alignment;
4624       Constant *Size;
4625       if (isCallocLikeFn(MallocCall, TLI)) {
4626         auto *Num = cast<ConstantInt>(MallocCall->getOperand(0));
4627         auto *SizeT = cast<ConstantInt>(MallocCall->getOperand(1));
4628         APInt TotalSize = SizeT->getValue() * Num->getValue();
4629         Size =
4630             ConstantInt::get(MallocCall->getOperand(0)->getType(), TotalSize);
4631       } else if (isAlignedAllocLikeFn(MallocCall, TLI)) {
4632         Size = cast<ConstantInt>(MallocCall->getOperand(1));
4633         Alignment = MaybeAlign(cast<ConstantInt>(MallocCall->getOperand(0))
4634                                    ->getValue()
4635                                    .getZExtValue());
4636       } else {
4637         Size = cast<ConstantInt>(MallocCall->getOperand(0));
4638       }
4639 
4640       unsigned AS = cast<PointerType>(MallocCall->getType())->getAddressSpace();
4641       Instruction *AI =
4642           new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment,
4643                          "", MallocCall->getNextNode());
4644 
4645       if (AI->getType() != MallocCall->getType())
4646         AI = new BitCastInst(AI, MallocCall->getType(), "malloc_bc",
4647                              AI->getNextNode());
4648 
4649       A.changeValueAfterManifest(*MallocCall, *AI);
4650 
4651       if (auto *II = dyn_cast<InvokeInst>(MallocCall)) {
4652         auto *NBB = II->getNormalDest();
4653         BranchInst::Create(NBB, MallocCall->getParent());
4654         A.deleteAfterManifest(*MallocCall);
4655       } else {
4656         A.deleteAfterManifest(*MallocCall);
4657       }
4658 
4659       // Zero out the allocated memory if it was a calloc.
4660       if (isCallocLikeFn(MallocCall, TLI)) {
4661         auto *BI = new BitCastInst(AI, MallocCall->getType(), "calloc_bc",
4662                                    AI->getNextNode());
4663         Value *Ops[] = {
4664             BI, ConstantInt::get(F->getContext(), APInt(8, 0, false)), Size,
4665             ConstantInt::get(Type::getInt1Ty(F->getContext()), false)};
4666 
4667         Type *Tys[] = {BI->getType(), MallocCall->getOperand(0)->getType()};
4668         Module *M = F->getParent();
4669         Function *Fn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
4670         CallInst::Create(Fn, Ops, "", BI->getNextNode());
4671       }
4672       HasChanged = ChangeStatus::CHANGED;
4673     }
4674 
4675     return HasChanged;
4676   }
4677 
4678   /// Collection of all malloc calls in a function.
4679   SmallSetVector<Instruction *, 4> MallocCalls;
4680 
4681   /// Collection of malloc calls that cannot be converted.
4682   DenseSet<const Instruction *> BadMallocCalls;
4683 
4684   /// A map for each malloc call to the set of associated free calls.
4685   DenseMap<Instruction *, SmallPtrSet<Instruction *, 4>> FreesForMalloc;
4686 
4687   ChangeStatus updateImpl(Attributor &A) override;
4688 };
4689 
4690 ChangeStatus AAHeapToStackImpl::updateImpl(Attributor &A) {
4691   const Function *F = getAnchorScope();
4692   const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
4693 
4694   MustBeExecutedContextExplorer &Explorer =
4695       A.getInfoCache().getMustBeExecutedContextExplorer();
4696 
4697   auto FreeCheck = [&](Instruction &I) {
4698     const auto &Frees = FreesForMalloc.lookup(&I);
4699     if (Frees.size() != 1)
4700       return false;
4701     Instruction *UniqueFree = *Frees.begin();
4702     return Explorer.findInContextOf(UniqueFree, I.getNextNode());
4703   };
4704 
4705   auto UsesCheck = [&](Instruction &I) {
4706     bool ValidUsesOnly = true;
4707     bool MustUse = true;
4708     auto Pred = [&](const Use &U, bool &Follow) -> bool {
4709       Instruction *UserI = cast<Instruction>(U.getUser());
4710       if (isa<LoadInst>(UserI))
4711         return true;
4712       if (auto *SI = dyn_cast<StoreInst>(UserI)) {
4713         if (SI->getValueOperand() == U.get()) {
4714           LLVM_DEBUG(dbgs()
4715                      << "[H2S] escaping store to memory: " << *UserI << "\n");
4716           ValidUsesOnly = false;
4717         } else {
4718           // A store into the malloc'ed memory is fine.
4719         }
4720         return true;
4721       }
4722       if (auto *CB = dyn_cast<CallBase>(UserI)) {
4723         if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd())
4724           return true;
4725         // Record malloc.
4726         if (isFreeCall(UserI, TLI)) {
4727           if (MustUse) {
4728             FreesForMalloc[&I].insert(UserI);
4729           } else {
4730             LLVM_DEBUG(dbgs() << "[H2S] free potentially on different mallocs: "
4731                               << *UserI << "\n");
4732             ValidUsesOnly = false;
4733           }
4734           return true;
4735         }
4736 
4737         unsigned ArgNo = CB->getArgOperandNo(&U);
4738 
4739         const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
4740             *this, IRPosition::callsite_argument(*CB, ArgNo));
4741 
4742         // If a callsite argument use is nofree, we are fine.
4743         const auto &ArgNoFreeAA = A.getAAFor<AANoFree>(
4744             *this, IRPosition::callsite_argument(*CB, ArgNo));
4745 
4746         if (!NoCaptureAA.isAssumedNoCapture() ||
4747             !ArgNoFreeAA.isAssumedNoFree()) {
4748           LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n");
4749           ValidUsesOnly = false;
4750         }
4751         return true;
4752       }
4753 
4754       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
4755           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
4756         MustUse &= !(isa<PHINode>(UserI) || isa<SelectInst>(UserI));
4757         Follow = true;
4758         return true;
4759       }
4760       // Unknown user for which we can not track uses further (in a way that
4761       // makes sense).
4762       LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n");
4763       ValidUsesOnly = false;
4764       return true;
4765     };
4766     A.checkForAllUses(Pred, *this, I);
4767     return ValidUsesOnly;
4768   };
4769 
4770   auto MallocCallocCheck = [&](Instruction &I) {
4771     if (BadMallocCalls.count(&I))
4772       return true;
4773 
4774     bool IsMalloc = isMallocLikeFn(&I, TLI);
4775     bool IsAlignedAllocLike = isAlignedAllocLikeFn(&I, TLI);
4776     bool IsCalloc = !IsMalloc && isCallocLikeFn(&I, TLI);
4777     if (!IsMalloc && !IsAlignedAllocLike && !IsCalloc) {
4778       BadMallocCalls.insert(&I);
4779       return true;
4780     }
4781 
4782     if (IsMalloc) {
4783       if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(0)))
4784         if (Size->getValue().ule(MaxHeapToStackSize))
4785           if (UsesCheck(I) || FreeCheck(I)) {
4786             MallocCalls.insert(&I);
4787             return true;
4788           }
4789     } else if (IsAlignedAllocLike && isa<ConstantInt>(I.getOperand(0))) {
4790       // Only if the alignment and sizes are constant.
4791       if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1)))
4792         if (Size->getValue().ule(MaxHeapToStackSize))
4793           if (UsesCheck(I) || FreeCheck(I)) {
4794             MallocCalls.insert(&I);
4795             return true;
4796           }
4797     } else if (IsCalloc) {
4798       bool Overflow = false;
4799       if (auto *Num = dyn_cast<ConstantInt>(I.getOperand(0)))
4800         if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1)))
4801           if ((Size->getValue().umul_ov(Num->getValue(), Overflow))
4802                   .ule(MaxHeapToStackSize))
4803             if (!Overflow && (UsesCheck(I) || FreeCheck(I))) {
4804               MallocCalls.insert(&I);
4805               return true;
4806             }
4807     }
4808 
4809     BadMallocCalls.insert(&I);
4810     return true;
4811   };
4812 
4813   size_t NumBadMallocs = BadMallocCalls.size();
4814 
4815   A.checkForAllCallLikeInstructions(MallocCallocCheck, *this);
4816 
4817   if (NumBadMallocs != BadMallocCalls.size())
4818     return ChangeStatus::CHANGED;
4819 
4820   return ChangeStatus::UNCHANGED;
4821 }
4822 
4823 struct AAHeapToStackFunction final : public AAHeapToStackImpl {
4824   AAHeapToStackFunction(const IRPosition &IRP) : AAHeapToStackImpl(IRP) {}
4825 
4826   /// See AbstractAttribute::trackStatistics().
4827   void trackStatistics() const override {
4828     STATS_DECL(
4829         MallocCalls, Function,
4830         "Number of malloc/calloc/aligned_alloc calls converted to allocas");
4831     for (auto *C : MallocCalls)
4832       if (!BadMallocCalls.count(C))
4833         ++BUILD_STAT_NAME(MallocCalls, Function);
4834   }
4835 };
4836 
4837 /// ----------------------- Privatizable Pointers ------------------------------
4838 struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
4839   AAPrivatizablePtrImpl(const IRPosition &IRP)
4840       : AAPrivatizablePtr(IRP), PrivatizableType(llvm::None) {}
4841 
4842   ChangeStatus indicatePessimisticFixpoint() override {
4843     AAPrivatizablePtr::indicatePessimisticFixpoint();
4844     PrivatizableType = nullptr;
4845     return ChangeStatus::CHANGED;
4846   }
4847 
4848   /// Identify the type we can chose for a private copy of the underlying
4849   /// argument. None means it is not clear yet, nullptr means there is none.
4850   virtual Optional<Type *> identifyPrivatizableType(Attributor &A) = 0;
4851 
4852   /// Return a privatizable type that encloses both T0 and T1.
4853   /// TODO: This is merely a stub for now as we should manage a mapping as well.
4854   Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) {
4855     if (!T0.hasValue())
4856       return T1;
4857     if (!T1.hasValue())
4858       return T0;
4859     if (T0 == T1)
4860       return T0;
4861     return nullptr;
4862   }
4863 
4864   Optional<Type *> getPrivatizableType() const override {
4865     return PrivatizableType;
4866   }
4867 
4868   const std::string getAsStr() const override {
4869     return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]";
4870   }
4871 
4872 protected:
4873   Optional<Type *> PrivatizableType;
4874 };
4875 
4876 // TODO: Do this for call site arguments (probably also other values) as well.
4877 
4878 struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
4879   AAPrivatizablePtrArgument(const IRPosition &IRP)
4880       : AAPrivatizablePtrImpl(IRP) {}
4881 
4882   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
4883   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
4884     // If this is a byval argument and we know all the call sites (so we can
4885     // rewrite them), there is no need to check them explicitly.
4886     bool AllCallSitesKnown;
4887     if (getIRPosition().hasAttr(Attribute::ByVal) &&
4888         A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this,
4889                                true, AllCallSitesKnown))
4890       return getAssociatedValue().getType()->getPointerElementType();
4891 
4892     Optional<Type *> Ty;
4893     unsigned ArgNo = getIRPosition().getArgNo();
4894 
4895     // Make sure the associated call site argument has the same type at all call
4896     // sites and it is an allocation we know is safe to privatize, for now that
4897     // means we only allow alloca instructions.
4898     // TODO: We can additionally analyze the accesses in the callee to  create
4899     //       the type from that information instead. That is a little more
4900     //       involved and will be done in a follow up patch.
4901     auto CallSiteCheck = [&](AbstractCallSite ACS) {
4902       IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
4903       // Check if a coresponding argument was found or if it is one not
4904       // associated (which can happen for callback calls).
4905       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
4906         return false;
4907 
4908       // Check that all call sites agree on a type.
4909       auto &PrivCSArgAA = A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos);
4910       Optional<Type *> CSTy = PrivCSArgAA.getPrivatizableType();
4911 
4912       LLVM_DEBUG({
4913         dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
4914         if (CSTy.hasValue() && CSTy.getValue())
4915           CSTy.getValue()->print(dbgs());
4916         else if (CSTy.hasValue())
4917           dbgs() << "<nullptr>";
4918         else
4919           dbgs() << "<none>";
4920       });
4921 
4922       Ty = combineTypes(Ty, CSTy);
4923 
4924       LLVM_DEBUG({
4925         dbgs() << " : New Type: ";
4926         if (Ty.hasValue() && Ty.getValue())
4927           Ty.getValue()->print(dbgs());
4928         else if (Ty.hasValue())
4929           dbgs() << "<nullptr>";
4930         else
4931           dbgs() << "<none>";
4932         dbgs() << "\n";
4933       });
4934 
4935       return !Ty.hasValue() || Ty.getValue();
4936     };
4937 
4938     if (!A.checkForAllCallSites(CallSiteCheck, *this, true, AllCallSitesKnown))
4939       return nullptr;
4940     return Ty;
4941   }
4942 
4943   /// See AbstractAttribute::updateImpl(...).
4944   ChangeStatus updateImpl(Attributor &A) override {
4945     PrivatizableType = identifyPrivatizableType(A);
4946     if (!PrivatizableType.hasValue())
4947       return ChangeStatus::UNCHANGED;
4948     if (!PrivatizableType.getValue())
4949       return indicatePessimisticFixpoint();
4950 
4951     // Avoid arguments with padding for now.
4952     if (!getIRPosition().hasAttr(Attribute::ByVal) &&
4953         !ArgumentPromotionPass::isDenselyPacked(PrivatizableType.getValue(),
4954                                                 A.getInfoCache().getDL())) {
4955       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n");
4956       return indicatePessimisticFixpoint();
4957     }
4958 
4959     // Verify callee and caller agree on how the promoted argument would be
4960     // passed.
4961     // TODO: The use of the ArgumentPromotion interface here is ugly, we need a
4962     // specialized form of TargetTransformInfo::areFunctionArgsABICompatible
4963     // which doesn't require the arguments ArgumentPromotion wanted to pass.
4964     Function &Fn = *getIRPosition().getAnchorScope();
4965     SmallPtrSet<Argument *, 1> ArgsToPromote, Dummy;
4966     ArgsToPromote.insert(getAssociatedArgument());
4967     const auto *TTI =
4968         A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
4969     if (!TTI ||
4970         !ArgumentPromotionPass::areFunctionArgsABICompatible(
4971             Fn, *TTI, ArgsToPromote, Dummy) ||
4972         ArgsToPromote.empty()) {
4973       LLVM_DEBUG(
4974           dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for "
4975                  << Fn.getName() << "\n");
4976       return indicatePessimisticFixpoint();
4977     }
4978 
4979     // Collect the types that will replace the privatizable type in the function
4980     // signature.
4981     SmallVector<Type *, 16> ReplacementTypes;
4982     identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
4983 
4984     // Register a rewrite of the argument.
4985     Argument *Arg = getAssociatedArgument();
4986     if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
4987       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n");
4988       return indicatePessimisticFixpoint();
4989     }
4990 
4991     unsigned ArgNo = Arg->getArgNo();
4992 
4993     // Helper to check if for the given call site the associated argument is
4994     // passed to a callback where the privatization would be different.
4995     auto IsCompatiblePrivArgOfCallback = [&](CallSite CS) {
4996       SmallVector<const Use *, 4> CBUses;
4997       AbstractCallSite::getCallbackUses(CS, CBUses);
4998       for (const Use *U : CBUses) {
4999         AbstractCallSite CBACS(U);
5000         assert(CBACS && CBACS.isCallbackCall());
5001         for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
5002           int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
5003 
5004           LLVM_DEBUG({
5005             dbgs()
5006                 << "[AAPrivatizablePtr] Argument " << *Arg
5007                 << "check if can be privatized in the context of its parent ("
5008                 << Arg->getParent()->getName()
5009                 << ")\n[AAPrivatizablePtr] because it is an argument in a "
5010                    "callback ("
5011                 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
5012                 << ")\n[AAPrivatizablePtr] " << CBArg << " : "
5013                 << CBACS.getCallArgOperand(CBArg) << " vs "
5014                 << CS.getArgOperand(ArgNo) << "\n"
5015                 << "[AAPrivatizablePtr] " << CBArg << " : "
5016                 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n";
5017           });
5018 
5019           if (CBArgNo != int(ArgNo))
5020             continue;
5021           const auto &CBArgPrivAA =
5022               A.getAAFor<AAPrivatizablePtr>(*this, IRPosition::argument(CBArg));
5023           if (CBArgPrivAA.isValidState()) {
5024             auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType();
5025             if (!CBArgPrivTy.hasValue())
5026               continue;
5027             if (CBArgPrivTy.getValue() == PrivatizableType)
5028               continue;
5029           }
5030 
5031           LLVM_DEBUG({
5032             dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5033                    << " cannot be privatized in the context of its parent ("
5034                    << Arg->getParent()->getName()
5035                    << ")\n[AAPrivatizablePtr] because it is an argument in a "
5036                       "callback ("
5037                    << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
5038                    << ").\n[AAPrivatizablePtr] for which the argument "
5039                       "privatization is not compatible.\n";
5040           });
5041           return false;
5042         }
5043       }
5044       return true;
5045     };
5046 
5047     // Helper to check if for the given call site the associated argument is
5048     // passed to a direct call where the privatization would be different.
5049     auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
5050       CallBase *DC = cast<CallBase>(ACS.getInstruction());
5051       int DCArgNo = ACS.getCallArgOperandNo(ArgNo);
5052       assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->getNumArgOperands() &&
5053              "Expected a direct call operand for callback call operand");
5054 
5055       LLVM_DEBUG({
5056         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5057                << " check if be privatized in the context of its parent ("
5058                << Arg->getParent()->getName()
5059                << ")\n[AAPrivatizablePtr] because it is an argument in a "
5060                   "direct call of ("
5061                << DCArgNo << "@" << DC->getCalledFunction()->getName()
5062                << ").\n";
5063       });
5064 
5065       Function *DCCallee = DC->getCalledFunction();
5066       if (unsigned(DCArgNo) < DCCallee->arg_size()) {
5067         const auto &DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
5068             *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)));
5069         if (DCArgPrivAA.isValidState()) {
5070           auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType();
5071           if (!DCArgPrivTy.hasValue())
5072             return true;
5073           if (DCArgPrivTy.getValue() == PrivatizableType)
5074             return true;
5075         }
5076       }
5077 
5078       LLVM_DEBUG({
5079         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5080                << " cannot be privatized in the context of its parent ("
5081                << Arg->getParent()->getName()
5082                << ")\n[AAPrivatizablePtr] because it is an argument in a "
5083                   "direct call of ("
5084                << ACS.getCallSite().getCalledFunction()->getName()
5085                << ").\n[AAPrivatizablePtr] for which the argument "
5086                   "privatization is not compatible.\n";
5087       });
5088       return false;
5089     };
5090 
5091     // Helper to check if the associated argument is used at the given abstract
5092     // call site in a way that is incompatible with the privatization assumed
5093     // here.
5094     auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
5095       if (ACS.isDirectCall())
5096         return IsCompatiblePrivArgOfCallback(ACS.getCallSite());
5097       if (ACS.isCallbackCall())
5098         return IsCompatiblePrivArgOfDirectCS(ACS);
5099       return false;
5100     };
5101 
5102     bool AllCallSitesKnown;
5103     if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true,
5104                                 AllCallSitesKnown))
5105       return indicatePessimisticFixpoint();
5106 
5107     return ChangeStatus::UNCHANGED;
5108   }
5109 
5110   /// Given a type to private \p PrivType, collect the constituates (which are
5111   /// used) in \p ReplacementTypes.
5112   static void
5113   identifyReplacementTypes(Type *PrivType,
5114                            SmallVectorImpl<Type *> &ReplacementTypes) {
5115     // TODO: For now we expand the privatization type to the fullest which can
5116     //       lead to dead arguments that need to be removed later.
5117     assert(PrivType && "Expected privatizable type!");
5118 
5119     // Traverse the type, extract constituate types on the outermost level.
5120     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5121       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
5122         ReplacementTypes.push_back(PrivStructType->getElementType(u));
5123     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5124       ReplacementTypes.append(PrivArrayType->getNumElements(),
5125                               PrivArrayType->getElementType());
5126     } else {
5127       ReplacementTypes.push_back(PrivType);
5128     }
5129   }
5130 
5131   /// Initialize \p Base according to the type \p PrivType at position \p IP.
5132   /// The values needed are taken from the arguments of \p F starting at
5133   /// position \p ArgNo.
5134   static void createInitialization(Type *PrivType, Value &Base, Function &F,
5135                                    unsigned ArgNo, Instruction &IP) {
5136     assert(PrivType && "Expected privatizable type!");
5137 
5138     IRBuilder<NoFolder> IRB(&IP);
5139     const DataLayout &DL = F.getParent()->getDataLayout();
5140 
5141     // Traverse the type, build GEPs and stores.
5142     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5143       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
5144       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
5145         Type *PointeeTy = PrivStructType->getElementType(u)->getPointerTo();
5146         Value *Ptr = constructPointer(
5147             PointeeTy, &Base, PrivStructLayout->getElementOffset(u), IRB, DL);
5148         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
5149       }
5150     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5151       Type *PointeePtrTy = PrivArrayType->getElementType()->getPointerTo();
5152       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeePtrTy);
5153       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
5154         Value *Ptr =
5155             constructPointer(PointeePtrTy, &Base, u * PointeeTySize, IRB, DL);
5156         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
5157       }
5158     } else {
5159       new StoreInst(F.getArg(ArgNo), &Base, &IP);
5160     }
5161   }
5162 
5163   /// Extract values from \p Base according to the type \p PrivType at the
5164   /// call position \p ACS. The values are appended to \p ReplacementValues.
5165   void createReplacementValues(Type *PrivType, AbstractCallSite ACS,
5166                                Value *Base,
5167                                SmallVectorImpl<Value *> &ReplacementValues) {
5168     assert(Base && "Expected base value!");
5169     assert(PrivType && "Expected privatizable type!");
5170     Instruction *IP = ACS.getInstruction();
5171 
5172     IRBuilder<NoFolder> IRB(IP);
5173     const DataLayout &DL = IP->getModule()->getDataLayout();
5174 
5175     if (Base->getType()->getPointerElementType() != PrivType)
5176       Base = BitCastInst::CreateBitOrPointerCast(Base, PrivType->getPointerTo(),
5177                                                  "", ACS.getInstruction());
5178 
5179     // TODO: Improve the alignment of the loads.
5180     // Traverse the type, build GEPs and loads.
5181     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5182       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
5183       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
5184         Type *PointeeTy = PrivStructType->getElementType(u);
5185         Value *Ptr =
5186             constructPointer(PointeeTy->getPointerTo(), Base,
5187                              PrivStructLayout->getElementOffset(u), IRB, DL);
5188         LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
5189         L->setAlignment(Align(1));
5190         ReplacementValues.push_back(L);
5191       }
5192     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5193       Type *PointeeTy = PrivArrayType->getElementType();
5194       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
5195       Type *PointeePtrTy = PointeeTy->getPointerTo();
5196       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
5197         Value *Ptr =
5198             constructPointer(PointeePtrTy, Base, u * PointeeTySize, IRB, DL);
5199         LoadInst *L = new LoadInst(PointeePtrTy, Ptr, "", IP);
5200         L->setAlignment(Align(1));
5201         ReplacementValues.push_back(L);
5202       }
5203     } else {
5204       LoadInst *L = new LoadInst(PrivType, Base, "", IP);
5205       L->setAlignment(Align(1));
5206       ReplacementValues.push_back(L);
5207     }
5208   }
5209 
5210   /// See AbstractAttribute::manifest(...)
5211   ChangeStatus manifest(Attributor &A) override {
5212     if (!PrivatizableType.hasValue())
5213       return ChangeStatus::UNCHANGED;
5214     assert(PrivatizableType.getValue() && "Expected privatizable type!");
5215 
5216     // Collect all tail calls in the function as we cannot allow new allocas to
5217     // escape into tail recursion.
5218     // TODO: Be smarter about new allocas escaping into tail calls.
5219     SmallVector<CallInst *, 16> TailCalls;
5220     if (!A.checkForAllInstructions(
5221             [&](Instruction &I) {
5222               CallInst &CI = cast<CallInst>(I);
5223               if (CI.isTailCall())
5224                 TailCalls.push_back(&CI);
5225               return true;
5226             },
5227             *this, {Instruction::Call}))
5228       return ChangeStatus::UNCHANGED;
5229 
5230     Argument *Arg = getAssociatedArgument();
5231 
5232     // Callback to repair the associated function. A new alloca is placed at the
5233     // beginning and initialized with the values passed through arguments. The
5234     // new alloca replaces the use of the old pointer argument.
5235     Attributor::ArgumentReplacementInfo::CalleeRepairCBTy FnRepairCB =
5236         [=](const Attributor::ArgumentReplacementInfo &ARI,
5237             Function &ReplacementFn, Function::arg_iterator ArgIt) {
5238           BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
5239           Instruction *IP = &*EntryBB.getFirstInsertionPt();
5240           auto *AI = new AllocaInst(PrivatizableType.getValue(), 0,
5241                                     Arg->getName() + ".priv", IP);
5242           createInitialization(PrivatizableType.getValue(), *AI, ReplacementFn,
5243                                ArgIt->getArgNo(), *IP);
5244           Arg->replaceAllUsesWith(AI);
5245 
5246           for (CallInst *CI : TailCalls)
5247             CI->setTailCall(false);
5248         };
5249 
5250     // Callback to repair a call site of the associated function. The elements
5251     // of the privatizable type are loaded prior to the call and passed to the
5252     // new function version.
5253     Attributor::ArgumentReplacementInfo::ACSRepairCBTy ACSRepairCB =
5254         [=](const Attributor::ArgumentReplacementInfo &ARI,
5255             AbstractCallSite ACS, SmallVectorImpl<Value *> &NewArgOperands) {
5256           createReplacementValues(
5257               PrivatizableType.getValue(), ACS,
5258               ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()),
5259               NewArgOperands);
5260         };
5261 
5262     // Collect the types that will replace the privatizable type in the function
5263     // signature.
5264     SmallVector<Type *, 16> ReplacementTypes;
5265     identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
5266 
5267     // Register a rewrite of the argument.
5268     if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
5269                                            std::move(FnRepairCB),
5270                                            std::move(ACSRepairCB)))
5271       return ChangeStatus::CHANGED;
5272     return ChangeStatus::UNCHANGED;
5273   }
5274 
5275   /// See AbstractAttribute::trackStatistics()
5276   void trackStatistics() const override {
5277     STATS_DECLTRACK_ARG_ATTR(privatizable_ptr);
5278   }
5279 };
5280 
5281 struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl {
5282   AAPrivatizablePtrFloating(const IRPosition &IRP)
5283       : AAPrivatizablePtrImpl(IRP) {}
5284 
5285   /// See AbstractAttribute::initialize(...).
5286   virtual void initialize(Attributor &A) override {
5287     // TODO: We can privatize more than arguments.
5288     indicatePessimisticFixpoint();
5289   }
5290 
5291   ChangeStatus updateImpl(Attributor &A) override {
5292     llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::"
5293                      "updateImpl will not be called");
5294   }
5295 
5296   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
5297   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
5298     Value *Obj =
5299         GetUnderlyingObject(&getAssociatedValue(), A.getInfoCache().getDL());
5300     if (!Obj) {
5301       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n");
5302       return nullptr;
5303     }
5304 
5305     if (auto *AI = dyn_cast<AllocaInst>(Obj))
5306       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
5307         if (CI->isOne())
5308           return Obj->getType()->getPointerElementType();
5309     if (auto *Arg = dyn_cast<Argument>(Obj)) {
5310       auto &PrivArgAA =
5311           A.getAAFor<AAPrivatizablePtr>(*this, IRPosition::argument(*Arg));
5312       if (PrivArgAA.isAssumedPrivatizablePtr())
5313         return Obj->getType()->getPointerElementType();
5314     }
5315 
5316     LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid "
5317                          "alloca nor privatizable argument: "
5318                       << *Obj << "!\n");
5319     return nullptr;
5320   }
5321 
5322   /// See AbstractAttribute::trackStatistics()
5323   void trackStatistics() const override {
5324     STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr);
5325   }
5326 };
5327 
5328 struct AAPrivatizablePtrCallSiteArgument final
5329     : public AAPrivatizablePtrFloating {
5330   AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP)
5331       : AAPrivatizablePtrFloating(IRP) {}
5332 
5333   /// See AbstractAttribute::initialize(...).
5334   void initialize(Attributor &A) override {
5335     if (getIRPosition().hasAttr(Attribute::ByVal))
5336       indicateOptimisticFixpoint();
5337   }
5338 
5339   /// See AbstractAttribute::updateImpl(...).
5340   ChangeStatus updateImpl(Attributor &A) override {
5341     PrivatizableType = identifyPrivatizableType(A);
5342     if (!PrivatizableType.hasValue())
5343       return ChangeStatus::UNCHANGED;
5344     if (!PrivatizableType.getValue())
5345       return indicatePessimisticFixpoint();
5346 
5347     const IRPosition &IRP = getIRPosition();
5348     auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, IRP);
5349     if (!NoCaptureAA.isAssumedNoCapture()) {
5350       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n");
5351       return indicatePessimisticFixpoint();
5352     }
5353 
5354     auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP);
5355     if (!NoAliasAA.isAssumedNoAlias()) {
5356       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n");
5357       return indicatePessimisticFixpoint();
5358     }
5359 
5360     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(*this, IRP);
5361     if (!MemBehaviorAA.isAssumedReadOnly()) {
5362       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n");
5363       return indicatePessimisticFixpoint();
5364     }
5365 
5366     return ChangeStatus::UNCHANGED;
5367   }
5368 
5369   /// See AbstractAttribute::trackStatistics()
5370   void trackStatistics() const override {
5371     STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr);
5372   }
5373 };
5374 
5375 struct AAPrivatizablePtrCallSiteReturned final
5376     : public AAPrivatizablePtrFloating {
5377   AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP)
5378       : AAPrivatizablePtrFloating(IRP) {}
5379 
5380   /// See AbstractAttribute::initialize(...).
5381   void initialize(Attributor &A) override {
5382     // TODO: We can privatize more than arguments.
5383     indicatePessimisticFixpoint();
5384   }
5385 
5386   /// See AbstractAttribute::trackStatistics()
5387   void trackStatistics() const override {
5388     STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr);
5389   }
5390 };
5391 
5392 struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating {
5393   AAPrivatizablePtrReturned(const IRPosition &IRP)
5394       : AAPrivatizablePtrFloating(IRP) {}
5395 
5396   /// See AbstractAttribute::initialize(...).
5397   void initialize(Attributor &A) override {
5398     // TODO: We can privatize more than arguments.
5399     indicatePessimisticFixpoint();
5400   }
5401 
5402   /// See AbstractAttribute::trackStatistics()
5403   void trackStatistics() const override {
5404     STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr);
5405   }
5406 };
5407 
5408 /// -------------------- Memory Behavior Attributes ----------------------------
5409 /// Includes read-none, read-only, and write-only.
5410 /// ----------------------------------------------------------------------------
5411 struct AAMemoryBehaviorImpl : public AAMemoryBehavior {
5412   AAMemoryBehaviorImpl(const IRPosition &IRP) : AAMemoryBehavior(IRP) {}
5413 
5414   /// See AbstractAttribute::initialize(...).
5415   void initialize(Attributor &A) override {
5416     intersectAssumedBits(BEST_STATE);
5417     getKnownStateFromValue(getIRPosition(), getState());
5418     IRAttribute::initialize(A);
5419   }
5420 
5421   /// Return the memory behavior information encoded in the IR for \p IRP.
5422   static void getKnownStateFromValue(const IRPosition &IRP,
5423                                      BitIntegerState &State,
5424                                      bool IgnoreSubsumingPositions = false) {
5425     SmallVector<Attribute, 2> Attrs;
5426     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
5427     for (const Attribute &Attr : Attrs) {
5428       switch (Attr.getKindAsEnum()) {
5429       case Attribute::ReadNone:
5430         State.addKnownBits(NO_ACCESSES);
5431         break;
5432       case Attribute::ReadOnly:
5433         State.addKnownBits(NO_WRITES);
5434         break;
5435       case Attribute::WriteOnly:
5436         State.addKnownBits(NO_READS);
5437         break;
5438       default:
5439         llvm_unreachable("Unexpected attribute!");
5440       }
5441     }
5442 
5443     if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) {
5444       if (!I->mayReadFromMemory())
5445         State.addKnownBits(NO_READS);
5446       if (!I->mayWriteToMemory())
5447         State.addKnownBits(NO_WRITES);
5448     }
5449   }
5450 
5451   /// See AbstractAttribute::getDeducedAttributes(...).
5452   void getDeducedAttributes(LLVMContext &Ctx,
5453                             SmallVectorImpl<Attribute> &Attrs) const override {
5454     assert(Attrs.size() == 0);
5455     if (isAssumedReadNone())
5456       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
5457     else if (isAssumedReadOnly())
5458       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
5459     else if (isAssumedWriteOnly())
5460       Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
5461     assert(Attrs.size() <= 1);
5462   }
5463 
5464   /// See AbstractAttribute::manifest(...).
5465   ChangeStatus manifest(Attributor &A) override {
5466     if (hasAttr(Attribute::ReadNone, /* IgnoreSubsumingPositions */ true))
5467       return ChangeStatus::UNCHANGED;
5468 
5469     const IRPosition &IRP = getIRPosition();
5470 
5471     // Check if we would improve the existing attributes first.
5472     SmallVector<Attribute, 4> DeducedAttrs;
5473     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
5474     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
5475           return IRP.hasAttr(Attr.getKindAsEnum(),
5476                              /* IgnoreSubsumingPositions */ true);
5477         }))
5478       return ChangeStatus::UNCHANGED;
5479 
5480     // Clear existing attributes.
5481     IRP.removeAttrs(AttrKinds);
5482 
5483     // Use the generic manifest method.
5484     return IRAttribute::manifest(A);
5485   }
5486 
5487   /// See AbstractState::getAsStr().
5488   const std::string getAsStr() const override {
5489     if (isAssumedReadNone())
5490       return "readnone";
5491     if (isAssumedReadOnly())
5492       return "readonly";
5493     if (isAssumedWriteOnly())
5494       return "writeonly";
5495     return "may-read/write";
5496   }
5497 
5498   /// The set of IR attributes AAMemoryBehavior deals with.
5499   static const Attribute::AttrKind AttrKinds[3];
5500 };
5501 
5502 const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = {
5503     Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
5504 
5505 /// Memory behavior attribute for a floating value.
5506 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
5507   AAMemoryBehaviorFloating(const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {}
5508 
5509   /// See AbstractAttribute::initialize(...).
5510   void initialize(Attributor &A) override {
5511     AAMemoryBehaviorImpl::initialize(A);
5512     // Initialize the use vector with all direct uses of the associated value.
5513     for (const Use &U : getAssociatedValue().uses())
5514       Uses.insert(&U);
5515   }
5516 
5517   /// See AbstractAttribute::updateImpl(...).
5518   ChangeStatus updateImpl(Attributor &A) override;
5519 
5520   /// See AbstractAttribute::trackStatistics()
5521   void trackStatistics() const override {
5522     if (isAssumedReadNone())
5523       STATS_DECLTRACK_FLOATING_ATTR(readnone)
5524     else if (isAssumedReadOnly())
5525       STATS_DECLTRACK_FLOATING_ATTR(readonly)
5526     else if (isAssumedWriteOnly())
5527       STATS_DECLTRACK_FLOATING_ATTR(writeonly)
5528   }
5529 
5530 private:
5531   /// Return true if users of \p UserI might access the underlying
5532   /// variable/location described by \p U and should therefore be analyzed.
5533   bool followUsersOfUseIn(Attributor &A, const Use *U,
5534                           const Instruction *UserI);
5535 
5536   /// Update the state according to the effect of use \p U in \p UserI.
5537   void analyzeUseIn(Attributor &A, const Use *U, const Instruction *UserI);
5538 
5539 protected:
5540   /// Container for (transitive) uses of the associated argument.
5541   SetVector<const Use *> Uses;
5542 };
5543 
5544 /// Memory behavior attribute for function argument.
5545 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
5546   AAMemoryBehaviorArgument(const IRPosition &IRP)
5547       : AAMemoryBehaviorFloating(IRP) {}
5548 
5549   /// See AbstractAttribute::initialize(...).
5550   void initialize(Attributor &A) override {
5551     intersectAssumedBits(BEST_STATE);
5552     const IRPosition &IRP = getIRPosition();
5553     // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we
5554     // can query it when we use has/getAttr. That would allow us to reuse the
5555     // initialize of the base class here.
5556     bool HasByVal =
5557         IRP.hasAttr({Attribute::ByVal}, /* IgnoreSubsumingPositions */ true);
5558     getKnownStateFromValue(IRP, getState(),
5559                            /* IgnoreSubsumingPositions */ HasByVal);
5560 
5561     // Initialize the use vector with all direct uses of the associated value.
5562     Argument *Arg = getAssociatedArgument();
5563     if (!Arg || !A.isFunctionIPOAmendable(*(Arg->getParent()))) {
5564       indicatePessimisticFixpoint();
5565     } else {
5566       // Initialize the use vector with all direct uses of the associated value.
5567       for (const Use &U : Arg->uses())
5568         Uses.insert(&U);
5569     }
5570   }
5571 
5572   ChangeStatus manifest(Attributor &A) override {
5573     // TODO: Pointer arguments are not supported on vectors of pointers yet.
5574     if (!getAssociatedValue().getType()->isPointerTy())
5575       return ChangeStatus::UNCHANGED;
5576 
5577     // TODO: From readattrs.ll: "inalloca parameters are always
5578     //                           considered written"
5579     if (hasAttr({Attribute::InAlloca})) {
5580       removeKnownBits(NO_WRITES);
5581       removeAssumedBits(NO_WRITES);
5582     }
5583     return AAMemoryBehaviorFloating::manifest(A);
5584   }
5585 
5586   /// See AbstractAttribute::trackStatistics()
5587   void trackStatistics() const override {
5588     if (isAssumedReadNone())
5589       STATS_DECLTRACK_ARG_ATTR(readnone)
5590     else if (isAssumedReadOnly())
5591       STATS_DECLTRACK_ARG_ATTR(readonly)
5592     else if (isAssumedWriteOnly())
5593       STATS_DECLTRACK_ARG_ATTR(writeonly)
5594   }
5595 };
5596 
5597 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
5598   AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP)
5599       : AAMemoryBehaviorArgument(IRP) {}
5600 
5601   /// See AbstractAttribute::initialize(...).
5602   void initialize(Attributor &A) override {
5603     if (Argument *Arg = getAssociatedArgument()) {
5604       if (Arg->hasByValAttr()) {
5605         addKnownBits(NO_WRITES);
5606         removeKnownBits(NO_READS);
5607         removeAssumedBits(NO_READS);
5608       }
5609     } else {
5610     }
5611     AAMemoryBehaviorArgument::initialize(A);
5612   }
5613 
5614   /// See AbstractAttribute::updateImpl(...).
5615   ChangeStatus updateImpl(Attributor &A) override {
5616     // TODO: Once we have call site specific value information we can provide
5617     //       call site specific liveness liveness information and then it makes
5618     //       sense to specialize attributes for call sites arguments instead of
5619     //       redirecting requests to the callee argument.
5620     Argument *Arg = getAssociatedArgument();
5621     const IRPosition &ArgPos = IRPosition::argument(*Arg);
5622     auto &ArgAA = A.getAAFor<AAMemoryBehavior>(*this, ArgPos);
5623     return clampStateAndIndicateChange(
5624         getState(),
5625         static_cast<const AAMemoryBehavior::StateType &>(ArgAA.getState()));
5626   }
5627 
5628   /// See AbstractAttribute::trackStatistics()
5629   void trackStatistics() const override {
5630     if (isAssumedReadNone())
5631       STATS_DECLTRACK_CSARG_ATTR(readnone)
5632     else if (isAssumedReadOnly())
5633       STATS_DECLTRACK_CSARG_ATTR(readonly)
5634     else if (isAssumedWriteOnly())
5635       STATS_DECLTRACK_CSARG_ATTR(writeonly)
5636   }
5637 };
5638 
5639 /// Memory behavior attribute for a call site return position.
5640 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
5641   AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP)
5642       : AAMemoryBehaviorFloating(IRP) {}
5643 
5644   /// See AbstractAttribute::manifest(...).
5645   ChangeStatus manifest(Attributor &A) override {
5646     // We do not annotate returned values.
5647     return ChangeStatus::UNCHANGED;
5648   }
5649 
5650   /// See AbstractAttribute::trackStatistics()
5651   void trackStatistics() const override {}
5652 };
5653 
5654 /// An AA to represent the memory behavior function attributes.
5655 struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl {
5656   AAMemoryBehaviorFunction(const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {}
5657 
5658   /// See AbstractAttribute::updateImpl(Attributor &A).
5659   virtual ChangeStatus updateImpl(Attributor &A) override;
5660 
5661   /// See AbstractAttribute::manifest(...).
5662   ChangeStatus manifest(Attributor &A) override {
5663     Function &F = cast<Function>(getAnchorValue());
5664     if (isAssumedReadNone()) {
5665       F.removeFnAttr(Attribute::ArgMemOnly);
5666       F.removeFnAttr(Attribute::InaccessibleMemOnly);
5667       F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
5668     }
5669     return AAMemoryBehaviorImpl::manifest(A);
5670   }
5671 
5672   /// See AbstractAttribute::trackStatistics()
5673   void trackStatistics() const override {
5674     if (isAssumedReadNone())
5675       STATS_DECLTRACK_FN_ATTR(readnone)
5676     else if (isAssumedReadOnly())
5677       STATS_DECLTRACK_FN_ATTR(readonly)
5678     else if (isAssumedWriteOnly())
5679       STATS_DECLTRACK_FN_ATTR(writeonly)
5680   }
5681 };
5682 
5683 /// AAMemoryBehavior attribute for call sites.
5684 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl {
5685   AAMemoryBehaviorCallSite(const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {}
5686 
5687   /// See AbstractAttribute::initialize(...).
5688   void initialize(Attributor &A) override {
5689     AAMemoryBehaviorImpl::initialize(A);
5690     Function *F = getAssociatedFunction();
5691     if (!F || !A.isFunctionIPOAmendable(*F))
5692       indicatePessimisticFixpoint();
5693   }
5694 
5695   /// See AbstractAttribute::updateImpl(...).
5696   ChangeStatus updateImpl(Attributor &A) override {
5697     // TODO: Once we have call site specific value information we can provide
5698     //       call site specific liveness liveness information and then it makes
5699     //       sense to specialize attributes for call sites arguments instead of
5700     //       redirecting requests to the callee argument.
5701     Function *F = getAssociatedFunction();
5702     const IRPosition &FnPos = IRPosition::function(*F);
5703     auto &FnAA = A.getAAFor<AAMemoryBehavior>(*this, FnPos);
5704     return clampStateAndIndicateChange(
5705         getState(),
5706         static_cast<const AAMemoryBehavior::StateType &>(FnAA.getState()));
5707   }
5708 
5709   /// See AbstractAttribute::trackStatistics()
5710   void trackStatistics() const override {
5711     if (isAssumedReadNone())
5712       STATS_DECLTRACK_CS_ATTR(readnone)
5713     else if (isAssumedReadOnly())
5714       STATS_DECLTRACK_CS_ATTR(readonly)
5715     else if (isAssumedWriteOnly())
5716       STATS_DECLTRACK_CS_ATTR(writeonly)
5717   }
5718 };
5719 
5720 ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) {
5721 
5722   // The current assumed state used to determine a change.
5723   auto AssumedState = getAssumed();
5724 
5725   auto CheckRWInst = [&](Instruction &I) {
5726     // If the instruction has an own memory behavior state, use it to restrict
5727     // the local state. No further analysis is required as the other memory
5728     // state is as optimistic as it gets.
5729     if (ImmutableCallSite ICS = ImmutableCallSite(&I)) {
5730       const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
5731           *this, IRPosition::callsite_function(ICS));
5732       intersectAssumedBits(MemBehaviorAA.getAssumed());
5733       return !isAtFixpoint();
5734     }
5735 
5736     // Remove access kind modifiers if necessary.
5737     if (I.mayReadFromMemory())
5738       removeAssumedBits(NO_READS);
5739     if (I.mayWriteToMemory())
5740       removeAssumedBits(NO_WRITES);
5741     return !isAtFixpoint();
5742   };
5743 
5744   if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this))
5745     return indicatePessimisticFixpoint();
5746 
5747   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
5748                                         : ChangeStatus::UNCHANGED;
5749 }
5750 
5751 ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) {
5752 
5753   const IRPosition &IRP = getIRPosition();
5754   const IRPosition &FnPos = IRPosition::function_scope(IRP);
5755   AAMemoryBehavior::StateType &S = getState();
5756 
5757   // First, check the function scope. We take the known information and we avoid
5758   // work if the assumed information implies the current assumed information for
5759   // this attribute. This is a valid for all but byval arguments.
5760   Argument *Arg = IRP.getAssociatedArgument();
5761   AAMemoryBehavior::base_t FnMemAssumedState =
5762       AAMemoryBehavior::StateType::getWorstState();
5763   if (!Arg || !Arg->hasByValAttr()) {
5764     const auto &FnMemAA = A.getAAFor<AAMemoryBehavior>(
5765         *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
5766     FnMemAssumedState = FnMemAA.getAssumed();
5767     S.addKnownBits(FnMemAA.getKnown());
5768     if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed())
5769       return ChangeStatus::UNCHANGED;
5770   }
5771 
5772   // Make sure the value is not captured (except through "return"), if
5773   // it is, any information derived would be irrelevant anyway as we cannot
5774   // check the potential aliases introduced by the capture. However, no need
5775   // to fall back to anythign less optimistic than the function state.
5776   const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
5777       *this, IRP, /* TrackDependence */ true, DepClassTy::OPTIONAL);
5778   if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
5779     S.intersectAssumedBits(FnMemAssumedState);
5780     return ChangeStatus::CHANGED;
5781   }
5782 
5783   // The current assumed state used to determine a change.
5784   auto AssumedState = S.getAssumed();
5785 
5786   // Liveness information to exclude dead users.
5787   // TODO: Take the FnPos once we have call site specific liveness information.
5788   const auto &LivenessAA = A.getAAFor<AAIsDead>(
5789       *this, IRPosition::function(*IRP.getAssociatedFunction()),
5790       /* TrackDependence */ false);
5791 
5792   // Visit and expand uses until all are analyzed or a fixpoint is reached.
5793   for (unsigned i = 0; i < Uses.size() && !isAtFixpoint(); i++) {
5794     const Use *U = Uses[i];
5795     Instruction *UserI = cast<Instruction>(U->getUser());
5796     LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << **U << " in " << *UserI
5797                       << " [Dead: " << (A.isAssumedDead(*U, this, &LivenessAA))
5798                       << "]\n");
5799     if (A.isAssumedDead(*U, this, &LivenessAA))
5800       continue;
5801 
5802     // Droppable users, e.g., llvm::assume does not actually perform any action.
5803     if (UserI->isDroppable())
5804       continue;
5805 
5806     // Check if the users of UserI should also be visited.
5807     if (followUsersOfUseIn(A, U, UserI))
5808       for (const Use &UserIUse : UserI->uses())
5809         Uses.insert(&UserIUse);
5810 
5811     // If UserI might touch memory we analyze the use in detail.
5812     if (UserI->mayReadOrWriteMemory())
5813       analyzeUseIn(A, U, UserI);
5814   }
5815 
5816   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
5817                                         : ChangeStatus::UNCHANGED;
5818 }
5819 
5820 bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use *U,
5821                                                   const Instruction *UserI) {
5822   // The loaded value is unrelated to the pointer argument, no need to
5823   // follow the users of the load.
5824   if (isa<LoadInst>(UserI))
5825     return false;
5826 
5827   // By default we follow all uses assuming UserI might leak information on U,
5828   // we have special handling for call sites operands though.
5829   ImmutableCallSite ICS(UserI);
5830   if (!ICS || !ICS.isArgOperand(U))
5831     return true;
5832 
5833   // If the use is a call argument known not to be captured, the users of
5834   // the call do not need to be visited because they have to be unrelated to
5835   // the input. Note that this check is not trivial even though we disallow
5836   // general capturing of the underlying argument. The reason is that the
5837   // call might the argument "through return", which we allow and for which we
5838   // need to check call users.
5839   if (U->get()->getType()->isPointerTy()) {
5840     unsigned ArgNo = ICS.getArgumentNo(U);
5841     const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
5842         *this, IRPosition::callsite_argument(ICS, ArgNo),
5843         /* TrackDependence */ true, DepClassTy::OPTIONAL);
5844     return !ArgNoCaptureAA.isAssumedNoCapture();
5845   }
5846 
5847   return true;
5848 }
5849 
5850 void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use *U,
5851                                             const Instruction *UserI) {
5852   assert(UserI->mayReadOrWriteMemory());
5853 
5854   switch (UserI->getOpcode()) {
5855   default:
5856     // TODO: Handle all atomics and other side-effect operations we know of.
5857     break;
5858   case Instruction::Load:
5859     // Loads cause the NO_READS property to disappear.
5860     removeAssumedBits(NO_READS);
5861     return;
5862 
5863   case Instruction::Store:
5864     // Stores cause the NO_WRITES property to disappear if the use is the
5865     // pointer operand. Note that we do assume that capturing was taken care of
5866     // somewhere else.
5867     if (cast<StoreInst>(UserI)->getPointerOperand() == U->get())
5868       removeAssumedBits(NO_WRITES);
5869     return;
5870 
5871   case Instruction::Call:
5872   case Instruction::CallBr:
5873   case Instruction::Invoke: {
5874     // For call sites we look at the argument memory behavior attribute (this
5875     // could be recursive!) in order to restrict our own state.
5876     ImmutableCallSite ICS(UserI);
5877 
5878     // Give up on operand bundles.
5879     if (ICS.isBundleOperand(U)) {
5880       indicatePessimisticFixpoint();
5881       return;
5882     }
5883 
5884     // Calling a function does read the function pointer, maybe write it if the
5885     // function is self-modifying.
5886     if (ICS.isCallee(U)) {
5887       removeAssumedBits(NO_READS);
5888       break;
5889     }
5890 
5891     // Adjust the possible access behavior based on the information on the
5892     // argument.
5893     IRPosition Pos;
5894     if (U->get()->getType()->isPointerTy())
5895       Pos = IRPosition::callsite_argument(ICS, ICS.getArgumentNo(U));
5896     else
5897       Pos = IRPosition::callsite_function(ICS);
5898     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
5899         *this, Pos,
5900         /* TrackDependence */ true, DepClassTy::OPTIONAL);
5901     // "assumed" has at most the same bits as the MemBehaviorAA assumed
5902     // and at least "known".
5903     intersectAssumedBits(MemBehaviorAA.getAssumed());
5904     return;
5905   }
5906   };
5907 
5908   // Generally, look at the "may-properties" and adjust the assumed state if we
5909   // did not trigger special handling before.
5910   if (UserI->mayReadFromMemory())
5911     removeAssumedBits(NO_READS);
5912   if (UserI->mayWriteToMemory())
5913     removeAssumedBits(NO_WRITES);
5914 }
5915 
5916 } // namespace
5917 
5918 /// -------------------- Memory Locations Attributes ---------------------------
5919 /// Includes read-none, argmemonly, inaccessiblememonly,
5920 /// inaccessiblememorargmemonly
5921 /// ----------------------------------------------------------------------------
5922 
5923 std::string AAMemoryLocation::getMemoryLocationsAsStr(
5924     AAMemoryLocation::MemoryLocationsKind MLK) {
5925   if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS))
5926     return "all memory";
5927   if (MLK == AAMemoryLocation::NO_LOCATIONS)
5928     return "no memory";
5929   std::string S = "memory:";
5930   if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM))
5931     S += "stack,";
5932   if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM))
5933     S += "constant,";
5934   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_INTERNAL_MEM))
5935     S += "internal global,";
5936   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_EXTERNAL_MEM))
5937     S += "external global,";
5938   if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM))
5939     S += "argument,";
5940   if (0 == (MLK & AAMemoryLocation::NO_INACCESSIBLE_MEM))
5941     S += "inaccessible,";
5942   if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM))
5943     S += "malloced,";
5944   if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM))
5945     S += "unknown,";
5946   S.pop_back();
5947   return S;
5948 }
5949 
5950 struct AAMemoryLocationImpl : public AAMemoryLocation {
5951 
5952   AAMemoryLocationImpl(const IRPosition &IRP) : AAMemoryLocation(IRP) {}
5953 
5954   /// See AbstractAttribute::initialize(...).
5955   void initialize(Attributor &A) override {
5956     intersectAssumedBits(BEST_STATE);
5957     getKnownStateFromValue(getIRPosition(), getState());
5958     IRAttribute::initialize(A);
5959   }
5960 
5961   /// Return the memory behavior information encoded in the IR for \p IRP.
5962   static void getKnownStateFromValue(const IRPosition &IRP,
5963                                      BitIntegerState &State,
5964                                      bool IgnoreSubsumingPositions = false) {
5965     SmallVector<Attribute, 2> Attrs;
5966     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
5967     for (const Attribute &Attr : Attrs) {
5968       switch (Attr.getKindAsEnum()) {
5969       case Attribute::ReadNone:
5970         State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM);
5971         break;
5972       case Attribute::InaccessibleMemOnly:
5973         State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
5974         break;
5975       case Attribute::ArgMemOnly:
5976         State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true));
5977         break;
5978       case Attribute::InaccessibleMemOrArgMemOnly:
5979         State.addKnownBits(
5980             inverseLocation(NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true));
5981         break;
5982       default:
5983         llvm_unreachable("Unexpected attribute!");
5984       }
5985     }
5986   }
5987 
5988   /// See AbstractAttribute::getDeducedAttributes(...).
5989   void getDeducedAttributes(LLVMContext &Ctx,
5990                             SmallVectorImpl<Attribute> &Attrs) const override {
5991     assert(Attrs.size() == 0);
5992     if (isAssumedReadNone()) {
5993       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
5994     } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) {
5995       if (isAssumedInaccessibleMemOnly())
5996         Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly));
5997       else if (isAssumedArgMemOnly())
5998         Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly));
5999       else if (isAssumedInaccessibleOrArgMemOnly())
6000         Attrs.push_back(
6001             Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly));
6002     }
6003     assert(Attrs.size() <= 1);
6004   }
6005 
6006   /// See AbstractAttribute::manifest(...).
6007   ChangeStatus manifest(Attributor &A) override {
6008     const IRPosition &IRP = getIRPosition();
6009 
6010     // Check if we would improve the existing attributes first.
6011     SmallVector<Attribute, 4> DeducedAttrs;
6012     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
6013     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
6014           return IRP.hasAttr(Attr.getKindAsEnum(),
6015                              /* IgnoreSubsumingPositions */ true);
6016         }))
6017       return ChangeStatus::UNCHANGED;
6018 
6019     // Clear existing attributes.
6020     IRP.removeAttrs(AttrKinds);
6021     if (isAssumedReadNone())
6022       IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds);
6023 
6024     // Use the generic manifest method.
6025     return IRAttribute::manifest(A);
6026   }
6027 
6028   /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...).
6029   bool checkForAllAccessesToMemoryKind(
6030       function_ref<bool(const Instruction *, const Value *, AccessKind,
6031                         MemoryLocationsKind)>
6032           Pred,
6033       MemoryLocationsKind RequestedMLK) const override {
6034     if (!isValidState())
6035       return false;
6036 
6037     MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
6038     if (AssumedMLK == NO_LOCATIONS)
6039       return true;
6040 
6041     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
6042       if (CurMLK & RequestedMLK)
6043         continue;
6044 
6045       const auto &Accesses = AccessKindAccessesMap.lookup(CurMLK);
6046       for (const AccessInfo &AI : Accesses) {
6047         if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
6048           return false;
6049       }
6050     }
6051 
6052     return true;
6053   }
6054 
6055   ChangeStatus indicatePessimisticFixpoint() override {
6056     // If we give up and indicate a pessimistic fixpoint this instruction will
6057     // become an access for all potential access kinds:
6058     // TODO: Add pointers for argmemonly and globals to improve the results of
6059     //       checkForAllAccessesToMemoryKind.
6060     bool Changed = false;
6061     MemoryLocationsKind KnownMLK = getKnown();
6062     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
6063     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
6064       if (!(CurMLK & KnownMLK))
6065         updateStateAndAccessesMap(getState(), AccessKindAccessesMap, CurMLK, I,
6066                                   nullptr, Changed);
6067     return AAMemoryLocation::indicatePessimisticFixpoint();
6068   }
6069 
6070 protected:
6071   /// Helper struct to tie together an instruction that has a read or write
6072   /// effect with the pointer it accesses (if any).
6073   struct AccessInfo {
6074 
6075     /// The instruction that caused the access.
6076     const Instruction *I;
6077 
6078     /// The base pointer that is accessed, or null if unknown.
6079     const Value *Ptr;
6080 
6081     /// The kind of access (read/write/read+write).
6082     AccessKind Kind;
6083 
6084     bool operator==(const AccessInfo &RHS) const {
6085       return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind;
6086     }
6087     bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const {
6088       if (LHS.I != RHS.I)
6089         return LHS.I < RHS.I;
6090       if (LHS.Ptr != RHS.Ptr)
6091         return LHS.Ptr < RHS.Ptr;
6092       if (LHS.Kind != RHS.Kind)
6093         return LHS.Kind < RHS.Kind;
6094       return false;
6095     }
6096   };
6097 
6098   /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the
6099   /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind.
6100   using AccessKindAccessesMapTy =
6101       DenseMap<unsigned, SmallSet<AccessInfo, 8, AccessInfo>>;
6102   AccessKindAccessesMapTy AccessKindAccessesMap;
6103 
6104   /// Return the kind(s) of location that may be accessed by \p V.
6105   AAMemoryLocation::MemoryLocationsKind
6106   categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed);
6107 
6108   /// Update the state \p State and the AccessKindAccessesMap given that \p I is
6109   /// an access to a \p MLK memory location with the access pointer \p Ptr.
6110   static void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
6111                                         AccessKindAccessesMapTy &AccessMap,
6112                                         MemoryLocationsKind MLK,
6113                                         const Instruction *I, const Value *Ptr,
6114                                         bool &Changed) {
6115     // TODO: The kind should be determined at the call sites based on the
6116     // information we have there.
6117     AccessKind Kind = READ_WRITE;
6118     if (I) {
6119       Kind = I->mayReadFromMemory() ? READ : NONE;
6120       Kind = AccessKind(Kind | (I->mayWriteToMemory() ? WRITE : NONE));
6121     }
6122 
6123     assert(isPowerOf2_32(MLK) && "Expected a single location set!");
6124     Changed |= AccessMap[MLK].insert(AccessInfo{I, Ptr, Kind}).second;
6125     State.removeAssumedBits(MLK);
6126   }
6127 
6128   /// Determine the underlying locations kinds for \p Ptr, e.g., globals or
6129   /// arguments, and update the state and access map accordingly.
6130   void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr,
6131                           AAMemoryLocation::StateType &State, bool &Changed);
6132 
6133   /// The set of IR attributes AAMemoryLocation deals with.
6134   static const Attribute::AttrKind AttrKinds[4];
6135 };
6136 
6137 const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = {
6138     Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly,
6139     Attribute::InaccessibleMemOrArgMemOnly};
6140 
6141 void AAMemoryLocationImpl::categorizePtrValue(
6142     Attributor &A, const Instruction &I, const Value &Ptr,
6143     AAMemoryLocation::StateType &State, bool &Changed) {
6144   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for "
6145                     << Ptr << " ["
6146                     << getMemoryLocationsAsStr(State.getAssumed()) << "]\n");
6147 
6148   auto StripGEPCB = [](Value *V) -> Value * {
6149     auto *GEP = dyn_cast<GEPOperator>(V);
6150     while (GEP) {
6151       V = GEP->getPointerOperand();
6152       GEP = dyn_cast<GEPOperator>(V);
6153     }
6154     return V;
6155   };
6156 
6157   auto VisitValueCB = [&](Value &V, const Instruction *,
6158                           AAMemoryLocation::StateType &T,
6159                           bool Stripped) -> bool {
6160     assert(!isa<GEPOperator>(V) && "GEPs should have been stripped.");
6161     if (isa<UndefValue>(V))
6162       return true;
6163     if (auto *Arg = dyn_cast<Argument>(&V)) {
6164       if (Arg->hasByValAttr())
6165         updateStateAndAccessesMap(T, AccessKindAccessesMap, NO_LOCAL_MEM, &I,
6166                                   &V, Changed);
6167       else
6168         updateStateAndAccessesMap(T, AccessKindAccessesMap, NO_ARGUMENT_MEM, &I,
6169                                   &V, Changed);
6170       return true;
6171     }
6172     if (auto *GV = dyn_cast<GlobalValue>(&V)) {
6173       if (GV->hasLocalLinkage())
6174         updateStateAndAccessesMap(T, AccessKindAccessesMap,
6175                                   NO_GLOBAL_INTERNAL_MEM, &I, &V, Changed);
6176       else
6177         updateStateAndAccessesMap(T, AccessKindAccessesMap,
6178                                   NO_GLOBAL_EXTERNAL_MEM, &I, &V, Changed);
6179       return true;
6180     }
6181     if (isa<AllocaInst>(V)) {
6182       updateStateAndAccessesMap(T, AccessKindAccessesMap, NO_LOCAL_MEM, &I, &V,
6183                                 Changed);
6184       return true;
6185     }
6186     if (ImmutableCallSite ICS = ImmutableCallSite(&V)) {
6187       const auto &NoAliasAA =
6188           A.getAAFor<AANoAlias>(*this, IRPosition::callsite_returned(ICS));
6189       if (NoAliasAA.isAssumedNoAlias()) {
6190         updateStateAndAccessesMap(T, AccessKindAccessesMap, NO_MALLOCED_MEM, &I,
6191                                   &V, Changed);
6192         return true;
6193       }
6194     }
6195 
6196     updateStateAndAccessesMap(T, AccessKindAccessesMap, NO_UNKOWN_MEM, &I, &V,
6197                               Changed);
6198     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value cannot be categorized: "
6199                       << V << " -> " << getMemoryLocationsAsStr(T.getAssumed())
6200                       << "\n");
6201     return true;
6202   };
6203 
6204   if (!genericValueTraversal<AAMemoryLocation, AAMemoryLocation::StateType>(
6205           A, IRPosition::value(Ptr), *this, State, VisitValueCB, getCtxI(),
6206           /* MaxValues */ 32, StripGEPCB)) {
6207     LLVM_DEBUG(
6208         dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n");
6209     updateStateAndAccessesMap(State, AccessKindAccessesMap, NO_UNKOWN_MEM, &I,
6210                               nullptr, Changed);
6211   } else {
6212     LLVM_DEBUG(
6213         dbgs()
6214         << "[AAMemoryLocation] Accessed locations with pointer locations: "
6215         << getMemoryLocationsAsStr(State.getAssumed()) << "\n");
6216   }
6217 }
6218 
6219 AAMemoryLocation::MemoryLocationsKind
6220 AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I,
6221                                                   bool &Changed) {
6222   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for "
6223                     << I << "\n");
6224 
6225   AAMemoryLocation::StateType AccessedLocs;
6226   AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
6227 
6228   if (ImmutableCallSite ICS = ImmutableCallSite(&I)) {
6229 
6230     // First check if we assume any memory is access is visible.
6231     const auto &ICSMemLocationAA =
6232         A.getAAFor<AAMemoryLocation>(*this, IRPosition::callsite_function(ICS));
6233     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I
6234                       << " [" << ICSMemLocationAA << "]\n");
6235 
6236     if (ICSMemLocationAA.isAssumedReadNone())
6237       return NO_LOCATIONS;
6238 
6239     if (ICSMemLocationAA.isAssumedInaccessibleMemOnly()) {
6240       updateStateAndAccessesMap(AccessedLocs, AccessKindAccessesMap,
6241                                 NO_INACCESSIBLE_MEM, &I, nullptr, Changed);
6242       return AccessedLocs.getAssumed();
6243     }
6244 
6245     uint32_t ICSAssumedNotAccessedLocs =
6246         ICSMemLocationAA.getAssumedNotAccessedLocation();
6247 
6248     // Set the argmemonly and global bit as we handle them separately below.
6249     uint32_t ICSAssumedNotAccessedLocsNoArgMem =
6250         ICSAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
6251 
6252     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
6253       if (ICSAssumedNotAccessedLocsNoArgMem & CurMLK)
6254         continue;
6255       updateStateAndAccessesMap(AccessedLocs, AccessKindAccessesMap, CurMLK, &I,
6256                                 nullptr, Changed);
6257     }
6258 
6259     // Now handle global memory if it might be accessed. This is slightly tricky
6260     // as NO_GLOBAL_MEM has multiple bits set.
6261     bool HasGlobalAccesses = ((~ICSAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
6262     if (HasGlobalAccesses) {
6263       auto AccessPred = [&](const Instruction *, const Value *Ptr,
6264                             AccessKind Kind, MemoryLocationsKind MLK) {
6265         updateStateAndAccessesMap(AccessedLocs, AccessKindAccessesMap, MLK, &I,
6266                                   Ptr, Changed);
6267         return true;
6268       };
6269       if (!ICSMemLocationAA.checkForAllAccessesToMemoryKind(
6270               AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false)))
6271         return AccessedLocs.getWorstState();
6272     }
6273 
6274     LLVM_DEBUG(
6275         dbgs() << "[AAMemoryLocation] Accessed state before argument handling: "
6276                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
6277 
6278     // Now handle argument memory if it might be accessed.
6279     bool HasArgAccesses = ((~ICSAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
6280     if (HasArgAccesses) {
6281       for (unsigned ArgNo = 0, e = ICS.getNumArgOperands(); ArgNo < e;
6282            ++ArgNo) {
6283 
6284         // Skip non-pointer arguments.
6285         const Value *ArgOp = ICS.getArgOperand(ArgNo);
6286         if (!ArgOp->getType()->isPtrOrPtrVectorTy())
6287           continue;
6288 
6289         // Skip readnone arguments.
6290         const IRPosition &ArgOpIRP = IRPosition::callsite_argument(ICS, ArgNo);
6291         const auto &ArgOpMemLocationAA = A.getAAFor<AAMemoryBehavior>(
6292             *this, ArgOpIRP, /* TrackDependence */ true, DepClassTy::OPTIONAL);
6293 
6294         if (ArgOpMemLocationAA.isAssumedReadNone())
6295           continue;
6296 
6297         // Categorize potentially accessed pointer arguments as if there was an
6298         // access instruction with them as pointer.
6299         categorizePtrValue(A, I, *ArgOp, AccessedLocs, Changed);
6300       }
6301     }
6302 
6303     LLVM_DEBUG(
6304         dbgs() << "[AAMemoryLocation] Accessed state after argument handling: "
6305                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
6306 
6307     return AccessedLocs.getAssumed();
6308   }
6309 
6310   if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) {
6311     LLVM_DEBUG(
6312         dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: "
6313                << I << " [" << *Ptr << "]\n");
6314     categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed);
6315     return AccessedLocs.getAssumed();
6316   }
6317 
6318   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: "
6319                     << I << "\n");
6320   updateStateAndAccessesMap(AccessedLocs, AccessKindAccessesMap, NO_UNKOWN_MEM,
6321                             &I, nullptr, Changed);
6322   return AccessedLocs.getAssumed();
6323 }
6324 
6325 /// An AA to represent the memory behavior function attributes.
6326 struct AAMemoryLocationFunction final : public AAMemoryLocationImpl {
6327   AAMemoryLocationFunction(const IRPosition &IRP) : AAMemoryLocationImpl(IRP) {}
6328 
6329   /// See AbstractAttribute::updateImpl(Attributor &A).
6330   virtual ChangeStatus updateImpl(Attributor &A) override {
6331 
6332     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
6333         *this, getIRPosition(), /* TrackDependence */ false);
6334     if (MemBehaviorAA.isAssumedReadNone()) {
6335       if (MemBehaviorAA.isKnownReadNone())
6336         return indicateOptimisticFixpoint();
6337       assert(isAssumedReadNone() &&
6338              "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
6339       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
6340       return ChangeStatus::UNCHANGED;
6341     }
6342 
6343     // The current assumed state used to determine a change.
6344     auto AssumedState = getAssumed();
6345     bool Changed = false;
6346 
6347     auto CheckRWInst = [&](Instruction &I) {
6348       MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed);
6349       LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I
6350                         << ": " << getMemoryLocationsAsStr(MLK) << "\n");
6351       removeAssumedBits(inverseLocation(MLK, false, false));
6352       return true;
6353     };
6354 
6355     if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this))
6356       return indicatePessimisticFixpoint();
6357 
6358     Changed |= AssumedState != getAssumed();
6359     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
6360   }
6361 
6362   /// See AbstractAttribute::trackStatistics()
6363   void trackStatistics() const override {
6364     if (isAssumedReadNone())
6365       STATS_DECLTRACK_FN_ATTR(readnone)
6366     else if (isAssumedArgMemOnly())
6367       STATS_DECLTRACK_FN_ATTR(argmemonly)
6368     else if (isAssumedInaccessibleMemOnly())
6369       STATS_DECLTRACK_FN_ATTR(inaccessiblememonly)
6370     else if (isAssumedInaccessibleOrArgMemOnly())
6371       STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly)
6372   }
6373 };
6374 
6375 /// AAMemoryLocation attribute for call sites.
6376 struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
6377   AAMemoryLocationCallSite(const IRPosition &IRP) : AAMemoryLocationImpl(IRP) {}
6378 
6379   /// See AbstractAttribute::initialize(...).
6380   void initialize(Attributor &A) override {
6381     AAMemoryLocationImpl::initialize(A);
6382     Function *F = getAssociatedFunction();
6383     if (!F || !A.isFunctionIPOAmendable(*F))
6384       indicatePessimisticFixpoint();
6385   }
6386 
6387   /// See AbstractAttribute::updateImpl(...).
6388   ChangeStatus updateImpl(Attributor &A) override {
6389     // TODO: Once we have call site specific value information we can provide
6390     //       call site specific liveness liveness information and then it makes
6391     //       sense to specialize attributes for call sites arguments instead of
6392     //       redirecting requests to the callee argument.
6393     Function *F = getAssociatedFunction();
6394     const IRPosition &FnPos = IRPosition::function(*F);
6395     auto &FnAA = A.getAAFor<AAMemoryLocation>(*this, FnPos);
6396     bool Changed = false;
6397     auto AccessPred = [&](const Instruction *I, const Value *Ptr,
6398                           AccessKind Kind, MemoryLocationsKind MLK) {
6399       updateStateAndAccessesMap(getState(), AccessKindAccessesMap, MLK, I, Ptr,
6400                                 Changed);
6401       return true;
6402     };
6403     if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
6404       return indicatePessimisticFixpoint();
6405     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
6406   }
6407 
6408   /// See AbstractAttribute::trackStatistics()
6409   void trackStatistics() const override {
6410     if (isAssumedReadNone())
6411       STATS_DECLTRACK_CS_ATTR(readnone)
6412   }
6413 };
6414 
6415 /// ------------------ Value Constant Range Attribute -------------------------
6416 
6417 struct AAValueConstantRangeImpl : AAValueConstantRange {
6418   using StateType = IntegerRangeState;
6419   AAValueConstantRangeImpl(const IRPosition &IRP) : AAValueConstantRange(IRP) {}
6420 
6421   /// See AbstractAttribute::getAsStr().
6422   const std::string getAsStr() const override {
6423     std::string Str;
6424     llvm::raw_string_ostream OS(Str);
6425     OS << "range(" << getBitWidth() << ")<";
6426     getKnown().print(OS);
6427     OS << " / ";
6428     getAssumed().print(OS);
6429     OS << ">";
6430     return OS.str();
6431   }
6432 
6433   /// Helper function to get a SCEV expr for the associated value at program
6434   /// point \p I.
6435   const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const {
6436     if (!getAnchorScope())
6437       return nullptr;
6438 
6439     ScalarEvolution *SE =
6440         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
6441             *getAnchorScope());
6442 
6443     LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
6444         *getAnchorScope());
6445 
6446     if (!SE || !LI)
6447       return nullptr;
6448 
6449     const SCEV *S = SE->getSCEV(&getAssociatedValue());
6450     if (!I)
6451       return S;
6452 
6453     return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent()));
6454   }
6455 
6456   /// Helper function to get a range from SCEV for the associated value at
6457   /// program point \p I.
6458   ConstantRange getConstantRangeFromSCEV(Attributor &A,
6459                                          const Instruction *I = nullptr) const {
6460     if (!getAnchorScope())
6461       return getWorstState(getBitWidth());
6462 
6463     ScalarEvolution *SE =
6464         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
6465             *getAnchorScope());
6466 
6467     const SCEV *S = getSCEV(A, I);
6468     if (!SE || !S)
6469       return getWorstState(getBitWidth());
6470 
6471     return SE->getUnsignedRange(S);
6472   }
6473 
6474   /// Helper function to get a range from LVI for the associated value at
6475   /// program point \p I.
6476   ConstantRange
6477   getConstantRangeFromLVI(Attributor &A,
6478                           const Instruction *CtxI = nullptr) const {
6479     if (!getAnchorScope())
6480       return getWorstState(getBitWidth());
6481 
6482     LazyValueInfo *LVI =
6483         A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
6484             *getAnchorScope());
6485 
6486     if (!LVI || !CtxI)
6487       return getWorstState(getBitWidth());
6488     return LVI->getConstantRange(&getAssociatedValue(),
6489                                  const_cast<BasicBlock *>(CtxI->getParent()),
6490                                  const_cast<Instruction *>(CtxI));
6491   }
6492 
6493   /// See AAValueConstantRange::getKnownConstantRange(..).
6494   ConstantRange
6495   getKnownConstantRange(Attributor &A,
6496                         const Instruction *CtxI = nullptr) const override {
6497     if (!CtxI || CtxI == getCtxI())
6498       return getKnown();
6499 
6500     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
6501     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
6502     return getKnown().intersectWith(SCEVR).intersectWith(LVIR);
6503   }
6504 
6505   /// See AAValueConstantRange::getAssumedConstantRange(..).
6506   ConstantRange
6507   getAssumedConstantRange(Attributor &A,
6508                           const Instruction *CtxI = nullptr) const override {
6509     // TODO: Make SCEV use Attributor assumption.
6510     //       We may be able to bound a variable range via assumptions in
6511     //       Attributor. ex.) If x is assumed to be in [1, 3] and y is known to
6512     //       evolve to x^2 + x, then we can say that y is in [2, 12].
6513 
6514     if (!CtxI || CtxI == getCtxI())
6515       return getAssumed();
6516 
6517     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
6518     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
6519     return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
6520   }
6521 
6522   /// See AbstractAttribute::initialize(..).
6523   void initialize(Attributor &A) override {
6524     // Intersect a range given by SCEV.
6525     intersectKnown(getConstantRangeFromSCEV(A, getCtxI()));
6526 
6527     // Intersect a range given by LVI.
6528     intersectKnown(getConstantRangeFromLVI(A, getCtxI()));
6529   }
6530 
6531   /// Helper function to create MDNode for range metadata.
6532   static MDNode *
6533   getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx,
6534                             const ConstantRange &AssumedConstantRange) {
6535     Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get(
6536                                   Ty, AssumedConstantRange.getLower())),
6537                               ConstantAsMetadata::get(ConstantInt::get(
6538                                   Ty, AssumedConstantRange.getUpper()))};
6539     return MDNode::get(Ctx, LowAndHigh);
6540   }
6541 
6542   /// Return true if \p Assumed is included in \p KnownRanges.
6543   static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) {
6544 
6545     if (Assumed.isFullSet())
6546       return false;
6547 
6548     if (!KnownRanges)
6549       return true;
6550 
6551     // If multiple ranges are annotated in IR, we give up to annotate assumed
6552     // range for now.
6553 
6554     // TODO:  If there exists a known range which containts assumed range, we
6555     // can say assumed range is better.
6556     if (KnownRanges->getNumOperands() > 2)
6557       return false;
6558 
6559     ConstantInt *Lower =
6560         mdconst::extract<ConstantInt>(KnownRanges->getOperand(0));
6561     ConstantInt *Upper =
6562         mdconst::extract<ConstantInt>(KnownRanges->getOperand(1));
6563 
6564     ConstantRange Known(Lower->getValue(), Upper->getValue());
6565     return Known.contains(Assumed) && Known != Assumed;
6566   }
6567 
6568   /// Helper function to set range metadata.
6569   static bool
6570   setRangeMetadataIfisBetterRange(Instruction *I,
6571                                   const ConstantRange &AssumedConstantRange) {
6572     auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range);
6573     if (isBetterRange(AssumedConstantRange, OldRangeMD)) {
6574       if (!AssumedConstantRange.isEmptySet()) {
6575         I->setMetadata(LLVMContext::MD_range,
6576                        getMDNodeForConstantRange(I->getType(), I->getContext(),
6577                                                  AssumedConstantRange));
6578         return true;
6579       }
6580     }
6581     return false;
6582   }
6583 
6584   /// See AbstractAttribute::manifest()
6585   ChangeStatus manifest(Attributor &A) override {
6586     ChangeStatus Changed = ChangeStatus::UNCHANGED;
6587     ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
6588     assert(!AssumedConstantRange.isFullSet() && "Invalid state");
6589 
6590     auto &V = getAssociatedValue();
6591     if (!AssumedConstantRange.isEmptySet() &&
6592         !AssumedConstantRange.isSingleElement()) {
6593       if (Instruction *I = dyn_cast<Instruction>(&V))
6594         if (isa<CallInst>(I) || isa<LoadInst>(I))
6595           if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange))
6596             Changed = ChangeStatus::CHANGED;
6597     }
6598 
6599     return Changed;
6600   }
6601 };
6602 
6603 struct AAValueConstantRangeArgument final
6604     : AAArgumentFromCallSiteArguments<
6605           AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState> {
6606   using Base = AAArgumentFromCallSiteArguments<
6607       AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState>;
6608   AAValueConstantRangeArgument(const IRPosition &IRP) : Base(IRP) {}
6609 
6610   /// See AbstractAttribute::initialize(..).
6611   void initialize(Attributor &A) override {
6612     if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
6613       indicatePessimisticFixpoint();
6614     } else {
6615       Base::initialize(A);
6616     }
6617   }
6618 
6619   /// See AbstractAttribute::trackStatistics()
6620   void trackStatistics() const override {
6621     STATS_DECLTRACK_ARG_ATTR(value_range)
6622   }
6623 };
6624 
6625 struct AAValueConstantRangeReturned
6626     : AAReturnedFromReturnedValues<AAValueConstantRange,
6627                                    AAValueConstantRangeImpl> {
6628   using Base = AAReturnedFromReturnedValues<AAValueConstantRange,
6629                                             AAValueConstantRangeImpl>;
6630   AAValueConstantRangeReturned(const IRPosition &IRP) : Base(IRP) {}
6631 
6632   /// See AbstractAttribute::initialize(...).
6633   void initialize(Attributor &A) override {}
6634 
6635   /// See AbstractAttribute::trackStatistics()
6636   void trackStatistics() const override {
6637     STATS_DECLTRACK_FNRET_ATTR(value_range)
6638   }
6639 };
6640 
6641 struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
6642   AAValueConstantRangeFloating(const IRPosition &IRP)
6643       : AAValueConstantRangeImpl(IRP) {}
6644 
6645   /// See AbstractAttribute::initialize(...).
6646   void initialize(Attributor &A) override {
6647     AAValueConstantRangeImpl::initialize(A);
6648     Value &V = getAssociatedValue();
6649 
6650     if (auto *C = dyn_cast<ConstantInt>(&V)) {
6651       unionAssumed(ConstantRange(C->getValue()));
6652       indicateOptimisticFixpoint();
6653       return;
6654     }
6655 
6656     if (isa<UndefValue>(&V)) {
6657       // Collapse the undef state to 0.
6658       unionAssumed(ConstantRange(APInt(getBitWidth(), 0)));
6659       indicateOptimisticFixpoint();
6660       return;
6661     }
6662 
6663     if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V))
6664       return;
6665     // If it is a load instruction with range metadata, use it.
6666     if (LoadInst *LI = dyn_cast<LoadInst>(&V))
6667       if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
6668         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
6669         return;
6670       }
6671 
6672     // We can work with PHI and select instruction as we traverse their operands
6673     // during update.
6674     if (isa<SelectInst>(V) || isa<PHINode>(V))
6675       return;
6676 
6677     // Otherwise we give up.
6678     indicatePessimisticFixpoint();
6679 
6680     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: "
6681                       << getAssociatedValue() << "\n");
6682   }
6683 
6684   bool calculateBinaryOperator(
6685       Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T,
6686       const Instruction *CtxI,
6687       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
6688     Value *LHS = BinOp->getOperand(0);
6689     Value *RHS = BinOp->getOperand(1);
6690     // TODO: Allow non integers as well.
6691     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
6692       return false;
6693 
6694     auto &LHSAA =
6695         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*LHS));
6696     QuerriedAAs.push_back(&LHSAA);
6697     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
6698 
6699     auto &RHSAA =
6700         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*RHS));
6701     QuerriedAAs.push_back(&RHSAA);
6702     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
6703 
6704     auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange);
6705 
6706     T.unionAssumed(AssumedRange);
6707 
6708     // TODO: Track a known state too.
6709 
6710     return T.isValidState();
6711   }
6712 
6713   bool calculateCastInst(
6714       Attributor &A, CastInst *CastI, IntegerRangeState &T,
6715       const Instruction *CtxI,
6716       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
6717     assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!");
6718     // TODO: Allow non integers as well.
6719     Value &OpV = *CastI->getOperand(0);
6720     if (!OpV.getType()->isIntegerTy())
6721       return false;
6722 
6723     auto &OpAA =
6724         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(OpV));
6725     QuerriedAAs.push_back(&OpAA);
6726     T.unionAssumed(
6727         OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth()));
6728     return T.isValidState();
6729   }
6730 
6731   bool
6732   calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T,
6733                    const Instruction *CtxI,
6734                    SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
6735     Value *LHS = CmpI->getOperand(0);
6736     Value *RHS = CmpI->getOperand(1);
6737     // TODO: Allow non integers as well.
6738     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
6739       return false;
6740 
6741     auto &LHSAA =
6742         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*LHS));
6743     QuerriedAAs.push_back(&LHSAA);
6744     auto &RHSAA =
6745         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*RHS));
6746     QuerriedAAs.push_back(&RHSAA);
6747 
6748     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
6749     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
6750 
6751     // If one of them is empty set, we can't decide.
6752     if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
6753       return true;
6754 
6755     bool MustTrue = false, MustFalse = false;
6756 
6757     auto AllowedRegion =
6758         ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange);
6759 
6760     auto SatisfyingRegion = ConstantRange::makeSatisfyingICmpRegion(
6761         CmpI->getPredicate(), RHSAARange);
6762 
6763     if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
6764       MustFalse = true;
6765 
6766     if (SatisfyingRegion.contains(LHSAARange))
6767       MustTrue = true;
6768 
6769     assert((!MustTrue || !MustFalse) &&
6770            "Either MustTrue or MustFalse should be false!");
6771 
6772     if (MustTrue)
6773       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1)));
6774     else if (MustFalse)
6775       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0)));
6776     else
6777       T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true));
6778 
6779     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA
6780                       << " " << RHSAA << "\n");
6781 
6782     // TODO: Track a known state too.
6783     return T.isValidState();
6784   }
6785 
6786   /// See AbstractAttribute::updateImpl(...).
6787   ChangeStatus updateImpl(Attributor &A) override {
6788     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
6789                             IntegerRangeState &T, bool Stripped) -> bool {
6790       Instruction *I = dyn_cast<Instruction>(&V);
6791       if (!I || isa<CallBase>(I)) {
6792 
6793         // If the value is not instruction, we query AA to Attributor.
6794         const auto &AA =
6795             A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(V));
6796 
6797         // Clamp operator is not used to utilize a program point CtxI.
6798         T.unionAssumed(AA.getAssumedConstantRange(A, CtxI));
6799 
6800         return T.isValidState();
6801       }
6802 
6803       SmallVector<const AAValueConstantRange *, 4> QuerriedAAs;
6804       if (auto *BinOp = dyn_cast<BinaryOperator>(I)) {
6805         if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs))
6806           return false;
6807       } else if (auto *CmpI = dyn_cast<CmpInst>(I)) {
6808         if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs))
6809           return false;
6810       } else if (auto *CastI = dyn_cast<CastInst>(I)) {
6811         if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs))
6812           return false;
6813       } else {
6814         // Give up with other instructions.
6815         // TODO: Add other instructions
6816 
6817         T.indicatePessimisticFixpoint();
6818         return false;
6819       }
6820 
6821       // Catch circular reasoning in a pessimistic way for now.
6822       // TODO: Check how the range evolves and if we stripped anything, see also
6823       //       AADereferenceable or AAAlign for similar situations.
6824       for (const AAValueConstantRange *QueriedAA : QuerriedAAs) {
6825         if (QueriedAA != this)
6826           continue;
6827         // If we are in a stady state we do not need to worry.
6828         if (T.getAssumed() == getState().getAssumed())
6829           continue;
6830         T.indicatePessimisticFixpoint();
6831       }
6832 
6833       return T.isValidState();
6834     };
6835 
6836     IntegerRangeState T(getBitWidth());
6837 
6838     if (!genericValueTraversal<AAValueConstantRange, IntegerRangeState>(
6839             A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
6840       return indicatePessimisticFixpoint();
6841 
6842     return clampStateAndIndicateChange(getState(), T);
6843   }
6844 
6845   /// See AbstractAttribute::trackStatistics()
6846   void trackStatistics() const override {
6847     STATS_DECLTRACK_FLOATING_ATTR(value_range)
6848   }
6849 };
6850 
6851 struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
6852   AAValueConstantRangeFunction(const IRPosition &IRP)
6853       : AAValueConstantRangeImpl(IRP) {}
6854 
6855   /// See AbstractAttribute::initialize(...).
6856   ChangeStatus updateImpl(Attributor &A) override {
6857     llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will "
6858                      "not be called");
6859   }
6860 
6861   /// See AbstractAttribute::trackStatistics()
6862   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) }
6863 };
6864 
6865 struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
6866   AAValueConstantRangeCallSite(const IRPosition &IRP)
6867       : AAValueConstantRangeFunction(IRP) {}
6868 
6869   /// See AbstractAttribute::trackStatistics()
6870   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) }
6871 };
6872 
6873 struct AAValueConstantRangeCallSiteReturned
6874     : AACallSiteReturnedFromReturned<AAValueConstantRange,
6875                                      AAValueConstantRangeImpl> {
6876   AAValueConstantRangeCallSiteReturned(const IRPosition &IRP)
6877       : AACallSiteReturnedFromReturned<AAValueConstantRange,
6878                                        AAValueConstantRangeImpl>(IRP) {}
6879 
6880   /// See AbstractAttribute::initialize(...).
6881   void initialize(Attributor &A) override {
6882     // If it is a load instruction with range metadata, use the metadata.
6883     if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue()))
6884       if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range))
6885         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
6886 
6887     AAValueConstantRangeImpl::initialize(A);
6888   }
6889 
6890   /// See AbstractAttribute::trackStatistics()
6891   void trackStatistics() const override {
6892     STATS_DECLTRACK_CSRET_ATTR(value_range)
6893   }
6894 };
6895 struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
6896   AAValueConstantRangeCallSiteArgument(const IRPosition &IRP)
6897       : AAValueConstantRangeFloating(IRP) {}
6898 
6899   /// See AbstractAttribute::trackStatistics()
6900   void trackStatistics() const override {
6901     STATS_DECLTRACK_CSARG_ATTR(value_range)
6902   }
6903 };
6904 
6905 const char AAReturnedValues::ID = 0;
6906 const char AANoUnwind::ID = 0;
6907 const char AANoSync::ID = 0;
6908 const char AANoFree::ID = 0;
6909 const char AANonNull::ID = 0;
6910 const char AANoRecurse::ID = 0;
6911 const char AAWillReturn::ID = 0;
6912 const char AAUndefinedBehavior::ID = 0;
6913 const char AANoAlias::ID = 0;
6914 const char AAReachability::ID = 0;
6915 const char AANoReturn::ID = 0;
6916 const char AAIsDead::ID = 0;
6917 const char AADereferenceable::ID = 0;
6918 const char AAAlign::ID = 0;
6919 const char AANoCapture::ID = 0;
6920 const char AAValueSimplify::ID = 0;
6921 const char AAHeapToStack::ID = 0;
6922 const char AAPrivatizablePtr::ID = 0;
6923 const char AAMemoryBehavior::ID = 0;
6924 const char AAMemoryLocation::ID = 0;
6925 const char AAValueConstantRange::ID = 0;
6926 
6927 // Macro magic to create the static generator function for attributes that
6928 // follow the naming scheme.
6929 
6930 #define SWITCH_PK_INV(CLASS, PK, POS_NAME)                                     \
6931   case IRPosition::PK:                                                         \
6932     llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
6933 
6934 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX)                               \
6935   case IRPosition::PK:                                                         \
6936     AA = new (A.Allocator) CLASS##SUFFIX(IRP);                                 \
6937     break;
6938 
6939 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                 \
6940   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
6941     CLASS *AA = nullptr;                                                       \
6942     switch (IRP.getPositionKind()) {                                           \
6943       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
6944       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
6945       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
6946       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
6947       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
6948       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
6949       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
6950       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
6951     }                                                                          \
6952     return *AA;                                                                \
6953   }
6954 
6955 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                    \
6956   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
6957     CLASS *AA = nullptr;                                                       \
6958     switch (IRP.getPositionKind()) {                                           \
6959       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
6960       SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function")                           \
6961       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
6962       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
6963       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
6964       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
6965       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
6966       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
6967     }                                                                          \
6968     return *AA;                                                                \
6969   }
6970 
6971 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                      \
6972   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
6973     CLASS *AA = nullptr;                                                       \
6974     switch (IRP.getPositionKind()) {                                           \
6975       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
6976       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
6977       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
6978       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
6979       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
6980       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
6981       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
6982       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
6983     }                                                                          \
6984     return *AA;                                                                \
6985   }
6986 
6987 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)            \
6988   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
6989     CLASS *AA = nullptr;                                                       \
6990     switch (IRP.getPositionKind()) {                                           \
6991       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
6992       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
6993       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
6994       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
6995       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
6996       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
6997       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
6998       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
6999     }                                                                          \
7000     return *AA;                                                                \
7001   }
7002 
7003 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                  \
7004   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7005     CLASS *AA = nullptr;                                                       \
7006     switch (IRP.getPositionKind()) {                                           \
7007       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7008       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
7009       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7010       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
7011       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
7012       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
7013       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
7014       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
7015     }                                                                          \
7016     return *AA;                                                                \
7017   }
7018 
7019 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind)
7020 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync)
7021 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse)
7022 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn)
7023 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn)
7024 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues)
7025 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation)
7026 
7027 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull)
7028 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias)
7029 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr)
7030 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable)
7031 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign)
7032 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture)
7033 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange)
7034 
7035 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify)
7036 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead)
7037 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree)
7038 
7039 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack)
7040 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability)
7041 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior)
7042 
7043 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior)
7044 
7045 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
7046 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
7047 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
7048 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
7049 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
7050 #undef SWITCH_PK_CREATE
7051 #undef SWITCH_PK_INV
7052