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