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 || !ArgVal->getType()->isPointerTy())
2023           continue;
2024         IRPosition CalleeArgumentIRP = IRPosition::callsite_argument(CB, idx);
2025         if (!CalleeArgumentIRP.hasAttr({Attribute::NoUndef}))
2026           continue;
2027         auto &NonNullAA = A.getAAFor<AANonNull>(*this, CalleeArgumentIRP);
2028         if (!NonNullAA.isKnownNonNull())
2029           continue;
2030         const auto &ValueSimplifyAA =
2031             A.getAAFor<AAValueSimplify>(*this, IRPosition::value(*ArgVal));
2032         Optional<Value *> SimplifiedVal =
2033             ValueSimplifyAA.getAssumedSimplifiedValue(A);
2034 
2035         if (!ValueSimplifyAA.isKnown())
2036           continue;
2037         // Here, we handle three cases.
2038         //   (1) Not having a value means it is dead. (we can replace the value
2039         //       with undef)
2040         //   (2) Simplified to null pointer. The argument is a poison value and
2041         //       violate noundef attribute.
2042         //   (3) Simplified to undef. The argument violate noundef attriubte.
2043         if (!SimplifiedVal.hasValue() ||
2044             isa<ConstantPointerNull>(*SimplifiedVal.getValue()) ||
2045             isa<UndefValue>(*SimplifiedVal.getValue())) {
2046           KnownUBInsts.insert(&I);
2047           return true;
2048         }
2049       }
2050       return true;
2051     };
2052 
2053     auto InspectReturnInstForUB =
2054         [&](Value &V, const SmallSetVector<ReturnInst *, 4> RetInsts) {
2055           // Check if a return instruction always cause UB or not
2056           // Note: It is guaranteed that the returned position of the anchor
2057           //       scope has noundef attribute when this is called.
2058 
2059           // When the returned position has noundef attriubte, UB occur in the
2060           // following cases.
2061           //   (1) Returned value is known to be undef.
2062           //   (2) The value is known to be a null pointer and the returned
2063           //       position has nonnull attribute (because the returned value is
2064           //       poison).
2065           // Note: This callback is not called for a dead returned value because
2066           //       such values are ignored in
2067           //       checkForAllReturnedValuesAndReturnedInsts.
2068           bool FoundUB = false;
2069           if (isa<UndefValue>(V)) {
2070             FoundUB = true;
2071           } else {
2072             if (isa<ConstantPointerNull>(V)) {
2073               auto &NonNullAA = A.getAAFor<AANonNull>(
2074                   *this, IRPosition::returned(*getAnchorScope()));
2075               if (NonNullAA.isKnownNonNull())
2076                 FoundUB = true;
2077             }
2078           }
2079 
2080           if (FoundUB)
2081             for (ReturnInst *RI : RetInsts)
2082               KnownUBInsts.insert(RI);
2083           return true;
2084         };
2085 
2086     A.checkForAllInstructions(InspectMemAccessInstForUB, *this,
2087                               {Instruction::Load, Instruction::Store,
2088                                Instruction::AtomicCmpXchg,
2089                                Instruction::AtomicRMW},
2090                               /* CheckBBLivenessOnly */ true);
2091     A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::Br},
2092                               /* CheckBBLivenessOnly */ true);
2093     A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *this);
2094 
2095     // If the returned position of the anchor scope has noundef attriubte, check
2096     // all returned instructions.
2097     // TODO: If AANoUndef is implemented, ask it here.
2098     if (IRPosition::returned(*getAnchorScope()).hasAttr({Attribute::NoUndef}))
2099       A.checkForAllReturnedValuesAndReturnInsts(InspectReturnInstForUB, *this);
2100 
2101     if (NoUBPrevSize != AssumedNoUBInsts.size() ||
2102         UBPrevSize != KnownUBInsts.size())
2103       return ChangeStatus::CHANGED;
2104     return ChangeStatus::UNCHANGED;
2105   }
2106 
2107   bool isKnownToCauseUB(Instruction *I) const override {
2108     return KnownUBInsts.count(I);
2109   }
2110 
2111   bool isAssumedToCauseUB(Instruction *I) const override {
2112     // In simple words, if an instruction is not in the assumed to _not_
2113     // cause UB, then it is assumed UB (that includes those
2114     // in the KnownUBInsts set). The rest is boilerplate
2115     // is to ensure that it is one of the instructions we test
2116     // for UB.
2117 
2118     switch (I->getOpcode()) {
2119     case Instruction::Load:
2120     case Instruction::Store:
2121     case Instruction::AtomicCmpXchg:
2122     case Instruction::AtomicRMW:
2123       return !AssumedNoUBInsts.count(I);
2124     case Instruction::Br: {
2125       auto BrInst = cast<BranchInst>(I);
2126       if (BrInst->isUnconditional())
2127         return false;
2128       return !AssumedNoUBInsts.count(I);
2129     } break;
2130     default:
2131       return false;
2132     }
2133     return false;
2134   }
2135 
2136   ChangeStatus manifest(Attributor &A) override {
2137     if (KnownUBInsts.empty())
2138       return ChangeStatus::UNCHANGED;
2139     for (Instruction *I : KnownUBInsts)
2140       A.changeToUnreachableAfterManifest(I);
2141     return ChangeStatus::CHANGED;
2142   }
2143 
2144   /// See AbstractAttribute::getAsStr()
2145   const std::string getAsStr() const override {
2146     return getAssumed() ? "undefined-behavior" : "no-ub";
2147   }
2148 
2149   /// Note: The correctness of this analysis depends on the fact that the
2150   /// following 2 sets will stop changing after some point.
2151   /// "Change" here means that their size changes.
2152   /// The size of each set is monotonically increasing
2153   /// (we only add items to them) and it is upper bounded by the number of
2154   /// instructions in the processed function (we can never save more
2155   /// elements in either set than this number). Hence, at some point,
2156   /// they will stop increasing.
2157   /// Consequently, at some point, both sets will have stopped
2158   /// changing, effectively making the analysis reach a fixpoint.
2159 
2160   /// Note: These 2 sets are disjoint and an instruction can be considered
2161   /// one of 3 things:
2162   /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in
2163   ///    the KnownUBInsts set.
2164   /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior
2165   ///    has a reason to assume it).
2166   /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior
2167   ///    could not find a reason to assume or prove that it can cause UB,
2168   ///    hence it assumes it doesn't. We have a set for these instructions
2169   ///    so that we don't reprocess them in every update.
2170   ///    Note however that instructions in this set may cause UB.
2171 
2172 protected:
2173   /// A set of all live instructions _known_ to cause UB.
2174   SmallPtrSet<Instruction *, 8> KnownUBInsts;
2175 
2176 private:
2177   /// A set of all the (live) instructions that are assumed to _not_ cause UB.
2178   SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
2179 
2180   // Should be called on updates in which if we're processing an instruction
2181   // \p I that depends on a value \p V, one of the following has to happen:
2182   // - If the value is assumed, then stop.
2183   // - If the value is known but undef, then consider it UB.
2184   // - Otherwise, do specific processing with the simplified value.
2185   // We return None in the first 2 cases to signify that an appropriate
2186   // action was taken and the caller should stop.
2187   // Otherwise, we return the simplified value that the caller should
2188   // use for specific processing.
2189   Optional<Value *> stopOnUndefOrAssumed(Attributor &A, const Value *V,
2190                                          Instruction *I) {
2191     const auto &ValueSimplifyAA =
2192         A.getAAFor<AAValueSimplify>(*this, IRPosition::value(*V));
2193     Optional<Value *> SimplifiedV =
2194         ValueSimplifyAA.getAssumedSimplifiedValue(A);
2195     if (!ValueSimplifyAA.isKnown()) {
2196       // Don't depend on assumed values.
2197       return llvm::None;
2198     }
2199     if (!SimplifiedV.hasValue()) {
2200       // If it is known (which we tested above) but it doesn't have a value,
2201       // then we can assume `undef` and hence the instruction is UB.
2202       KnownUBInsts.insert(I);
2203       return llvm::None;
2204     }
2205     Value *Val = SimplifiedV.getValue();
2206     if (isa<UndefValue>(Val)) {
2207       KnownUBInsts.insert(I);
2208       return llvm::None;
2209     }
2210     return Val;
2211   }
2212 };
2213 
2214 struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
2215   AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A)
2216       : AAUndefinedBehaviorImpl(IRP, A) {}
2217 
2218   /// See AbstractAttribute::trackStatistics()
2219   void trackStatistics() const override {
2220     STATS_DECL(UndefinedBehaviorInstruction, Instruction,
2221                "Number of instructions known to have UB");
2222     BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) +=
2223         KnownUBInsts.size();
2224   }
2225 };
2226 
2227 /// ------------------------ Will-Return Attributes ----------------------------
2228 
2229 // Helper function that checks whether a function has any cycle which we don't
2230 // know if it is bounded or not.
2231 // Loops with maximum trip count are considered bounded, any other cycle not.
2232 static bool mayContainUnboundedCycle(Function &F, Attributor &A) {
2233   ScalarEvolution *SE =
2234       A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F);
2235   LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F);
2236   // If either SCEV or LoopInfo is not available for the function then we assume
2237   // any cycle to be unbounded cycle.
2238   // We use scc_iterator which uses Tarjan algorithm to find all the maximal
2239   // SCCs.To detect if there's a cycle, we only need to find the maximal ones.
2240   if (!SE || !LI) {
2241     for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI)
2242       if (SCCI.hasCycle())
2243         return true;
2244     return false;
2245   }
2246 
2247   // If there's irreducible control, the function may contain non-loop cycles.
2248   if (mayContainIrreducibleControl(F, LI))
2249     return true;
2250 
2251   // Any loop that does not have a max trip count is considered unbounded cycle.
2252   for (auto *L : LI->getLoopsInPreorder()) {
2253     if (!SE->getSmallConstantMaxTripCount(L))
2254       return true;
2255   }
2256   return false;
2257 }
2258 
2259 struct AAWillReturnImpl : public AAWillReturn {
2260   AAWillReturnImpl(const IRPosition &IRP, Attributor &A)
2261       : AAWillReturn(IRP, A) {}
2262 
2263   /// See AbstractAttribute::initialize(...).
2264   void initialize(Attributor &A) override {
2265     AAWillReturn::initialize(A);
2266 
2267     Function *F = getAnchorScope();
2268     if (!F || !A.isFunctionIPOAmendable(*F) || mayContainUnboundedCycle(*F, A))
2269       indicatePessimisticFixpoint();
2270   }
2271 
2272   /// See AbstractAttribute::updateImpl(...).
2273   ChangeStatus updateImpl(Attributor &A) override {
2274     auto CheckForWillReturn = [&](Instruction &I) {
2275       IRPosition IPos = IRPosition::callsite_function(cast<CallBase>(I));
2276       const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos);
2277       if (WillReturnAA.isKnownWillReturn())
2278         return true;
2279       if (!WillReturnAA.isAssumedWillReturn())
2280         return false;
2281       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos);
2282       return NoRecurseAA.isAssumedNoRecurse();
2283     };
2284 
2285     if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this))
2286       return indicatePessimisticFixpoint();
2287 
2288     return ChangeStatus::UNCHANGED;
2289   }
2290 
2291   /// See AbstractAttribute::getAsStr()
2292   const std::string getAsStr() const override {
2293     return getAssumed() ? "willreturn" : "may-noreturn";
2294   }
2295 };
2296 
2297 struct AAWillReturnFunction final : AAWillReturnImpl {
2298   AAWillReturnFunction(const IRPosition &IRP, Attributor &A)
2299       : AAWillReturnImpl(IRP, A) {}
2300 
2301   /// See AbstractAttribute::trackStatistics()
2302   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
2303 };
2304 
2305 /// WillReturn attribute deduction for a call sites.
2306 struct AAWillReturnCallSite final : AAWillReturnImpl {
2307   AAWillReturnCallSite(const IRPosition &IRP, Attributor &A)
2308       : AAWillReturnImpl(IRP, A) {}
2309 
2310   /// See AbstractAttribute::initialize(...).
2311   void initialize(Attributor &A) override {
2312     AAWillReturnImpl::initialize(A);
2313     Function *F = getAssociatedFunction();
2314     if (!F)
2315       indicatePessimisticFixpoint();
2316   }
2317 
2318   /// See AbstractAttribute::updateImpl(...).
2319   ChangeStatus updateImpl(Attributor &A) override {
2320     // TODO: Once we have call site specific value information we can provide
2321     //       call site specific liveness information and then it makes
2322     //       sense to specialize attributes for call sites arguments instead of
2323     //       redirecting requests to the callee argument.
2324     Function *F = getAssociatedFunction();
2325     const IRPosition &FnPos = IRPosition::function(*F);
2326     auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos);
2327     return clampStateAndIndicateChange(getState(), FnAA.getState());
2328   }
2329 
2330   /// See AbstractAttribute::trackStatistics()
2331   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); }
2332 };
2333 
2334 /// -------------------AAReachability Attribute--------------------------
2335 
2336 struct AAReachabilityImpl : AAReachability {
2337   AAReachabilityImpl(const IRPosition &IRP, Attributor &A)
2338       : AAReachability(IRP, A) {}
2339 
2340   const std::string getAsStr() const override {
2341     // TODO: Return the number of reachable queries.
2342     return "reachable";
2343   }
2344 
2345   /// See AbstractAttribute::initialize(...).
2346   void initialize(Attributor &A) override { indicatePessimisticFixpoint(); }
2347 
2348   /// See AbstractAttribute::updateImpl(...).
2349   ChangeStatus updateImpl(Attributor &A) override {
2350     return indicatePessimisticFixpoint();
2351   }
2352 };
2353 
2354 struct AAReachabilityFunction final : public AAReachabilityImpl {
2355   AAReachabilityFunction(const IRPosition &IRP, Attributor &A)
2356       : AAReachabilityImpl(IRP, A) {}
2357 
2358   /// See AbstractAttribute::trackStatistics()
2359   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(reachable); }
2360 };
2361 
2362 /// ------------------------ NoAlias Argument Attribute ------------------------
2363 
2364 struct AANoAliasImpl : AANoAlias {
2365   AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) {
2366     assert(getAssociatedType()->isPointerTy() &&
2367            "Noalias is a pointer attribute");
2368   }
2369 
2370   const std::string getAsStr() const override {
2371     return getAssumed() ? "noalias" : "may-alias";
2372   }
2373 };
2374 
2375 /// NoAlias attribute for a floating value.
2376 struct AANoAliasFloating final : AANoAliasImpl {
2377   AANoAliasFloating(const IRPosition &IRP, Attributor &A)
2378       : AANoAliasImpl(IRP, A) {}
2379 
2380   /// See AbstractAttribute::initialize(...).
2381   void initialize(Attributor &A) override {
2382     AANoAliasImpl::initialize(A);
2383     Value *Val = &getAssociatedValue();
2384     do {
2385       CastInst *CI = dyn_cast<CastInst>(Val);
2386       if (!CI)
2387         break;
2388       Value *Base = CI->getOperand(0);
2389       if (!Base->hasOneUse())
2390         break;
2391       Val = Base;
2392     } while (true);
2393 
2394     if (!Val->getType()->isPointerTy()) {
2395       indicatePessimisticFixpoint();
2396       return;
2397     }
2398 
2399     if (isa<AllocaInst>(Val))
2400       indicateOptimisticFixpoint();
2401     else if (isa<ConstantPointerNull>(Val) &&
2402              !NullPointerIsDefined(getAnchorScope(),
2403                                    Val->getType()->getPointerAddressSpace()))
2404       indicateOptimisticFixpoint();
2405     else if (Val != &getAssociatedValue()) {
2406       const auto &ValNoAliasAA =
2407           A.getAAFor<AANoAlias>(*this, IRPosition::value(*Val));
2408       if (ValNoAliasAA.isKnownNoAlias())
2409         indicateOptimisticFixpoint();
2410     }
2411   }
2412 
2413   /// See AbstractAttribute::updateImpl(...).
2414   ChangeStatus updateImpl(Attributor &A) override {
2415     // TODO: Implement this.
2416     return indicatePessimisticFixpoint();
2417   }
2418 
2419   /// See AbstractAttribute::trackStatistics()
2420   void trackStatistics() const override {
2421     STATS_DECLTRACK_FLOATING_ATTR(noalias)
2422   }
2423 };
2424 
2425 /// NoAlias attribute for an argument.
2426 struct AANoAliasArgument final
2427     : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
2428   using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
2429   AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
2430 
2431   /// See AbstractAttribute::initialize(...).
2432   void initialize(Attributor &A) override {
2433     Base::initialize(A);
2434     // See callsite argument attribute and callee argument attribute.
2435     if (hasAttr({Attribute::ByVal}))
2436       indicateOptimisticFixpoint();
2437   }
2438 
2439   /// See AbstractAttribute::update(...).
2440   ChangeStatus updateImpl(Attributor &A) override {
2441     // We have to make sure no-alias on the argument does not break
2442     // synchronization when this is a callback argument, see also [1] below.
2443     // If synchronization cannot be affected, we delegate to the base updateImpl
2444     // function, otherwise we give up for now.
2445 
2446     // If the function is no-sync, no-alias cannot break synchronization.
2447     const auto &NoSyncAA = A.getAAFor<AANoSync>(
2448         *this, IRPosition::function_scope(getIRPosition()));
2449     if (NoSyncAA.isAssumedNoSync())
2450       return Base::updateImpl(A);
2451 
2452     // If the argument is read-only, no-alias cannot break synchronization.
2453     const auto &MemBehaviorAA =
2454         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition());
2455     if (MemBehaviorAA.isAssumedReadOnly())
2456       return Base::updateImpl(A);
2457 
2458     // If the argument is never passed through callbacks, no-alias cannot break
2459     // synchronization.
2460     bool AllCallSitesKnown;
2461     if (A.checkForAllCallSites(
2462             [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this,
2463             true, AllCallSitesKnown))
2464       return Base::updateImpl(A);
2465 
2466     // TODO: add no-alias but make sure it doesn't break synchronization by
2467     // introducing fake uses. See:
2468     // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel,
2469     //     International Workshop on OpenMP 2018,
2470     //     http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf
2471 
2472     return indicatePessimisticFixpoint();
2473   }
2474 
2475   /// See AbstractAttribute::trackStatistics()
2476   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
2477 };
2478 
2479 struct AANoAliasCallSiteArgument final : AANoAliasImpl {
2480   AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A)
2481       : AANoAliasImpl(IRP, A) {}
2482 
2483   /// See AbstractAttribute::initialize(...).
2484   void initialize(Attributor &A) override {
2485     // See callsite argument attribute and callee argument attribute.
2486     const auto &CB = cast<CallBase>(getAnchorValue());
2487     if (CB.paramHasAttr(getArgNo(), Attribute::NoAlias))
2488       indicateOptimisticFixpoint();
2489     Value &Val = getAssociatedValue();
2490     if (isa<ConstantPointerNull>(Val) &&
2491         !NullPointerIsDefined(getAnchorScope(),
2492                               Val.getType()->getPointerAddressSpace()))
2493       indicateOptimisticFixpoint();
2494   }
2495 
2496   /// Determine if the underlying value may alias with the call site argument
2497   /// \p OtherArgNo of \p ICS (= the underlying call site).
2498   bool mayAliasWithArgument(Attributor &A, AAResults *&AAR,
2499                             const AAMemoryBehavior &MemBehaviorAA,
2500                             const CallBase &CB, unsigned OtherArgNo) {
2501     // We do not need to worry about aliasing with the underlying IRP.
2502     if (this->getArgNo() == (int)OtherArgNo)
2503       return false;
2504 
2505     // If it is not a pointer or pointer vector we do not alias.
2506     const Value *ArgOp = CB.getArgOperand(OtherArgNo);
2507     if (!ArgOp->getType()->isPtrOrPtrVectorTy())
2508       return false;
2509 
2510     auto &CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
2511         *this, IRPosition::callsite_argument(CB, OtherArgNo),
2512         /* TrackDependence */ false);
2513 
2514     // If the argument is readnone, there is no read-write aliasing.
2515     if (CBArgMemBehaviorAA.isAssumedReadNone()) {
2516       A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
2517       return false;
2518     }
2519 
2520     // If the argument is readonly and the underlying value is readonly, there
2521     // is no read-write aliasing.
2522     bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly();
2523     if (CBArgMemBehaviorAA.isAssumedReadOnly() && IsReadOnly) {
2524       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
2525       A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
2526       return false;
2527     }
2528 
2529     // We have to utilize actual alias analysis queries so we need the object.
2530     if (!AAR)
2531       AAR = A.getInfoCache().getAAResultsForFunction(*getAnchorScope());
2532 
2533     // Try to rule it out at the call site.
2534     bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp);
2535     LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between "
2536                          "callsite arguments: "
2537                       << getAssociatedValue() << " " << *ArgOp << " => "
2538                       << (IsAliasing ? "" : "no-") << "alias \n");
2539 
2540     return IsAliasing;
2541   }
2542 
2543   bool
2544   isKnownNoAliasDueToNoAliasPreservation(Attributor &A, AAResults *&AAR,
2545                                          const AAMemoryBehavior &MemBehaviorAA,
2546                                          const AANoAlias &NoAliasAA) {
2547     // We can deduce "noalias" if the following conditions hold.
2548     // (i)   Associated value is assumed to be noalias in the definition.
2549     // (ii)  Associated value is assumed to be no-capture in all the uses
2550     //       possibly executed before this callsite.
2551     // (iii) There is no other pointer argument which could alias with the
2552     //       value.
2553 
2554     bool AssociatedValueIsNoAliasAtDef = NoAliasAA.isAssumedNoAlias();
2555     if (!AssociatedValueIsNoAliasAtDef) {
2556       LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue()
2557                         << " is not no-alias at the definition\n");
2558       return false;
2559     }
2560 
2561     A.recordDependence(NoAliasAA, *this, DepClassTy::OPTIONAL);
2562 
2563     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
2564     auto &NoCaptureAA =
2565         A.getAAFor<AANoCapture>(*this, VIRP, /* TrackDependence */ false);
2566     // Check whether the value is captured in the scope using AANoCapture.
2567     //      Look at CFG and check only uses possibly executed before this
2568     //      callsite.
2569     auto UsePred = [&](const Use &U, bool &Follow) -> bool {
2570       Instruction *UserI = cast<Instruction>(U.getUser());
2571 
2572       // If user if curr instr and only use.
2573       if (UserI == getCtxI() && UserI->hasOneUse())
2574         return true;
2575 
2576       const Function *ScopeFn = VIRP.getAnchorScope();
2577       if (ScopeFn) {
2578         const auto &ReachabilityAA =
2579             A.getAAFor<AAReachability>(*this, IRPosition::function(*ScopeFn));
2580 
2581         if (!ReachabilityAA.isAssumedReachable(A, *UserI, *getCtxI()))
2582           return true;
2583 
2584         if (auto *CB = dyn_cast<CallBase>(UserI)) {
2585           if (CB->isArgOperand(&U)) {
2586 
2587             unsigned ArgNo = CB->getArgOperandNo(&U);
2588 
2589             const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
2590                 *this, IRPosition::callsite_argument(*CB, ArgNo));
2591 
2592             if (NoCaptureAA.isAssumedNoCapture())
2593               return true;
2594           }
2595         }
2596       }
2597 
2598       // For cases which can potentially have more users
2599       if (isa<GetElementPtrInst>(U) || isa<BitCastInst>(U) || isa<PHINode>(U) ||
2600           isa<SelectInst>(U)) {
2601         Follow = true;
2602         return true;
2603       }
2604 
2605       LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *U << "\n");
2606       return false;
2607     };
2608 
2609     if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
2610       if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) {
2611         LLVM_DEBUG(
2612             dbgs() << "[AANoAliasCSArg] " << getAssociatedValue()
2613                    << " cannot be noalias as it is potentially captured\n");
2614         return false;
2615       }
2616     }
2617     A.recordDependence(NoCaptureAA, *this, DepClassTy::OPTIONAL);
2618 
2619     // Check there is no other pointer argument which could alias with the
2620     // value passed at this call site.
2621     // TODO: AbstractCallSite
2622     const auto &CB = cast<CallBase>(getAnchorValue());
2623     for (unsigned OtherArgNo = 0; OtherArgNo < CB.getNumArgOperands();
2624          OtherArgNo++)
2625       if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo))
2626         return false;
2627 
2628     return true;
2629   }
2630 
2631   /// See AbstractAttribute::updateImpl(...).
2632   ChangeStatus updateImpl(Attributor &A) override {
2633     // If the argument is readnone we are done as there are no accesses via the
2634     // argument.
2635     auto &MemBehaviorAA =
2636         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(),
2637                                      /* TrackDependence */ false);
2638     if (MemBehaviorAA.isAssumedReadNone()) {
2639       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
2640       return ChangeStatus::UNCHANGED;
2641     }
2642 
2643     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
2644     const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, VIRP,
2645                                                   /* TrackDependence */ false);
2646 
2647     AAResults *AAR = nullptr;
2648     if (isKnownNoAliasDueToNoAliasPreservation(A, AAR, MemBehaviorAA,
2649                                                NoAliasAA)) {
2650       LLVM_DEBUG(
2651           dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n");
2652       return ChangeStatus::UNCHANGED;
2653     }
2654 
2655     return indicatePessimisticFixpoint();
2656   }
2657 
2658   /// See AbstractAttribute::trackStatistics()
2659   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) }
2660 };
2661 
2662 /// NoAlias attribute for function return value.
2663 struct AANoAliasReturned final : AANoAliasImpl {
2664   AANoAliasReturned(const IRPosition &IRP, Attributor &A)
2665       : AANoAliasImpl(IRP, A) {}
2666 
2667   /// See AbstractAttribute::updateImpl(...).
2668   virtual ChangeStatus updateImpl(Attributor &A) override {
2669 
2670     auto CheckReturnValue = [&](Value &RV) -> bool {
2671       if (Constant *C = dyn_cast<Constant>(&RV))
2672         if (C->isNullValue() || isa<UndefValue>(C))
2673           return true;
2674 
2675       /// For now, we can only deduce noalias if we have call sites.
2676       /// FIXME: add more support.
2677       if (!isa<CallBase>(&RV))
2678         return false;
2679 
2680       const IRPosition &RVPos = IRPosition::value(RV);
2681       const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, RVPos);
2682       if (!NoAliasAA.isAssumedNoAlias())
2683         return false;
2684 
2685       const auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, RVPos);
2686       return NoCaptureAA.isAssumedNoCaptureMaybeReturned();
2687     };
2688 
2689     if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
2690       return indicatePessimisticFixpoint();
2691 
2692     return ChangeStatus::UNCHANGED;
2693   }
2694 
2695   /// See AbstractAttribute::trackStatistics()
2696   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
2697 };
2698 
2699 /// NoAlias attribute deduction for a call site return value.
2700 struct AANoAliasCallSiteReturned final : AANoAliasImpl {
2701   AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A)
2702       : AANoAliasImpl(IRP, A) {}
2703 
2704   /// See AbstractAttribute::initialize(...).
2705   void initialize(Attributor &A) override {
2706     AANoAliasImpl::initialize(A);
2707     Function *F = getAssociatedFunction();
2708     if (!F)
2709       indicatePessimisticFixpoint();
2710   }
2711 
2712   /// See AbstractAttribute::updateImpl(...).
2713   ChangeStatus updateImpl(Attributor &A) override {
2714     // TODO: Once we have call site specific value information we can provide
2715     //       call site specific liveness information and then it makes
2716     //       sense to specialize attributes for call sites arguments instead of
2717     //       redirecting requests to the callee argument.
2718     Function *F = getAssociatedFunction();
2719     const IRPosition &FnPos = IRPosition::returned(*F);
2720     auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos);
2721     return clampStateAndIndicateChange(getState(), FnAA.getState());
2722   }
2723 
2724   /// See AbstractAttribute::trackStatistics()
2725   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); }
2726 };
2727 
2728 /// -------------------AAIsDead Function Attribute-----------------------
2729 
2730 struct AAIsDeadValueImpl : public AAIsDead {
2731   AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
2732 
2733   /// See AAIsDead::isAssumedDead().
2734   bool isAssumedDead() const override { return getAssumed(); }
2735 
2736   /// See AAIsDead::isKnownDead().
2737   bool isKnownDead() const override { return getKnown(); }
2738 
2739   /// See AAIsDead::isAssumedDead(BasicBlock *).
2740   bool isAssumedDead(const BasicBlock *BB) const override { return false; }
2741 
2742   /// See AAIsDead::isKnownDead(BasicBlock *).
2743   bool isKnownDead(const BasicBlock *BB) const override { return false; }
2744 
2745   /// See AAIsDead::isAssumedDead(Instruction *I).
2746   bool isAssumedDead(const Instruction *I) const override {
2747     return I == getCtxI() && isAssumedDead();
2748   }
2749 
2750   /// See AAIsDead::isKnownDead(Instruction *I).
2751   bool isKnownDead(const Instruction *I) const override {
2752     return isAssumedDead(I) && getKnown();
2753   }
2754 
2755   /// See AbstractAttribute::getAsStr().
2756   const std::string getAsStr() const override {
2757     return isAssumedDead() ? "assumed-dead" : "assumed-live";
2758   }
2759 
2760   /// Check if all uses are assumed dead.
2761   bool areAllUsesAssumedDead(Attributor &A, Value &V) {
2762     auto UsePred = [&](const Use &U, bool &Follow) { return false; };
2763     // Explicitly set the dependence class to required because we want a long
2764     // chain of N dependent instructions to be considered live as soon as one is
2765     // without going through N update cycles. This is not required for
2766     // correctness.
2767     return A.checkForAllUses(UsePred, *this, V, DepClassTy::REQUIRED);
2768   }
2769 
2770   /// Determine if \p I is assumed to be side-effect free.
2771   bool isAssumedSideEffectFree(Attributor &A, Instruction *I) {
2772     if (!I || wouldInstructionBeTriviallyDead(I))
2773       return true;
2774 
2775     auto *CB = dyn_cast<CallBase>(I);
2776     if (!CB || isa<IntrinsicInst>(CB))
2777       return false;
2778 
2779     const IRPosition &CallIRP = IRPosition::callsite_function(*CB);
2780     const auto &NoUnwindAA = A.getAndUpdateAAFor<AANoUnwind>(
2781         *this, CallIRP, /* TrackDependence */ false);
2782     if (!NoUnwindAA.isAssumedNoUnwind())
2783       return false;
2784     if (!NoUnwindAA.isKnownNoUnwind())
2785       A.recordDependence(NoUnwindAA, *this, DepClassTy::OPTIONAL);
2786 
2787     const auto &MemBehaviorAA = A.getAndUpdateAAFor<AAMemoryBehavior>(
2788         *this, CallIRP, /* TrackDependence */ false);
2789     if (MemBehaviorAA.isAssumedReadOnly()) {
2790       if (!MemBehaviorAA.isKnownReadOnly())
2791         A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
2792       return true;
2793     }
2794     return false;
2795   }
2796 };
2797 
2798 struct AAIsDeadFloating : public AAIsDeadValueImpl {
2799   AAIsDeadFloating(const IRPosition &IRP, Attributor &A)
2800       : AAIsDeadValueImpl(IRP, A) {}
2801 
2802   /// See AbstractAttribute::initialize(...).
2803   void initialize(Attributor &A) override {
2804     if (isa<UndefValue>(getAssociatedValue())) {
2805       indicatePessimisticFixpoint();
2806       return;
2807     }
2808 
2809     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
2810     if (!isAssumedSideEffectFree(A, I))
2811       indicatePessimisticFixpoint();
2812   }
2813 
2814   /// See AbstractAttribute::updateImpl(...).
2815   ChangeStatus updateImpl(Attributor &A) override {
2816     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
2817     if (!isAssumedSideEffectFree(A, I))
2818       return indicatePessimisticFixpoint();
2819 
2820     if (!areAllUsesAssumedDead(A, getAssociatedValue()))
2821       return indicatePessimisticFixpoint();
2822     return ChangeStatus::UNCHANGED;
2823   }
2824 
2825   /// See AbstractAttribute::manifest(...).
2826   ChangeStatus manifest(Attributor &A) override {
2827     Value &V = getAssociatedValue();
2828     if (auto *I = dyn_cast<Instruction>(&V)) {
2829       // If we get here we basically know the users are all dead. We check if
2830       // isAssumedSideEffectFree returns true here again because it might not be
2831       // the case and only the users are dead but the instruction (=call) is
2832       // still needed.
2833       if (isAssumedSideEffectFree(A, I) && !isa<InvokeInst>(I)) {
2834         A.deleteAfterManifest(*I);
2835         return ChangeStatus::CHANGED;
2836       }
2837     }
2838     if (V.use_empty())
2839       return ChangeStatus::UNCHANGED;
2840 
2841     bool UsedAssumedInformation = false;
2842     Optional<Constant *> C =
2843         A.getAssumedConstant(V, *this, UsedAssumedInformation);
2844     if (C.hasValue() && C.getValue())
2845       return ChangeStatus::UNCHANGED;
2846 
2847     // Replace the value with undef as it is dead but keep droppable uses around
2848     // as they provide information we don't want to give up on just yet.
2849     UndefValue &UV = *UndefValue::get(V.getType());
2850     bool AnyChange =
2851         A.changeValueAfterManifest(V, UV, /* ChangeDropppable */ false);
2852     return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
2853   }
2854 
2855   /// See AbstractAttribute::trackStatistics()
2856   void trackStatistics() const override {
2857     STATS_DECLTRACK_FLOATING_ATTR(IsDead)
2858   }
2859 };
2860 
2861 struct AAIsDeadArgument : public AAIsDeadFloating {
2862   AAIsDeadArgument(const IRPosition &IRP, Attributor &A)
2863       : AAIsDeadFloating(IRP, A) {}
2864 
2865   /// See AbstractAttribute::initialize(...).
2866   void initialize(Attributor &A) override {
2867     if (!A.isFunctionIPOAmendable(*getAnchorScope()))
2868       indicatePessimisticFixpoint();
2869   }
2870 
2871   /// See AbstractAttribute::manifest(...).
2872   ChangeStatus manifest(Attributor &A) override {
2873     ChangeStatus Changed = AAIsDeadFloating::manifest(A);
2874     Argument &Arg = *getAssociatedArgument();
2875     if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {}))
2876       if (A.registerFunctionSignatureRewrite(
2877               Arg, /* ReplacementTypes */ {},
2878               Attributor::ArgumentReplacementInfo::CalleeRepairCBTy{},
2879               Attributor::ArgumentReplacementInfo::ACSRepairCBTy{})) {
2880         Arg.dropDroppableUses();
2881         return ChangeStatus::CHANGED;
2882       }
2883     return Changed;
2884   }
2885 
2886   /// See AbstractAttribute::trackStatistics()
2887   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) }
2888 };
2889 
2890 struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl {
2891   AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A)
2892       : AAIsDeadValueImpl(IRP, A) {}
2893 
2894   /// See AbstractAttribute::initialize(...).
2895   void initialize(Attributor &A) override {
2896     if (isa<UndefValue>(getAssociatedValue()))
2897       indicatePessimisticFixpoint();
2898   }
2899 
2900   /// See AbstractAttribute::updateImpl(...).
2901   ChangeStatus updateImpl(Attributor &A) override {
2902     // TODO: Once we have call site specific value information we can provide
2903     //       call site specific liveness information and then it makes
2904     //       sense to specialize attributes for call sites arguments instead of
2905     //       redirecting requests to the callee argument.
2906     Argument *Arg = getAssociatedArgument();
2907     if (!Arg)
2908       return indicatePessimisticFixpoint();
2909     const IRPosition &ArgPos = IRPosition::argument(*Arg);
2910     auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos);
2911     return clampStateAndIndicateChange(getState(), ArgAA.getState());
2912   }
2913 
2914   /// See AbstractAttribute::manifest(...).
2915   ChangeStatus manifest(Attributor &A) override {
2916     CallBase &CB = cast<CallBase>(getAnchorValue());
2917     Use &U = CB.getArgOperandUse(getArgNo());
2918     assert(!isa<UndefValue>(U.get()) &&
2919            "Expected undef values to be filtered out!");
2920     UndefValue &UV = *UndefValue::get(U->getType());
2921     if (A.changeUseAfterManifest(U, UV))
2922       return ChangeStatus::CHANGED;
2923     return ChangeStatus::UNCHANGED;
2924   }
2925 
2926   /// See AbstractAttribute::trackStatistics()
2927   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) }
2928 };
2929 
2930 struct AAIsDeadCallSiteReturned : public AAIsDeadFloating {
2931   AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A)
2932       : AAIsDeadFloating(IRP, A), IsAssumedSideEffectFree(true) {}
2933 
2934   /// See AAIsDead::isAssumedDead().
2935   bool isAssumedDead() const override {
2936     return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
2937   }
2938 
2939   /// See AbstractAttribute::initialize(...).
2940   void initialize(Attributor &A) override {
2941     if (isa<UndefValue>(getAssociatedValue())) {
2942       indicatePessimisticFixpoint();
2943       return;
2944     }
2945 
2946     // We track this separately as a secondary state.
2947     IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI());
2948   }
2949 
2950   /// See AbstractAttribute::updateImpl(...).
2951   ChangeStatus updateImpl(Attributor &A) override {
2952     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2953     if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) {
2954       IsAssumedSideEffectFree = false;
2955       Changed = ChangeStatus::CHANGED;
2956     }
2957 
2958     if (!areAllUsesAssumedDead(A, getAssociatedValue()))
2959       return indicatePessimisticFixpoint();
2960     return Changed;
2961   }
2962 
2963   /// See AbstractAttribute::trackStatistics()
2964   void trackStatistics() const override {
2965     if (IsAssumedSideEffectFree)
2966       STATS_DECLTRACK_CSRET_ATTR(IsDead)
2967     else
2968       STATS_DECLTRACK_CSRET_ATTR(UnusedResult)
2969   }
2970 
2971   /// See AbstractAttribute::getAsStr().
2972   const std::string getAsStr() const override {
2973     return isAssumedDead()
2974                ? "assumed-dead"
2975                : (getAssumed() ? "assumed-dead-users" : "assumed-live");
2976   }
2977 
2978 private:
2979   bool IsAssumedSideEffectFree;
2980 };
2981 
2982 struct AAIsDeadReturned : public AAIsDeadValueImpl {
2983   AAIsDeadReturned(const IRPosition &IRP, Attributor &A)
2984       : AAIsDeadValueImpl(IRP, A) {}
2985 
2986   /// See AbstractAttribute::updateImpl(...).
2987   ChangeStatus updateImpl(Attributor &A) override {
2988 
2989     A.checkForAllInstructions([](Instruction &) { return true; }, *this,
2990                               {Instruction::Ret});
2991 
2992     auto PredForCallSite = [&](AbstractCallSite ACS) {
2993       if (ACS.isCallbackCall() || !ACS.getInstruction())
2994         return false;
2995       return areAllUsesAssumedDead(A, *ACS.getInstruction());
2996     };
2997 
2998     bool AllCallSitesKnown;
2999     if (!A.checkForAllCallSites(PredForCallSite, *this, true,
3000                                 AllCallSitesKnown))
3001       return indicatePessimisticFixpoint();
3002 
3003     return ChangeStatus::UNCHANGED;
3004   }
3005 
3006   /// See AbstractAttribute::manifest(...).
3007   ChangeStatus manifest(Attributor &A) override {
3008     // TODO: Rewrite the signature to return void?
3009     bool AnyChange = false;
3010     UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType());
3011     auto RetInstPred = [&](Instruction &I) {
3012       ReturnInst &RI = cast<ReturnInst>(I);
3013       if (!isa<UndefValue>(RI.getReturnValue()))
3014         AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV);
3015       return true;
3016     };
3017     A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret});
3018     return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
3019   }
3020 
3021   /// See AbstractAttribute::trackStatistics()
3022   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) }
3023 };
3024 
3025 struct AAIsDeadFunction : public AAIsDead {
3026   AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
3027 
3028   /// See AbstractAttribute::initialize(...).
3029   void initialize(Attributor &A) override {
3030     const Function *F = getAnchorScope();
3031     if (F && !F->isDeclaration()) {
3032       ToBeExploredFrom.insert(&F->getEntryBlock().front());
3033       assumeLive(A, F->getEntryBlock());
3034     }
3035   }
3036 
3037   /// See AbstractAttribute::getAsStr().
3038   const std::string getAsStr() const override {
3039     return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
3040            std::to_string(getAnchorScope()->size()) + "][#TBEP " +
3041            std::to_string(ToBeExploredFrom.size()) + "][#KDE " +
3042            std::to_string(KnownDeadEnds.size()) + "]";
3043   }
3044 
3045   /// See AbstractAttribute::manifest(...).
3046   ChangeStatus manifest(Attributor &A) override {
3047     assert(getState().isValidState() &&
3048            "Attempted to manifest an invalid state!");
3049 
3050     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
3051     Function &F = *getAnchorScope();
3052 
3053     if (AssumedLiveBlocks.empty()) {
3054       A.deleteAfterManifest(F);
3055       return ChangeStatus::CHANGED;
3056     }
3057 
3058     // Flag to determine if we can change an invoke to a call assuming the
3059     // callee is nounwind. This is not possible if the personality of the
3060     // function allows to catch asynchronous exceptions.
3061     bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
3062 
3063     KnownDeadEnds.set_union(ToBeExploredFrom);
3064     for (const Instruction *DeadEndI : KnownDeadEnds) {
3065       auto *CB = dyn_cast<CallBase>(DeadEndI);
3066       if (!CB)
3067         continue;
3068       const auto &NoReturnAA = A.getAndUpdateAAFor<AANoReturn>(
3069           *this, IRPosition::callsite_function(*CB), /* TrackDependence */ true,
3070           DepClassTy::OPTIONAL);
3071       bool MayReturn = !NoReturnAA.isAssumedNoReturn();
3072       if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
3073         continue;
3074 
3075       if (auto *II = dyn_cast<InvokeInst>(DeadEndI))
3076         A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II));
3077       else
3078         A.changeToUnreachableAfterManifest(
3079             const_cast<Instruction *>(DeadEndI->getNextNode()));
3080       HasChanged = ChangeStatus::CHANGED;
3081     }
3082 
3083     STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted.");
3084     for (BasicBlock &BB : F)
3085       if (!AssumedLiveBlocks.count(&BB)) {
3086         A.deleteAfterManifest(BB);
3087         ++BUILD_STAT_NAME(AAIsDead, BasicBlock);
3088       }
3089 
3090     return HasChanged;
3091   }
3092 
3093   /// See AbstractAttribute::updateImpl(...).
3094   ChangeStatus updateImpl(Attributor &A) override;
3095 
3096   /// See AbstractAttribute::trackStatistics()
3097   void trackStatistics() const override {}
3098 
3099   /// Returns true if the function is assumed dead.
3100   bool isAssumedDead() const override { return false; }
3101 
3102   /// See AAIsDead::isKnownDead().
3103   bool isKnownDead() const override { return false; }
3104 
3105   /// See AAIsDead::isAssumedDead(BasicBlock *).
3106   bool isAssumedDead(const BasicBlock *BB) const override {
3107     assert(BB->getParent() == getAnchorScope() &&
3108            "BB must be in the same anchor scope function.");
3109 
3110     if (!getAssumed())
3111       return false;
3112     return !AssumedLiveBlocks.count(BB);
3113   }
3114 
3115   /// See AAIsDead::isKnownDead(BasicBlock *).
3116   bool isKnownDead(const BasicBlock *BB) const override {
3117     return getKnown() && isAssumedDead(BB);
3118   }
3119 
3120   /// See AAIsDead::isAssumed(Instruction *I).
3121   bool isAssumedDead(const Instruction *I) const override {
3122     assert(I->getParent()->getParent() == getAnchorScope() &&
3123            "Instruction must be in the same anchor scope function.");
3124 
3125     if (!getAssumed())
3126       return false;
3127 
3128     // If it is not in AssumedLiveBlocks then it for sure dead.
3129     // Otherwise, it can still be after noreturn call in a live block.
3130     if (!AssumedLiveBlocks.count(I->getParent()))
3131       return true;
3132 
3133     // If it is not after a liveness barrier it is live.
3134     const Instruction *PrevI = I->getPrevNode();
3135     while (PrevI) {
3136       if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
3137         return true;
3138       PrevI = PrevI->getPrevNode();
3139     }
3140     return false;
3141   }
3142 
3143   /// See AAIsDead::isKnownDead(Instruction *I).
3144   bool isKnownDead(const Instruction *I) const override {
3145     return getKnown() && isAssumedDead(I);
3146   }
3147 
3148   /// Assume \p BB is (partially) live now and indicate to the Attributor \p A
3149   /// that internal function called from \p BB should now be looked at.
3150   bool assumeLive(Attributor &A, const BasicBlock &BB) {
3151     if (!AssumedLiveBlocks.insert(&BB).second)
3152       return false;
3153 
3154     // We assume that all of BB is (probably) live now and if there are calls to
3155     // internal functions we will assume that those are now live as well. This
3156     // is a performance optimization for blocks with calls to a lot of internal
3157     // functions. It can however cause dead functions to be treated as live.
3158     for (const Instruction &I : BB)
3159       if (const auto *CB = dyn_cast<CallBase>(&I))
3160         if (const Function *F = CB->getCalledFunction())
3161           if (F->hasLocalLinkage())
3162             A.markLiveInternalFunction(*F);
3163     return true;
3164   }
3165 
3166   /// Collection of instructions that need to be explored again, e.g., we
3167   /// did assume they do not transfer control to (one of their) successors.
3168   SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
3169 
3170   /// Collection of instructions that are known to not transfer control.
3171   SmallSetVector<const Instruction *, 8> KnownDeadEnds;
3172 
3173   /// Collection of all assumed live BasicBlocks.
3174   DenseSet<const BasicBlock *> AssumedLiveBlocks;
3175 };
3176 
3177 static bool
3178 identifyAliveSuccessors(Attributor &A, const CallBase &CB,
3179                         AbstractAttribute &AA,
3180                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3181   const IRPosition &IPos = IRPosition::callsite_function(CB);
3182 
3183   const auto &NoReturnAA = A.getAndUpdateAAFor<AANoReturn>(
3184       AA, IPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
3185   if (NoReturnAA.isAssumedNoReturn())
3186     return !NoReturnAA.isKnownNoReturn();
3187   if (CB.isTerminator())
3188     AliveSuccessors.push_back(&CB.getSuccessor(0)->front());
3189   else
3190     AliveSuccessors.push_back(CB.getNextNode());
3191   return false;
3192 }
3193 
3194 static bool
3195 identifyAliveSuccessors(Attributor &A, const InvokeInst &II,
3196                         AbstractAttribute &AA,
3197                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3198   bool UsedAssumedInformation =
3199       identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
3200 
3201   // First, determine if we can change an invoke to a call assuming the
3202   // callee is nounwind. This is not possible if the personality of the
3203   // function allows to catch asynchronous exceptions.
3204   if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) {
3205     AliveSuccessors.push_back(&II.getUnwindDest()->front());
3206   } else {
3207     const IRPosition &IPos = IRPosition::callsite_function(II);
3208     const auto &AANoUnw = A.getAndUpdateAAFor<AANoUnwind>(
3209         AA, IPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
3210     if (AANoUnw.isAssumedNoUnwind()) {
3211       UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind();
3212     } else {
3213       AliveSuccessors.push_back(&II.getUnwindDest()->front());
3214     }
3215   }
3216   return UsedAssumedInformation;
3217 }
3218 
3219 static bool
3220 identifyAliveSuccessors(Attributor &A, const BranchInst &BI,
3221                         AbstractAttribute &AA,
3222                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3223   bool UsedAssumedInformation = false;
3224   if (BI.getNumSuccessors() == 1) {
3225     AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
3226   } else {
3227     Optional<ConstantInt *> CI = getAssumedConstantInt(
3228         A, *BI.getCondition(), AA, UsedAssumedInformation);
3229     if (!CI.hasValue()) {
3230       // No value yet, assume both edges are dead.
3231     } else if (CI.getValue()) {
3232       const BasicBlock *SuccBB =
3233           BI.getSuccessor(1 - CI.getValue()->getZExtValue());
3234       AliveSuccessors.push_back(&SuccBB->front());
3235     } else {
3236       AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
3237       AliveSuccessors.push_back(&BI.getSuccessor(1)->front());
3238       UsedAssumedInformation = false;
3239     }
3240   }
3241   return UsedAssumedInformation;
3242 }
3243 
3244 static bool
3245 identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
3246                         AbstractAttribute &AA,
3247                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3248   bool UsedAssumedInformation = false;
3249   Optional<ConstantInt *> CI =
3250       getAssumedConstantInt(A, *SI.getCondition(), AA, UsedAssumedInformation);
3251   if (!CI.hasValue()) {
3252     // No value yet, assume all edges are dead.
3253   } else if (CI.getValue()) {
3254     for (auto &CaseIt : SI.cases()) {
3255       if (CaseIt.getCaseValue() == CI.getValue()) {
3256         AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
3257         return UsedAssumedInformation;
3258       }
3259     }
3260     AliveSuccessors.push_back(&SI.getDefaultDest()->front());
3261     return UsedAssumedInformation;
3262   } else {
3263     for (const BasicBlock *SuccBB : successors(SI.getParent()))
3264       AliveSuccessors.push_back(&SuccBB->front());
3265   }
3266   return UsedAssumedInformation;
3267 }
3268 
3269 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
3270   ChangeStatus Change = ChangeStatus::UNCHANGED;
3271 
3272   LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/"
3273                     << getAnchorScope()->size() << "] BBs and "
3274                     << ToBeExploredFrom.size() << " exploration points and "
3275                     << KnownDeadEnds.size() << " known dead ends\n");
3276 
3277   // Copy and clear the list of instructions we need to explore from. It is
3278   // refilled with instructions the next update has to look at.
3279   SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(),
3280                                                ToBeExploredFrom.end());
3281   decltype(ToBeExploredFrom) NewToBeExploredFrom;
3282 
3283   SmallVector<const Instruction *, 8> AliveSuccessors;
3284   while (!Worklist.empty()) {
3285     const Instruction *I = Worklist.pop_back_val();
3286     LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n");
3287 
3288     // Fast forward for uninteresting instructions. We could look for UB here
3289     // though.
3290     while(!I->isTerminator() && !isa<CallBase>(I)) {
3291       Change = ChangeStatus::CHANGED;
3292       I = I->getNextNode();
3293     }
3294 
3295     AliveSuccessors.clear();
3296 
3297     bool UsedAssumedInformation = false;
3298     switch (I->getOpcode()) {
3299     // TODO: look for (assumed) UB to backwards propagate "deadness".
3300     default:
3301       assert(I->isTerminator() &&
3302              "Expected non-terminators to be handled already!");
3303       for (const BasicBlock *SuccBB : successors(I->getParent()))
3304         AliveSuccessors.push_back(&SuccBB->front());
3305       break;
3306     case Instruction::Call:
3307       UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
3308                                                        *this, AliveSuccessors);
3309       break;
3310     case Instruction::Invoke:
3311       UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
3312                                                        *this, AliveSuccessors);
3313       break;
3314     case Instruction::Br:
3315       UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I),
3316                                                        *this, AliveSuccessors);
3317       break;
3318     case Instruction::Switch:
3319       UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
3320                                                        *this, AliveSuccessors);
3321       break;
3322     }
3323 
3324     if (UsedAssumedInformation) {
3325       NewToBeExploredFrom.insert(I);
3326     } else {
3327       Change = ChangeStatus::CHANGED;
3328       if (AliveSuccessors.empty() ||
3329           (I->isTerminator() && AliveSuccessors.size() < I->getNumSuccessors()))
3330         KnownDeadEnds.insert(I);
3331     }
3332 
3333     LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: "
3334                       << AliveSuccessors.size() << " UsedAssumedInformation: "
3335                       << UsedAssumedInformation << "\n");
3336 
3337     for (const Instruction *AliveSuccessor : AliveSuccessors) {
3338       if (!I->isTerminator()) {
3339         assert(AliveSuccessors.size() == 1 &&
3340                "Non-terminator expected to have a single successor!");
3341         Worklist.push_back(AliveSuccessor);
3342       } else {
3343         if (assumeLive(A, *AliveSuccessor->getParent()))
3344           Worklist.push_back(AliveSuccessor);
3345       }
3346     }
3347   }
3348 
3349   ToBeExploredFrom = std::move(NewToBeExploredFrom);
3350 
3351   // If we know everything is live there is no need to query for liveness.
3352   // Instead, indicating a pessimistic fixpoint will cause the state to be
3353   // "invalid" and all queries to be answered conservatively without lookups.
3354   // To be in this state we have to (1) finished the exploration and (3) not
3355   // discovered any non-trivial dead end and (2) not ruled unreachable code
3356   // dead.
3357   if (ToBeExploredFrom.empty() &&
3358       getAnchorScope()->size() == AssumedLiveBlocks.size() &&
3359       llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) {
3360         return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
3361       }))
3362     return indicatePessimisticFixpoint();
3363   return Change;
3364 }
3365 
3366 /// Liveness information for a call sites.
3367 struct AAIsDeadCallSite final : AAIsDeadFunction {
3368   AAIsDeadCallSite(const IRPosition &IRP, Attributor &A)
3369       : AAIsDeadFunction(IRP, A) {}
3370 
3371   /// See AbstractAttribute::initialize(...).
3372   void initialize(Attributor &A) override {
3373     // TODO: Once we have call site specific value information we can provide
3374     //       call site specific liveness information and then it makes
3375     //       sense to specialize attributes for call sites instead of
3376     //       redirecting requests to the callee.
3377     llvm_unreachable("Abstract attributes for liveness are not "
3378                      "supported for call sites yet!");
3379   }
3380 
3381   /// See AbstractAttribute::updateImpl(...).
3382   ChangeStatus updateImpl(Attributor &A) override {
3383     return indicatePessimisticFixpoint();
3384   }
3385 
3386   /// See AbstractAttribute::trackStatistics()
3387   void trackStatistics() const override {}
3388 };
3389 
3390 /// -------------------- Dereferenceable Argument Attribute --------------------
3391 
3392 template <>
3393 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S,
3394                                                      const DerefState &R) {
3395   ChangeStatus CS0 =
3396       clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState);
3397   ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState);
3398   return CS0 | CS1;
3399 }
3400 
3401 struct AADereferenceableImpl : AADereferenceable {
3402   AADereferenceableImpl(const IRPosition &IRP, Attributor &A)
3403       : AADereferenceable(IRP, A) {}
3404   using StateType = DerefState;
3405 
3406   /// See AbstractAttribute::initialize(...).
3407   void initialize(Attributor &A) override {
3408     SmallVector<Attribute, 4> Attrs;
3409     getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
3410              Attrs, /* IgnoreSubsumingPositions */ false, &A);
3411     for (const Attribute &Attr : Attrs)
3412       takeKnownDerefBytesMaximum(Attr.getValueAsInt());
3413 
3414     const IRPosition &IRP = this->getIRPosition();
3415     NonNullAA = &A.getAAFor<AANonNull>(*this, IRP,
3416                                        /* TrackDependence */ false);
3417 
3418     bool CanBeNull;
3419     takeKnownDerefBytesMaximum(
3420         IRP.getAssociatedValue().getPointerDereferenceableBytes(
3421             A.getDataLayout(), CanBeNull));
3422 
3423     bool IsFnInterface = IRP.isFnInterfaceKind();
3424     Function *FnScope = IRP.getAnchorScope();
3425     if (IsFnInterface && (!FnScope || !A.isFunctionIPOAmendable(*FnScope))) {
3426       indicatePessimisticFixpoint();
3427       return;
3428     }
3429 
3430     if (Instruction *CtxI = getCtxI())
3431       followUsesInMBEC(*this, A, getState(), *CtxI);
3432   }
3433 
3434   /// See AbstractAttribute::getState()
3435   /// {
3436   StateType &getState() override { return *this; }
3437   const StateType &getState() const override { return *this; }
3438   /// }
3439 
3440   /// Helper function for collecting accessed bytes in must-be-executed-context
3441   void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I,
3442                               DerefState &State) {
3443     const Value *UseV = U->get();
3444     if (!UseV->getType()->isPointerTy())
3445       return;
3446 
3447     Type *PtrTy = UseV->getType();
3448     const DataLayout &DL = A.getDataLayout();
3449     int64_t Offset;
3450     if (const Value *Base = getBasePointerOfAccessPointerOperand(
3451             I, Offset, DL, /*AllowNonInbounds*/ true)) {
3452       if (Base == &getAssociatedValue() &&
3453           getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
3454         uint64_t Size = DL.getTypeStoreSize(PtrTy->getPointerElementType());
3455         State.addAccessedBytes(Offset, Size);
3456       }
3457     }
3458     return;
3459   }
3460 
3461   /// See followUsesInMBEC
3462   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
3463                        AADereferenceable::StateType &State) {
3464     bool IsNonNull = false;
3465     bool TrackUse = false;
3466     int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
3467         A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse);
3468     LLVM_DEBUG(dbgs() << "[AADereferenceable] Deref bytes: " << DerefBytes
3469                       << " for instruction " << *I << "\n");
3470 
3471     addAccessedBytesForUse(A, U, I, State);
3472     State.takeKnownDerefBytesMaximum(DerefBytes);
3473     return TrackUse;
3474   }
3475 
3476   /// See AbstractAttribute::manifest(...).
3477   ChangeStatus manifest(Attributor &A) override {
3478     ChangeStatus Change = AADereferenceable::manifest(A);
3479     if (isAssumedNonNull() && hasAttr(Attribute::DereferenceableOrNull)) {
3480       removeAttrs({Attribute::DereferenceableOrNull});
3481       return ChangeStatus::CHANGED;
3482     }
3483     return Change;
3484   }
3485 
3486   void getDeducedAttributes(LLVMContext &Ctx,
3487                             SmallVectorImpl<Attribute> &Attrs) const override {
3488     // TODO: Add *_globally support
3489     if (isAssumedNonNull())
3490       Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
3491           Ctx, getAssumedDereferenceableBytes()));
3492     else
3493       Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
3494           Ctx, getAssumedDereferenceableBytes()));
3495   }
3496 
3497   /// See AbstractAttribute::getAsStr().
3498   const std::string getAsStr() const override {
3499     if (!getAssumedDereferenceableBytes())
3500       return "unknown-dereferenceable";
3501     return std::string("dereferenceable") +
3502            (isAssumedNonNull() ? "" : "_or_null") +
3503            (isAssumedGlobal() ? "_globally" : "") + "<" +
3504            std::to_string(getKnownDereferenceableBytes()) + "-" +
3505            std::to_string(getAssumedDereferenceableBytes()) + ">";
3506   }
3507 };
3508 
3509 /// Dereferenceable attribute for a floating value.
3510 struct AADereferenceableFloating : AADereferenceableImpl {
3511   AADereferenceableFloating(const IRPosition &IRP, Attributor &A)
3512       : AADereferenceableImpl(IRP, A) {}
3513 
3514   /// See AbstractAttribute::updateImpl(...).
3515   ChangeStatus updateImpl(Attributor &A) override {
3516     const DataLayout &DL = A.getDataLayout();
3517 
3518     auto VisitValueCB = [&](const Value &V, const Instruction *, DerefState &T,
3519                             bool Stripped) -> bool {
3520       unsigned IdxWidth =
3521           DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
3522       APInt Offset(IdxWidth, 0);
3523       const Value *Base =
3524           stripAndAccumulateMinimalOffsets(A, *this, &V, DL, Offset, false);
3525 
3526       const auto &AA =
3527           A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base));
3528       int64_t DerefBytes = 0;
3529       if (!Stripped && this == &AA) {
3530         // Use IR information if we did not strip anything.
3531         // TODO: track globally.
3532         bool CanBeNull;
3533         DerefBytes = Base->getPointerDereferenceableBytes(DL, CanBeNull);
3534         T.GlobalState.indicatePessimisticFixpoint();
3535       } else {
3536         const DerefState &DS = AA.getState();
3537         DerefBytes = DS.DerefBytesState.getAssumed();
3538         T.GlobalState &= DS.GlobalState;
3539       }
3540 
3541       // For now we do not try to "increase" dereferenceability due to negative
3542       // indices as we first have to come up with code to deal with loops and
3543       // for overflows of the dereferenceable bytes.
3544       int64_t OffsetSExt = Offset.getSExtValue();
3545       if (OffsetSExt < 0)
3546         OffsetSExt = 0;
3547 
3548       T.takeAssumedDerefBytesMinimum(
3549           std::max(int64_t(0), DerefBytes - OffsetSExt));
3550 
3551       if (this == &AA) {
3552         if (!Stripped) {
3553           // If nothing was stripped IR information is all we got.
3554           T.takeKnownDerefBytesMaximum(
3555               std::max(int64_t(0), DerefBytes - OffsetSExt));
3556           T.indicatePessimisticFixpoint();
3557         } else if (OffsetSExt > 0) {
3558           // If something was stripped but there is circular reasoning we look
3559           // for the offset. If it is positive we basically decrease the
3560           // dereferenceable bytes in a circluar loop now, which will simply
3561           // drive them down to the known value in a very slow way which we
3562           // can accelerate.
3563           T.indicatePessimisticFixpoint();
3564         }
3565       }
3566 
3567       return T.isValidState();
3568     };
3569 
3570     DerefState T;
3571     if (!genericValueTraversal<AADereferenceable, DerefState>(
3572             A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
3573       return indicatePessimisticFixpoint();
3574 
3575     return clampStateAndIndicateChange(getState(), T);
3576   }
3577 
3578   /// See AbstractAttribute::trackStatistics()
3579   void trackStatistics() const override {
3580     STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
3581   }
3582 };
3583 
3584 /// Dereferenceable attribute for a return value.
3585 struct AADereferenceableReturned final
3586     : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
3587   AADereferenceableReturned(const IRPosition &IRP, Attributor &A)
3588       : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>(
3589             IRP, A) {}
3590 
3591   /// See AbstractAttribute::trackStatistics()
3592   void trackStatistics() const override {
3593     STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
3594   }
3595 };
3596 
3597 /// Dereferenceable attribute for an argument
3598 struct AADereferenceableArgument final
3599     : AAArgumentFromCallSiteArguments<AADereferenceable,
3600                                       AADereferenceableImpl> {
3601   using Base =
3602       AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>;
3603   AADereferenceableArgument(const IRPosition &IRP, Attributor &A)
3604       : Base(IRP, A) {}
3605 
3606   /// See AbstractAttribute::trackStatistics()
3607   void trackStatistics() const override {
3608     STATS_DECLTRACK_ARG_ATTR(dereferenceable)
3609   }
3610 };
3611 
3612 /// Dereferenceable attribute for a call site argument.
3613 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
3614   AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A)
3615       : AADereferenceableFloating(IRP, A) {}
3616 
3617   /// See AbstractAttribute::trackStatistics()
3618   void trackStatistics() const override {
3619     STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
3620   }
3621 };
3622 
3623 /// Dereferenceable attribute deduction for a call site return value.
3624 struct AADereferenceableCallSiteReturned final
3625     : AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl> {
3626   using Base =
3627       AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl>;
3628   AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A)
3629       : Base(IRP, A) {}
3630 
3631   /// See AbstractAttribute::trackStatistics()
3632   void trackStatistics() const override {
3633     STATS_DECLTRACK_CS_ATTR(dereferenceable);
3634   }
3635 };
3636 
3637 // ------------------------ Align Argument Attribute ------------------------
3638 
3639 static unsigned getKnownAlignForUse(Attributor &A,
3640                                     AbstractAttribute &QueryingAA,
3641                                     Value &AssociatedValue, const Use *U,
3642                                     const Instruction *I, bool &TrackUse) {
3643   // We need to follow common pointer manipulation uses to the accesses they
3644   // feed into.
3645   if (isa<CastInst>(I)) {
3646     // Follow all but ptr2int casts.
3647     TrackUse = !isa<PtrToIntInst>(I);
3648     return 0;
3649   }
3650   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3651     if (GEP->hasAllConstantIndices()) {
3652       TrackUse = true;
3653       return 0;
3654     }
3655   }
3656 
3657   MaybeAlign MA;
3658   if (const auto *CB = dyn_cast<CallBase>(I)) {
3659     if (CB->isBundleOperand(U) || CB->isCallee(U))
3660       return 0;
3661 
3662     unsigned ArgNo = CB->getArgOperandNo(U);
3663     IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
3664     // As long as we only use known information there is no need to track
3665     // dependences here.
3666     auto &AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP,
3667                                         /* TrackDependence */ false);
3668     MA = MaybeAlign(AlignAA.getKnownAlign());
3669   }
3670 
3671   const DataLayout &DL = A.getDataLayout();
3672   const Value *UseV = U->get();
3673   if (auto *SI = dyn_cast<StoreInst>(I)) {
3674     if (SI->getPointerOperand() == UseV)
3675       MA = SI->getAlign();
3676   } else if (auto *LI = dyn_cast<LoadInst>(I)) {
3677     if (LI->getPointerOperand() == UseV)
3678       MA = LI->getAlign();
3679   }
3680 
3681   if (!MA || *MA <= 1)
3682     return 0;
3683 
3684   unsigned Alignment = MA->value();
3685   int64_t Offset;
3686 
3687   if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) {
3688     if (Base == &AssociatedValue) {
3689       // BasePointerAddr + Offset = Alignment * Q for some integer Q.
3690       // So we can say that the maximum power of two which is a divisor of
3691       // gcd(Offset, Alignment) is an alignment.
3692 
3693       uint32_t gcd =
3694           greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), Alignment);
3695       Alignment = llvm::PowerOf2Floor(gcd);
3696     }
3697   }
3698 
3699   return Alignment;
3700 }
3701 
3702 struct AAAlignImpl : AAAlign {
3703   AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {}
3704 
3705   /// See AbstractAttribute::initialize(...).
3706   void initialize(Attributor &A) override {
3707     SmallVector<Attribute, 4> Attrs;
3708     getAttrs({Attribute::Alignment}, Attrs);
3709     for (const Attribute &Attr : Attrs)
3710       takeKnownMaximum(Attr.getValueAsInt());
3711 
3712     Value &V = getAssociatedValue();
3713     // TODO: This is a HACK to avoid getPointerAlignment to introduce a ptr2int
3714     //       use of the function pointer. This was caused by D73131. We want to
3715     //       avoid this for function pointers especially because we iterate
3716     //       their uses and int2ptr is not handled. It is not a correctness
3717     //       problem though!
3718     if (!V.getType()->getPointerElementType()->isFunctionTy())
3719       takeKnownMaximum(V.getPointerAlignment(A.getDataLayout()).value());
3720 
3721     if (getIRPosition().isFnInterfaceKind() &&
3722         (!getAnchorScope() ||
3723          !A.isFunctionIPOAmendable(*getAssociatedFunction()))) {
3724       indicatePessimisticFixpoint();
3725       return;
3726     }
3727 
3728     if (Instruction *CtxI = getCtxI())
3729       followUsesInMBEC(*this, A, getState(), *CtxI);
3730   }
3731 
3732   /// See AbstractAttribute::manifest(...).
3733   ChangeStatus manifest(Attributor &A) override {
3734     ChangeStatus LoadStoreChanged = ChangeStatus::UNCHANGED;
3735 
3736     // Check for users that allow alignment annotations.
3737     Value &AssociatedValue = getAssociatedValue();
3738     for (const Use &U : AssociatedValue.uses()) {
3739       if (auto *SI = dyn_cast<StoreInst>(U.getUser())) {
3740         if (SI->getPointerOperand() == &AssociatedValue)
3741           if (SI->getAlignment() < getAssumedAlign()) {
3742             STATS_DECLTRACK(AAAlign, Store,
3743                             "Number of times alignment added to a store");
3744             SI->setAlignment(Align(getAssumedAlign()));
3745             LoadStoreChanged = ChangeStatus::CHANGED;
3746           }
3747       } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) {
3748         if (LI->getPointerOperand() == &AssociatedValue)
3749           if (LI->getAlignment() < getAssumedAlign()) {
3750             LI->setAlignment(Align(getAssumedAlign()));
3751             STATS_DECLTRACK(AAAlign, Load,
3752                             "Number of times alignment added to a load");
3753             LoadStoreChanged = ChangeStatus::CHANGED;
3754           }
3755       }
3756     }
3757 
3758     ChangeStatus Changed = AAAlign::manifest(A);
3759 
3760     Align InheritAlign =
3761         getAssociatedValue().getPointerAlignment(A.getDataLayout());
3762     if (InheritAlign >= getAssumedAlign())
3763       return LoadStoreChanged;
3764     return Changed | LoadStoreChanged;
3765   }
3766 
3767   // TODO: Provide a helper to determine the implied ABI alignment and check in
3768   //       the existing manifest method and a new one for AAAlignImpl that value
3769   //       to avoid making the alignment explicit if it did not improve.
3770 
3771   /// See AbstractAttribute::getDeducedAttributes
3772   virtual void
3773   getDeducedAttributes(LLVMContext &Ctx,
3774                        SmallVectorImpl<Attribute> &Attrs) const override {
3775     if (getAssumedAlign() > 1)
3776       Attrs.emplace_back(
3777           Attribute::getWithAlignment(Ctx, Align(getAssumedAlign())));
3778   }
3779 
3780   /// See followUsesInMBEC
3781   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
3782                        AAAlign::StateType &State) {
3783     bool TrackUse = false;
3784 
3785     unsigned int KnownAlign =
3786         getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse);
3787     State.takeKnownMaximum(KnownAlign);
3788 
3789     return TrackUse;
3790   }
3791 
3792   /// See AbstractAttribute::getAsStr().
3793   const std::string getAsStr() const override {
3794     return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
3795                                 "-" + std::to_string(getAssumedAlign()) + ">")
3796                              : "unknown-align";
3797   }
3798 };
3799 
3800 /// Align attribute for a floating value.
3801 struct AAAlignFloating : AAAlignImpl {
3802   AAAlignFloating(const IRPosition &IRP, Attributor &A) : AAAlignImpl(IRP, A) {}
3803 
3804   /// See AbstractAttribute::updateImpl(...).
3805   ChangeStatus updateImpl(Attributor &A) override {
3806     const DataLayout &DL = A.getDataLayout();
3807 
3808     auto VisitValueCB = [&](Value &V, const Instruction *,
3809                             AAAlign::StateType &T, bool Stripped) -> bool {
3810       const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V));
3811       if (!Stripped && this == &AA) {
3812         // Use only IR information if we did not strip anything.
3813         Align PA = V.getPointerAlignment(DL);
3814         T.takeKnownMaximum(PA.value());
3815         T.indicatePessimisticFixpoint();
3816       } else {
3817         // Use abstract attribute information.
3818         const AAAlign::StateType &DS = AA.getState();
3819         T ^= DS;
3820       }
3821       return T.isValidState();
3822     };
3823 
3824     StateType T;
3825     if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T,
3826                                                    VisitValueCB, getCtxI()))
3827       return indicatePessimisticFixpoint();
3828 
3829     // TODO: If we know we visited all incoming values, thus no are assumed
3830     // dead, we can take the known information from the state T.
3831     return clampStateAndIndicateChange(getState(), T);
3832   }
3833 
3834   /// See AbstractAttribute::trackStatistics()
3835   void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
3836 };
3837 
3838 /// Align attribute for function return value.
3839 struct AAAlignReturned final
3840     : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
3841   AAAlignReturned(const IRPosition &IRP, Attributor &A)
3842       : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>(IRP, A) {}
3843 
3844   /// See AbstractAttribute::trackStatistics()
3845   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
3846 };
3847 
3848 /// Align attribute for function argument.
3849 struct AAAlignArgument final
3850     : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
3851   using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>;
3852   AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
3853 
3854   /// See AbstractAttribute::manifest(...).
3855   ChangeStatus manifest(Attributor &A) override {
3856     // If the associated argument is involved in a must-tail call we give up
3857     // because we would need to keep the argument alignments of caller and
3858     // callee in-sync. Just does not seem worth the trouble right now.
3859     if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
3860       return ChangeStatus::UNCHANGED;
3861     return Base::manifest(A);
3862   }
3863 
3864   /// See AbstractAttribute::trackStatistics()
3865   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
3866 };
3867 
3868 struct AAAlignCallSiteArgument final : AAAlignFloating {
3869   AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A)
3870       : AAAlignFloating(IRP, A) {}
3871 
3872   /// See AbstractAttribute::manifest(...).
3873   ChangeStatus manifest(Attributor &A) override {
3874     // If the associated argument is involved in a must-tail call we give up
3875     // because we would need to keep the argument alignments of caller and
3876     // callee in-sync. Just does not seem worth the trouble right now.
3877     if (Argument *Arg = getAssociatedArgument())
3878       if (A.getInfoCache().isInvolvedInMustTailCall(*Arg))
3879         return ChangeStatus::UNCHANGED;
3880     ChangeStatus Changed = AAAlignImpl::manifest(A);
3881     Align InheritAlign =
3882         getAssociatedValue().getPointerAlignment(A.getDataLayout());
3883     if (InheritAlign >= getAssumedAlign())
3884       Changed = ChangeStatus::UNCHANGED;
3885     return Changed;
3886   }
3887 
3888   /// See AbstractAttribute::updateImpl(Attributor &A).
3889   ChangeStatus updateImpl(Attributor &A) override {
3890     ChangeStatus Changed = AAAlignFloating::updateImpl(A);
3891     if (Argument *Arg = getAssociatedArgument()) {
3892       // We only take known information from the argument
3893       // so we do not need to track a dependence.
3894       const auto &ArgAlignAA = A.getAAFor<AAAlign>(
3895           *this, IRPosition::argument(*Arg), /* TrackDependence */ false);
3896       takeKnownMaximum(ArgAlignAA.getKnownAlign());
3897     }
3898     return Changed;
3899   }
3900 
3901   /// See AbstractAttribute::trackStatistics()
3902   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
3903 };
3904 
3905 /// Align attribute deduction for a call site return value.
3906 struct AAAlignCallSiteReturned final
3907     : AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl> {
3908   using Base = AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl>;
3909   AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A)
3910       : Base(IRP, A) {}
3911 
3912   /// See AbstractAttribute::initialize(...).
3913   void initialize(Attributor &A) override {
3914     Base::initialize(A);
3915     Function *F = getAssociatedFunction();
3916     if (!F)
3917       indicatePessimisticFixpoint();
3918   }
3919 
3920   /// See AbstractAttribute::trackStatistics()
3921   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); }
3922 };
3923 
3924 /// ------------------ Function No-Return Attribute ----------------------------
3925 struct AANoReturnImpl : public AANoReturn {
3926   AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {}
3927 
3928   /// See AbstractAttribute::initialize(...).
3929   void initialize(Attributor &A) override {
3930     AANoReturn::initialize(A);
3931     Function *F = getAssociatedFunction();
3932     if (!F)
3933       indicatePessimisticFixpoint();
3934   }
3935 
3936   /// See AbstractAttribute::getAsStr().
3937   const std::string getAsStr() const override {
3938     return getAssumed() ? "noreturn" : "may-return";
3939   }
3940 
3941   /// See AbstractAttribute::updateImpl(Attributor &A).
3942   virtual ChangeStatus updateImpl(Attributor &A) override {
3943     auto CheckForNoReturn = [](Instruction &) { return false; };
3944     if (!A.checkForAllInstructions(CheckForNoReturn, *this,
3945                                    {(unsigned)Instruction::Ret}))
3946       return indicatePessimisticFixpoint();
3947     return ChangeStatus::UNCHANGED;
3948   }
3949 };
3950 
3951 struct AANoReturnFunction final : AANoReturnImpl {
3952   AANoReturnFunction(const IRPosition &IRP, Attributor &A)
3953       : AANoReturnImpl(IRP, A) {}
3954 
3955   /// See AbstractAttribute::trackStatistics()
3956   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
3957 };
3958 
3959 /// NoReturn attribute deduction for a call sites.
3960 struct AANoReturnCallSite final : AANoReturnImpl {
3961   AANoReturnCallSite(const IRPosition &IRP, Attributor &A)
3962       : AANoReturnImpl(IRP, A) {}
3963 
3964   /// See AbstractAttribute::updateImpl(...).
3965   ChangeStatus updateImpl(Attributor &A) override {
3966     // TODO: Once we have call site specific value information we can provide
3967     //       call site specific liveness information and then it makes
3968     //       sense to specialize attributes for call sites arguments instead of
3969     //       redirecting requests to the callee argument.
3970     Function *F = getAssociatedFunction();
3971     const IRPosition &FnPos = IRPosition::function(*F);
3972     auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos);
3973     return clampStateAndIndicateChange(getState(), FnAA.getState());
3974   }
3975 
3976   /// See AbstractAttribute::trackStatistics()
3977   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); }
3978 };
3979 
3980 /// ----------------------- Variable Capturing ---------------------------------
3981 
3982 /// A class to hold the state of for no-capture attributes.
3983 struct AANoCaptureImpl : public AANoCapture {
3984   AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {}
3985 
3986   /// See AbstractAttribute::initialize(...).
3987   void initialize(Attributor &A) override {
3988     if (hasAttr(getAttrKind(), /* IgnoreSubsumingPositions */ true)) {
3989       indicateOptimisticFixpoint();
3990       return;
3991     }
3992     Function *AnchorScope = getAnchorScope();
3993     if (isFnInterfaceKind() &&
3994         (!AnchorScope || !A.isFunctionIPOAmendable(*AnchorScope))) {
3995       indicatePessimisticFixpoint();
3996       return;
3997     }
3998 
3999     // You cannot "capture" null in the default address space.
4000     if (isa<ConstantPointerNull>(getAssociatedValue()) &&
4001         getAssociatedValue().getType()->getPointerAddressSpace() == 0) {
4002       indicateOptimisticFixpoint();
4003       return;
4004     }
4005 
4006     const Function *F = getArgNo() >= 0 ? getAssociatedFunction() : AnchorScope;
4007 
4008     // Check what state the associated function can actually capture.
4009     if (F)
4010       determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
4011     else
4012       indicatePessimisticFixpoint();
4013   }
4014 
4015   /// See AbstractAttribute::updateImpl(...).
4016   ChangeStatus updateImpl(Attributor &A) override;
4017 
4018   /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...).
4019   virtual void
4020   getDeducedAttributes(LLVMContext &Ctx,
4021                        SmallVectorImpl<Attribute> &Attrs) const override {
4022     if (!isAssumedNoCaptureMaybeReturned())
4023       return;
4024 
4025     if (getArgNo() >= 0) {
4026       if (isAssumedNoCapture())
4027         Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture));
4028       else if (ManifestInternal)
4029         Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned"));
4030     }
4031   }
4032 
4033   /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known
4034   /// depending on the ability of the function associated with \p IRP to capture
4035   /// state in memory and through "returning/throwing", respectively.
4036   static void determineFunctionCaptureCapabilities(const IRPosition &IRP,
4037                                                    const Function &F,
4038                                                    BitIntegerState &State) {
4039     // TODO: Once we have memory behavior attributes we should use them here.
4040 
4041     // If we know we cannot communicate or write to memory, we do not care about
4042     // ptr2int anymore.
4043     if (F.onlyReadsMemory() && F.doesNotThrow() &&
4044         F.getReturnType()->isVoidTy()) {
4045       State.addKnownBits(NO_CAPTURE);
4046       return;
4047     }
4048 
4049     // A function cannot capture state in memory if it only reads memory, it can
4050     // however return/throw state and the state might be influenced by the
4051     // pointer value, e.g., loading from a returned pointer might reveal a bit.
4052     if (F.onlyReadsMemory())
4053       State.addKnownBits(NOT_CAPTURED_IN_MEM);
4054 
4055     // A function cannot communicate state back if it does not through
4056     // exceptions and doesn not return values.
4057     if (F.doesNotThrow() && F.getReturnType()->isVoidTy())
4058       State.addKnownBits(NOT_CAPTURED_IN_RET);
4059 
4060     // Check existing "returned" attributes.
4061     int ArgNo = IRP.getArgNo();
4062     if (F.doesNotThrow() && ArgNo >= 0) {
4063       for (unsigned u = 0, e = F.arg_size(); u < e; ++u)
4064         if (F.hasParamAttribute(u, Attribute::Returned)) {
4065           if (u == unsigned(ArgNo))
4066             State.removeAssumedBits(NOT_CAPTURED_IN_RET);
4067           else if (F.onlyReadsMemory())
4068             State.addKnownBits(NO_CAPTURE);
4069           else
4070             State.addKnownBits(NOT_CAPTURED_IN_RET);
4071           break;
4072         }
4073     }
4074   }
4075 
4076   /// See AbstractState::getAsStr().
4077   const std::string getAsStr() const override {
4078     if (isKnownNoCapture())
4079       return "known not-captured";
4080     if (isAssumedNoCapture())
4081       return "assumed not-captured";
4082     if (isKnownNoCaptureMaybeReturned())
4083       return "known not-captured-maybe-returned";
4084     if (isAssumedNoCaptureMaybeReturned())
4085       return "assumed not-captured-maybe-returned";
4086     return "assumed-captured";
4087   }
4088 };
4089 
4090 /// Attributor-aware capture tracker.
4091 struct AACaptureUseTracker final : public CaptureTracker {
4092 
4093   /// Create a capture tracker that can lookup in-flight abstract attributes
4094   /// through the Attributor \p A.
4095   ///
4096   /// If a use leads to a potential capture, \p CapturedInMemory is set and the
4097   /// search is stopped. If a use leads to a return instruction,
4098   /// \p CommunicatedBack is set to true and \p CapturedInMemory is not changed.
4099   /// If a use leads to a ptr2int which may capture the value,
4100   /// \p CapturedInInteger is set. If a use is found that is currently assumed
4101   /// "no-capture-maybe-returned", the user is added to the \p PotentialCopies
4102   /// set. All values in \p PotentialCopies are later tracked as well. For every
4103   /// explored use we decrement \p RemainingUsesToExplore. Once it reaches 0,
4104   /// the search is stopped with \p CapturedInMemory and \p CapturedInInteger
4105   /// conservatively set to true.
4106   AACaptureUseTracker(Attributor &A, AANoCapture &NoCaptureAA,
4107                       const AAIsDead &IsDeadAA, AANoCapture::StateType &State,
4108                       SmallVectorImpl<const Value *> &PotentialCopies,
4109                       unsigned &RemainingUsesToExplore)
4110       : A(A), NoCaptureAA(NoCaptureAA), IsDeadAA(IsDeadAA), State(State),
4111         PotentialCopies(PotentialCopies),
4112         RemainingUsesToExplore(RemainingUsesToExplore) {}
4113 
4114   /// Determine if \p V maybe captured. *Also updates the state!*
4115   bool valueMayBeCaptured(const Value *V) {
4116     if (V->getType()->isPointerTy()) {
4117       PointerMayBeCaptured(V, this);
4118     } else {
4119       State.indicatePessimisticFixpoint();
4120     }
4121     return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
4122   }
4123 
4124   /// See CaptureTracker::tooManyUses().
4125   void tooManyUses() override {
4126     State.removeAssumedBits(AANoCapture::NO_CAPTURE);
4127   }
4128 
4129   bool isDereferenceableOrNull(Value *O, const DataLayout &DL) override {
4130     if (CaptureTracker::isDereferenceableOrNull(O, DL))
4131       return true;
4132     const auto &DerefAA = A.getAAFor<AADereferenceable>(
4133         NoCaptureAA, IRPosition::value(*O), /* TrackDependence */ true,
4134         DepClassTy::OPTIONAL);
4135     return DerefAA.getAssumedDereferenceableBytes();
4136   }
4137 
4138   /// See CaptureTracker::captured(...).
4139   bool captured(const Use *U) override {
4140     Instruction *UInst = cast<Instruction>(U->getUser());
4141     LLVM_DEBUG(dbgs() << "Check use: " << *U->get() << " in " << *UInst
4142                       << "\n");
4143 
4144     // Because we may reuse the tracker multiple times we keep track of the
4145     // number of explored uses ourselves as well.
4146     if (RemainingUsesToExplore-- == 0) {
4147       LLVM_DEBUG(dbgs() << " - too many uses to explore!\n");
4148       return isCapturedIn(/* Memory */ true, /* Integer */ true,
4149                           /* Return */ true);
4150     }
4151 
4152     // Deal with ptr2int by following uses.
4153     if (isa<PtrToIntInst>(UInst)) {
4154       LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n");
4155       return valueMayBeCaptured(UInst);
4156     }
4157 
4158     // Explicitly catch return instructions.
4159     if (isa<ReturnInst>(UInst))
4160       return isCapturedIn(/* Memory */ false, /* Integer */ false,
4161                           /* Return */ true);
4162 
4163     // For now we only use special logic for call sites. However, the tracker
4164     // itself knows about a lot of other non-capturing cases already.
4165     auto *CB = dyn_cast<CallBase>(UInst);
4166     if (!CB || !CB->isArgOperand(U))
4167       return isCapturedIn(/* Memory */ true, /* Integer */ true,
4168                           /* Return */ true);
4169 
4170     unsigned ArgNo = CB->getArgOperandNo(U);
4171     const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo);
4172     // If we have a abstract no-capture attribute for the argument we can use
4173     // it to justify a non-capture attribute here. This allows recursion!
4174     auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(NoCaptureAA, CSArgPos);
4175     if (ArgNoCaptureAA.isAssumedNoCapture())
4176       return isCapturedIn(/* Memory */ false, /* Integer */ false,
4177                           /* Return */ false);
4178     if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
4179       addPotentialCopy(*CB);
4180       return isCapturedIn(/* Memory */ false, /* Integer */ false,
4181                           /* Return */ false);
4182     }
4183 
4184     // Lastly, we could not find a reason no-capture can be assumed so we don't.
4185     return isCapturedIn(/* Memory */ true, /* Integer */ true,
4186                         /* Return */ true);
4187   }
4188 
4189   /// Register \p CS as potential copy of the value we are checking.
4190   void addPotentialCopy(CallBase &CB) { PotentialCopies.push_back(&CB); }
4191 
4192   /// See CaptureTracker::shouldExplore(...).
4193   bool shouldExplore(const Use *U) override {
4194     // Check liveness and ignore droppable users.
4195     return !U->getUser()->isDroppable() &&
4196            !A.isAssumedDead(*U, &NoCaptureAA, &IsDeadAA);
4197   }
4198 
4199   /// Update the state according to \p CapturedInMem, \p CapturedInInt, and
4200   /// \p CapturedInRet, then return the appropriate value for use in the
4201   /// CaptureTracker::captured() interface.
4202   bool isCapturedIn(bool CapturedInMem, bool CapturedInInt,
4203                     bool CapturedInRet) {
4204     LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int "
4205                       << CapturedInInt << "|Ret " << CapturedInRet << "]\n");
4206     if (CapturedInMem)
4207       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM);
4208     if (CapturedInInt)
4209       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT);
4210     if (CapturedInRet)
4211       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET);
4212     return !State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
4213   }
4214 
4215 private:
4216   /// The attributor providing in-flight abstract attributes.
4217   Attributor &A;
4218 
4219   /// The abstract attribute currently updated.
4220   AANoCapture &NoCaptureAA;
4221 
4222   /// The abstract liveness state.
4223   const AAIsDead &IsDeadAA;
4224 
4225   /// The state currently updated.
4226   AANoCapture::StateType &State;
4227 
4228   /// Set of potential copies of the tracked value.
4229   SmallVectorImpl<const Value *> &PotentialCopies;
4230 
4231   /// Global counter to limit the number of explored uses.
4232   unsigned &RemainingUsesToExplore;
4233 };
4234 
4235 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) {
4236   const IRPosition &IRP = getIRPosition();
4237   const Value *V =
4238       getArgNo() >= 0 ? IRP.getAssociatedArgument() : &IRP.getAssociatedValue();
4239   if (!V)
4240     return indicatePessimisticFixpoint();
4241 
4242   const Function *F =
4243       getArgNo() >= 0 ? IRP.getAssociatedFunction() : IRP.getAnchorScope();
4244   assert(F && "Expected a function!");
4245   const IRPosition &FnPos = IRPosition::function(*F);
4246   const auto &IsDeadAA =
4247       A.getAAFor<AAIsDead>(*this, FnPos, /* TrackDependence */ false);
4248 
4249   AANoCapture::StateType T;
4250 
4251   // Readonly means we cannot capture through memory.
4252   const auto &FnMemAA =
4253       A.getAAFor<AAMemoryBehavior>(*this, FnPos, /* TrackDependence */ false);
4254   if (FnMemAA.isAssumedReadOnly()) {
4255     T.addKnownBits(NOT_CAPTURED_IN_MEM);
4256     if (FnMemAA.isKnownReadOnly())
4257       addKnownBits(NOT_CAPTURED_IN_MEM);
4258     else
4259       A.recordDependence(FnMemAA, *this, DepClassTy::OPTIONAL);
4260   }
4261 
4262   // Make sure all returned values are different than the underlying value.
4263   // TODO: we could do this in a more sophisticated way inside
4264   //       AAReturnedValues, e.g., track all values that escape through returns
4265   //       directly somehow.
4266   auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) {
4267     bool SeenConstant = false;
4268     for (auto &It : RVAA.returned_values()) {
4269       if (isa<Constant>(It.first)) {
4270         if (SeenConstant)
4271           return false;
4272         SeenConstant = true;
4273       } else if (!isa<Argument>(It.first) ||
4274                  It.first == getAssociatedArgument())
4275         return false;
4276     }
4277     return true;
4278   };
4279 
4280   const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(
4281       *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
4282   if (NoUnwindAA.isAssumedNoUnwind()) {
4283     bool IsVoidTy = F->getReturnType()->isVoidTy();
4284     const AAReturnedValues *RVAA =
4285         IsVoidTy ? nullptr
4286                  : &A.getAAFor<AAReturnedValues>(*this, FnPos,
4287                                                  /* TrackDependence */ true,
4288                                                  DepClassTy::OPTIONAL);
4289     if (IsVoidTy || CheckReturnedArgs(*RVAA)) {
4290       T.addKnownBits(NOT_CAPTURED_IN_RET);
4291       if (T.isKnown(NOT_CAPTURED_IN_MEM))
4292         return ChangeStatus::UNCHANGED;
4293       if (NoUnwindAA.isKnownNoUnwind() &&
4294           (IsVoidTy || RVAA->getState().isAtFixpoint())) {
4295         addKnownBits(NOT_CAPTURED_IN_RET);
4296         if (isKnown(NOT_CAPTURED_IN_MEM))
4297           return indicateOptimisticFixpoint();
4298       }
4299     }
4300   }
4301 
4302   // Use the CaptureTracker interface and logic with the specialized tracker,
4303   // defined in AACaptureUseTracker, that can look at in-flight abstract
4304   // attributes and directly updates the assumed state.
4305   SmallVector<const Value *, 4> PotentialCopies;
4306   unsigned RemainingUsesToExplore =
4307       getDefaultMaxUsesToExploreForCaptureTracking();
4308   AACaptureUseTracker Tracker(A, *this, IsDeadAA, T, PotentialCopies,
4309                               RemainingUsesToExplore);
4310 
4311   // Check all potential copies of the associated value until we can assume
4312   // none will be captured or we have to assume at least one might be.
4313   unsigned Idx = 0;
4314   PotentialCopies.push_back(V);
4315   while (T.isAssumed(NO_CAPTURE_MAYBE_RETURNED) && Idx < PotentialCopies.size())
4316     Tracker.valueMayBeCaptured(PotentialCopies[Idx++]);
4317 
4318   AANoCapture::StateType &S = getState();
4319   auto Assumed = S.getAssumed();
4320   S.intersectAssumedBits(T.getAssumed());
4321   if (!isAssumedNoCaptureMaybeReturned())
4322     return indicatePessimisticFixpoint();
4323   return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
4324                                    : ChangeStatus::CHANGED;
4325 }
4326 
4327 /// NoCapture attribute for function arguments.
4328 struct AANoCaptureArgument final : AANoCaptureImpl {
4329   AANoCaptureArgument(const IRPosition &IRP, Attributor &A)
4330       : AANoCaptureImpl(IRP, A) {}
4331 
4332   /// See AbstractAttribute::trackStatistics()
4333   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) }
4334 };
4335 
4336 /// NoCapture attribute for call site arguments.
4337 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
4338   AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A)
4339       : AANoCaptureImpl(IRP, A) {}
4340 
4341   /// See AbstractAttribute::initialize(...).
4342   void initialize(Attributor &A) override {
4343     if (Argument *Arg = getAssociatedArgument())
4344       if (Arg->hasByValAttr())
4345         indicateOptimisticFixpoint();
4346     AANoCaptureImpl::initialize(A);
4347   }
4348 
4349   /// See AbstractAttribute::updateImpl(...).
4350   ChangeStatus updateImpl(Attributor &A) override {
4351     // TODO: Once we have call site specific value information we can provide
4352     //       call site specific liveness information and then it makes
4353     //       sense to specialize attributes for call sites arguments instead of
4354     //       redirecting requests to the callee argument.
4355     Argument *Arg = getAssociatedArgument();
4356     if (!Arg)
4357       return indicatePessimisticFixpoint();
4358     const IRPosition &ArgPos = IRPosition::argument(*Arg);
4359     auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos);
4360     return clampStateAndIndicateChange(getState(), ArgAA.getState());
4361   }
4362 
4363   /// See AbstractAttribute::trackStatistics()
4364   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)};
4365 };
4366 
4367 /// NoCapture attribute for floating values.
4368 struct AANoCaptureFloating final : AANoCaptureImpl {
4369   AANoCaptureFloating(const IRPosition &IRP, Attributor &A)
4370       : AANoCaptureImpl(IRP, A) {}
4371 
4372   /// See AbstractAttribute::trackStatistics()
4373   void trackStatistics() const override {
4374     STATS_DECLTRACK_FLOATING_ATTR(nocapture)
4375   }
4376 };
4377 
4378 /// NoCapture attribute for function return value.
4379 struct AANoCaptureReturned final : AANoCaptureImpl {
4380   AANoCaptureReturned(const IRPosition &IRP, Attributor &A)
4381       : AANoCaptureImpl(IRP, A) {
4382     llvm_unreachable("NoCapture is not applicable to function returns!");
4383   }
4384 
4385   /// See AbstractAttribute::initialize(...).
4386   void initialize(Attributor &A) override {
4387     llvm_unreachable("NoCapture is not applicable to function returns!");
4388   }
4389 
4390   /// See AbstractAttribute::updateImpl(...).
4391   ChangeStatus updateImpl(Attributor &A) override {
4392     llvm_unreachable("NoCapture is not applicable to function returns!");
4393   }
4394 
4395   /// See AbstractAttribute::trackStatistics()
4396   void trackStatistics() const override {}
4397 };
4398 
4399 /// NoCapture attribute deduction for a call site return value.
4400 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
4401   AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A)
4402       : AANoCaptureImpl(IRP, A) {}
4403 
4404   /// See AbstractAttribute::trackStatistics()
4405   void trackStatistics() const override {
4406     STATS_DECLTRACK_CSRET_ATTR(nocapture)
4407   }
4408 };
4409 
4410 /// ------------------ Value Simplify Attribute ----------------------------
4411 struct AAValueSimplifyImpl : AAValueSimplify {
4412   AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A)
4413       : AAValueSimplify(IRP, A) {}
4414 
4415   /// See AbstractAttribute::initialize(...).
4416   void initialize(Attributor &A) override {
4417     if (getAssociatedValue().getType()->isVoidTy())
4418       indicatePessimisticFixpoint();
4419   }
4420 
4421   /// See AbstractAttribute::getAsStr().
4422   const std::string getAsStr() const override {
4423     return getAssumed() ? (getKnown() ? "simplified" : "maybe-simple")
4424                         : "not-simple";
4425   }
4426 
4427   /// See AbstractAttribute::trackStatistics()
4428   void trackStatistics() const override {}
4429 
4430   /// See AAValueSimplify::getAssumedSimplifiedValue()
4431   Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override {
4432     if (!getAssumed())
4433       return const_cast<Value *>(&getAssociatedValue());
4434     return SimplifiedAssociatedValue;
4435   }
4436 
4437   /// Helper function for querying AAValueSimplify and updating candicate.
4438   /// \param QueryingValue Value trying to unify with SimplifiedValue
4439   /// \param AccumulatedSimplifiedValue Current simplification result.
4440   static bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA,
4441                              Value &QueryingValue,
4442                              Optional<Value *> &AccumulatedSimplifiedValue) {
4443     // FIXME: Add a typecast support.
4444 
4445     auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>(
4446         QueryingAA, IRPosition::value(QueryingValue));
4447 
4448     Optional<Value *> QueryingValueSimplified =
4449         ValueSimplifyAA.getAssumedSimplifiedValue(A);
4450 
4451     if (!QueryingValueSimplified.hasValue())
4452       return true;
4453 
4454     if (!QueryingValueSimplified.getValue())
4455       return false;
4456 
4457     Value &QueryingValueSimplifiedUnwrapped =
4458         *QueryingValueSimplified.getValue();
4459 
4460     if (AccumulatedSimplifiedValue.hasValue() &&
4461         !isa<UndefValue>(AccumulatedSimplifiedValue.getValue()) &&
4462         !isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
4463       return AccumulatedSimplifiedValue == QueryingValueSimplified;
4464     if (AccumulatedSimplifiedValue.hasValue() &&
4465         isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
4466       return true;
4467 
4468     LLVM_DEBUG(dbgs() << "[ValueSimplify] " << QueryingValue
4469                       << " is assumed to be "
4470                       << QueryingValueSimplifiedUnwrapped << "\n");
4471 
4472     AccumulatedSimplifiedValue = QueryingValueSimplified;
4473     return true;
4474   }
4475 
4476   /// Returns a candidate is found or not
4477   template <typename AAType> bool askSimplifiedValueFor(Attributor &A) {
4478     if (!getAssociatedValue().getType()->isIntegerTy())
4479       return false;
4480 
4481     const auto &AA =
4482         A.getAAFor<AAType>(*this, getIRPosition(), /* TrackDependence */ false);
4483 
4484     Optional<ConstantInt *> COpt = AA.getAssumedConstantInt(A);
4485 
4486     if (!COpt.hasValue()) {
4487       SimplifiedAssociatedValue = llvm::None;
4488       A.recordDependence(AA, *this, DepClassTy::OPTIONAL);
4489       return true;
4490     }
4491     if (auto *C = COpt.getValue()) {
4492       SimplifiedAssociatedValue = C;
4493       A.recordDependence(AA, *this, DepClassTy::OPTIONAL);
4494       return true;
4495     }
4496     return false;
4497   }
4498 
4499   bool askSimplifiedValueForOtherAAs(Attributor &A) {
4500     if (askSimplifiedValueFor<AAValueConstantRange>(A))
4501       return true;
4502     if (askSimplifiedValueFor<AAPotentialValues>(A))
4503       return true;
4504     return false;
4505   }
4506 
4507   /// See AbstractAttribute::manifest(...).
4508   ChangeStatus manifest(Attributor &A) override {
4509     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4510 
4511     if (SimplifiedAssociatedValue.hasValue() &&
4512         !SimplifiedAssociatedValue.getValue())
4513       return Changed;
4514 
4515     Value &V = getAssociatedValue();
4516     auto *C = SimplifiedAssociatedValue.hasValue()
4517                   ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
4518                   : UndefValue::get(V.getType());
4519     if (C) {
4520       // We can replace the AssociatedValue with the constant.
4521       if (!V.user_empty() && &V != C && V.getType() == C->getType()) {
4522         LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *C
4523                           << " :: " << *this << "\n");
4524         if (A.changeValueAfterManifest(V, *C))
4525           Changed = ChangeStatus::CHANGED;
4526       }
4527     }
4528 
4529     return Changed | AAValueSimplify::manifest(A);
4530   }
4531 
4532   /// See AbstractState::indicatePessimisticFixpoint(...).
4533   ChangeStatus indicatePessimisticFixpoint() override {
4534     // NOTE: Associated value will be returned in a pessimistic fixpoint and is
4535     // regarded as known. That's why`indicateOptimisticFixpoint` is called.
4536     SimplifiedAssociatedValue = &getAssociatedValue();
4537     indicateOptimisticFixpoint();
4538     return ChangeStatus::CHANGED;
4539   }
4540 
4541 protected:
4542   // An assumed simplified value. Initially, it is set to Optional::None, which
4543   // means that the value is not clear under current assumption. If in the
4544   // pessimistic state, getAssumedSimplifiedValue doesn't return this value but
4545   // returns orignal associated value.
4546   Optional<Value *> SimplifiedAssociatedValue;
4547 };
4548 
4549 struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
4550   AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A)
4551       : AAValueSimplifyImpl(IRP, A) {}
4552 
4553   void initialize(Attributor &A) override {
4554     AAValueSimplifyImpl::initialize(A);
4555     if (!getAnchorScope() || getAnchorScope()->isDeclaration())
4556       indicatePessimisticFixpoint();
4557     if (hasAttr({Attribute::InAlloca, Attribute::Preallocated,
4558                  Attribute::StructRet, Attribute::Nest},
4559                 /* IgnoreSubsumingPositions */ true))
4560       indicatePessimisticFixpoint();
4561 
4562     // FIXME: This is a hack to prevent us from propagating function poiner in
4563     // the new pass manager CGSCC pass as it creates call edges the
4564     // CallGraphUpdater cannot handle yet.
4565     Value &V = getAssociatedValue();
4566     if (V.getType()->isPointerTy() &&
4567         V.getType()->getPointerElementType()->isFunctionTy() &&
4568         !A.isModulePass())
4569       indicatePessimisticFixpoint();
4570   }
4571 
4572   /// See AbstractAttribute::updateImpl(...).
4573   ChangeStatus updateImpl(Attributor &A) override {
4574     // Byval is only replacable if it is readonly otherwise we would write into
4575     // the replaced value and not the copy that byval creates implicitly.
4576     Argument *Arg = getAssociatedArgument();
4577     if (Arg->hasByValAttr()) {
4578       // TODO: We probably need to verify synchronization is not an issue, e.g.,
4579       //       there is no race by not copying a constant byval.
4580       const auto &MemAA = A.getAAFor<AAMemoryBehavior>(*this, getIRPosition());
4581       if (!MemAA.isAssumedReadOnly())
4582         return indicatePessimisticFixpoint();
4583     }
4584 
4585     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4586 
4587     auto PredForCallSite = [&](AbstractCallSite ACS) {
4588       const IRPosition &ACSArgPos =
4589           IRPosition::callsite_argument(ACS, getArgNo());
4590       // Check if a coresponding argument was found or if it is on not
4591       // associated (which can happen for callback calls).
4592       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
4593         return false;
4594 
4595       // We can only propagate thread independent values through callbacks.
4596       // This is different to direct/indirect call sites because for them we
4597       // know the thread executing the caller and callee is the same. For
4598       // callbacks this is not guaranteed, thus a thread dependent value could
4599       // be different for the caller and callee, making it invalid to propagate.
4600       Value &ArgOp = ACSArgPos.getAssociatedValue();
4601       if (ACS.isCallbackCall())
4602         if (auto *C = dyn_cast<Constant>(&ArgOp))
4603           if (C->isThreadDependent())
4604             return false;
4605       return checkAndUpdate(A, *this, ArgOp, SimplifiedAssociatedValue);
4606     };
4607 
4608     bool AllCallSitesKnown;
4609     if (!A.checkForAllCallSites(PredForCallSite, *this, true,
4610                                 AllCallSitesKnown))
4611       if (!askSimplifiedValueForOtherAAs(A))
4612         return indicatePessimisticFixpoint();
4613 
4614     // If a candicate was found in this update, return CHANGED.
4615     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4616                ? ChangeStatus::UNCHANGED
4617                : ChangeStatus ::CHANGED;
4618   }
4619 
4620   /// See AbstractAttribute::trackStatistics()
4621   void trackStatistics() const override {
4622     STATS_DECLTRACK_ARG_ATTR(value_simplify)
4623   }
4624 };
4625 
4626 struct AAValueSimplifyReturned : AAValueSimplifyImpl {
4627   AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A)
4628       : AAValueSimplifyImpl(IRP, A) {}
4629 
4630   /// See AbstractAttribute::updateImpl(...).
4631   ChangeStatus updateImpl(Attributor &A) override {
4632     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4633 
4634     auto PredForReturned = [&](Value &V) {
4635       return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue);
4636     };
4637 
4638     if (!A.checkForAllReturnedValues(PredForReturned, *this))
4639       if (!askSimplifiedValueForOtherAAs(A))
4640         return indicatePessimisticFixpoint();
4641 
4642     // If a candicate was found in this update, return CHANGED.
4643     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4644                ? ChangeStatus::UNCHANGED
4645                : ChangeStatus ::CHANGED;
4646   }
4647 
4648   ChangeStatus manifest(Attributor &A) override {
4649     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4650 
4651     if (SimplifiedAssociatedValue.hasValue() &&
4652         !SimplifiedAssociatedValue.getValue())
4653       return Changed;
4654 
4655     Value &V = getAssociatedValue();
4656     auto *C = SimplifiedAssociatedValue.hasValue()
4657                   ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
4658                   : UndefValue::get(V.getType());
4659     if (C) {
4660       auto PredForReturned =
4661           [&](Value &V, const SmallSetVector<ReturnInst *, 4> &RetInsts) {
4662             // We can replace the AssociatedValue with the constant.
4663             if (&V == C || V.getType() != C->getType() || isa<UndefValue>(V))
4664               return true;
4665 
4666             for (ReturnInst *RI : RetInsts) {
4667               if (RI->getFunction() != getAnchorScope())
4668                 continue;
4669               auto *RC = C;
4670               if (RC->getType() != RI->getReturnValue()->getType())
4671                 RC = ConstantExpr::getBitCast(RC,
4672                                               RI->getReturnValue()->getType());
4673               LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *RC
4674                                 << " in " << *RI << " :: " << *this << "\n");
4675               if (A.changeUseAfterManifest(RI->getOperandUse(0), *RC))
4676                 Changed = ChangeStatus::CHANGED;
4677             }
4678             return true;
4679           };
4680       A.checkForAllReturnedValuesAndReturnInsts(PredForReturned, *this);
4681     }
4682 
4683     return Changed | AAValueSimplify::manifest(A);
4684   }
4685 
4686   /// See AbstractAttribute::trackStatistics()
4687   void trackStatistics() const override {
4688     STATS_DECLTRACK_FNRET_ATTR(value_simplify)
4689   }
4690 };
4691 
4692 struct AAValueSimplifyFloating : AAValueSimplifyImpl {
4693   AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A)
4694       : AAValueSimplifyImpl(IRP, A) {}
4695 
4696   /// See AbstractAttribute::initialize(...).
4697   void initialize(Attributor &A) override {
4698     // FIXME: This might have exposed a SCC iterator update bug in the old PM.
4699     //        Needs investigation.
4700     // AAValueSimplifyImpl::initialize(A);
4701     Value &V = getAnchorValue();
4702 
4703     // TODO: add other stuffs
4704     if (isa<Constant>(V))
4705       indicatePessimisticFixpoint();
4706   }
4707 
4708   /// Check if \p ICmp is an equality comparison (==/!=) with at least one
4709   /// nullptr. If so, try to simplify it using AANonNull on the other operand.
4710   /// Return true if successful, in that case SimplifiedAssociatedValue will be
4711   /// updated and \p Changed is set appropriately.
4712   bool checkForNullPtrCompare(Attributor &A, ICmpInst *ICmp,
4713                               ChangeStatus &Changed) {
4714     if (!ICmp)
4715       return false;
4716     if (!ICmp->isEquality())
4717       return false;
4718 
4719     // This is a comparison with == or !-. We check for nullptr now.
4720     bool Op0IsNull = isa<ConstantPointerNull>(ICmp->getOperand(0));
4721     bool Op1IsNull = isa<ConstantPointerNull>(ICmp->getOperand(1));
4722     if (!Op0IsNull && !Op1IsNull)
4723       return false;
4724 
4725     LLVMContext &Ctx = ICmp->getContext();
4726     // Check for `nullptr ==/!= nullptr` first:
4727     if (Op0IsNull && Op1IsNull) {
4728       Value *NewVal = ConstantInt::get(
4729           Type::getInt1Ty(Ctx), ICmp->getPredicate() == CmpInst::ICMP_EQ);
4730       SimplifiedAssociatedValue = NewVal;
4731       indicateOptimisticFixpoint();
4732       assert(!SimplifiedAssociatedValue.hasValue() &&
4733              "Did not expect non-fixed value for constant comparison");
4734       Changed = ChangeStatus::CHANGED;
4735       return true;
4736     }
4737 
4738     // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the
4739     // non-nullptr operand and if we assume it's non-null we can conclude the
4740     // result of the comparison.
4741     assert((Op0IsNull || Op1IsNull) &&
4742            "Expected nullptr versus non-nullptr comparison at this point");
4743 
4744     // The index is the operand that we assume is not null.
4745     unsigned PtrIdx = Op0IsNull;
4746     auto &PtrNonNullAA = A.getAAFor<AANonNull>(
4747         *this, IRPosition::value(*ICmp->getOperand(PtrIdx)));
4748     if (!PtrNonNullAA.isAssumedNonNull())
4749       return false;
4750 
4751     // The new value depends on the predicate, true for != and false for ==.
4752     Value *NewVal = ConstantInt::get(Type::getInt1Ty(Ctx),
4753                                      ICmp->getPredicate() == CmpInst::ICMP_NE);
4754 
4755     assert((!SimplifiedAssociatedValue.hasValue() ||
4756             SimplifiedAssociatedValue == NewVal) &&
4757            "Did not expect to change value for zero-comparison");
4758 
4759     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4760     SimplifiedAssociatedValue = NewVal;
4761 
4762     if (PtrNonNullAA.isKnownNonNull())
4763       indicateOptimisticFixpoint();
4764 
4765     Changed = HasValueBefore ? ChangeStatus::UNCHANGED : ChangeStatus ::CHANGED;
4766     return true;
4767   }
4768 
4769   /// See AbstractAttribute::updateImpl(...).
4770   ChangeStatus updateImpl(Attributor &A) override {
4771     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4772 
4773     ChangeStatus Changed;
4774     if (checkForNullPtrCompare(A, dyn_cast<ICmpInst>(&getAnchorValue()),
4775                                Changed))
4776       return Changed;
4777 
4778     auto VisitValueCB = [&](Value &V, const Instruction *CtxI, bool &,
4779                             bool Stripped) -> bool {
4780       auto &AA = A.getAAFor<AAValueSimplify>(*this, IRPosition::value(V));
4781       if (!Stripped && this == &AA) {
4782         // TODO: Look the instruction and check recursively.
4783 
4784         LLVM_DEBUG(dbgs() << "[ValueSimplify] Can't be stripped more : " << V
4785                           << "\n");
4786         return false;
4787       }
4788       return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue);
4789     };
4790 
4791     bool Dummy = false;
4792     if (!genericValueTraversal<AAValueSimplify, bool>(
4793             A, getIRPosition(), *this, Dummy, VisitValueCB, getCtxI(),
4794             /* UseValueSimplify */ false))
4795       if (!askSimplifiedValueForOtherAAs(A))
4796         return indicatePessimisticFixpoint();
4797 
4798     // If a candicate was found in this update, return CHANGED.
4799 
4800     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4801                ? ChangeStatus::UNCHANGED
4802                : ChangeStatus ::CHANGED;
4803   }
4804 
4805   /// See AbstractAttribute::trackStatistics()
4806   void trackStatistics() const override {
4807     STATS_DECLTRACK_FLOATING_ATTR(value_simplify)
4808   }
4809 };
4810 
4811 struct AAValueSimplifyFunction : AAValueSimplifyImpl {
4812   AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A)
4813       : AAValueSimplifyImpl(IRP, A) {}
4814 
4815   /// See AbstractAttribute::initialize(...).
4816   void initialize(Attributor &A) override {
4817     SimplifiedAssociatedValue = &getAnchorValue();
4818     indicateOptimisticFixpoint();
4819   }
4820   /// See AbstractAttribute::initialize(...).
4821   ChangeStatus updateImpl(Attributor &A) override {
4822     llvm_unreachable(
4823         "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
4824   }
4825   /// See AbstractAttribute::trackStatistics()
4826   void trackStatistics() const override {
4827     STATS_DECLTRACK_FN_ATTR(value_simplify)
4828   }
4829 };
4830 
4831 struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
4832   AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A)
4833       : AAValueSimplifyFunction(IRP, A) {}
4834   /// See AbstractAttribute::trackStatistics()
4835   void trackStatistics() const override {
4836     STATS_DECLTRACK_CS_ATTR(value_simplify)
4837   }
4838 };
4839 
4840 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyReturned {
4841   AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A)
4842       : AAValueSimplifyReturned(IRP, A) {}
4843 
4844   /// See AbstractAttribute::manifest(...).
4845   ChangeStatus manifest(Attributor &A) override {
4846     return AAValueSimplifyImpl::manifest(A);
4847   }
4848 
4849   void trackStatistics() const override {
4850     STATS_DECLTRACK_CSRET_ATTR(value_simplify)
4851   }
4852 };
4853 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
4854   AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A)
4855       : AAValueSimplifyFloating(IRP, A) {}
4856 
4857   /// See AbstractAttribute::manifest(...).
4858   ChangeStatus manifest(Attributor &A) override {
4859     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4860 
4861     if (SimplifiedAssociatedValue.hasValue() &&
4862         !SimplifiedAssociatedValue.getValue())
4863       return Changed;
4864 
4865     Value &V = getAssociatedValue();
4866     auto *C = SimplifiedAssociatedValue.hasValue()
4867                   ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
4868                   : UndefValue::get(V.getType());
4869     if (C) {
4870       Use &U = cast<CallBase>(&getAnchorValue())->getArgOperandUse(getArgNo());
4871       // We can replace the AssociatedValue with the constant.
4872       if (&V != C && V.getType() == C->getType()) {
4873         if (A.changeUseAfterManifest(U, *C))
4874           Changed = ChangeStatus::CHANGED;
4875       }
4876     }
4877 
4878     return Changed | AAValueSimplify::manifest(A);
4879   }
4880 
4881   void trackStatistics() const override {
4882     STATS_DECLTRACK_CSARG_ATTR(value_simplify)
4883   }
4884 };
4885 
4886 /// ----------------------- Heap-To-Stack Conversion ---------------------------
4887 struct AAHeapToStackImpl : public AAHeapToStack {
4888   AAHeapToStackImpl(const IRPosition &IRP, Attributor &A)
4889       : AAHeapToStack(IRP, A) {}
4890 
4891   const std::string getAsStr() const override {
4892     return "[H2S] Mallocs: " + std::to_string(MallocCalls.size());
4893   }
4894 
4895   ChangeStatus manifest(Attributor &A) override {
4896     assert(getState().isValidState() &&
4897            "Attempted to manifest an invalid state!");
4898 
4899     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
4900     Function *F = getAnchorScope();
4901     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
4902 
4903     for (Instruction *MallocCall : MallocCalls) {
4904       // This malloc cannot be replaced.
4905       if (BadMallocCalls.count(MallocCall))
4906         continue;
4907 
4908       for (Instruction *FreeCall : FreesForMalloc[MallocCall]) {
4909         LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n");
4910         A.deleteAfterManifest(*FreeCall);
4911         HasChanged = ChangeStatus::CHANGED;
4912       }
4913 
4914       LLVM_DEBUG(dbgs() << "H2S: Removing malloc call: " << *MallocCall
4915                         << "\n");
4916 
4917       Align Alignment;
4918       Constant *Size;
4919       if (isCallocLikeFn(MallocCall, TLI)) {
4920         auto *Num = cast<ConstantInt>(MallocCall->getOperand(0));
4921         auto *SizeT = cast<ConstantInt>(MallocCall->getOperand(1));
4922         APInt TotalSize = SizeT->getValue() * Num->getValue();
4923         Size =
4924             ConstantInt::get(MallocCall->getOperand(0)->getType(), TotalSize);
4925       } else if (isAlignedAllocLikeFn(MallocCall, TLI)) {
4926         Size = cast<ConstantInt>(MallocCall->getOperand(1));
4927         Alignment = MaybeAlign(cast<ConstantInt>(MallocCall->getOperand(0))
4928                                    ->getValue()
4929                                    .getZExtValue())
4930                         .valueOrOne();
4931       } else {
4932         Size = cast<ConstantInt>(MallocCall->getOperand(0));
4933       }
4934 
4935       unsigned AS = cast<PointerType>(MallocCall->getType())->getAddressSpace();
4936       Instruction *AI =
4937           new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment,
4938                          "", MallocCall->getNextNode());
4939 
4940       if (AI->getType() != MallocCall->getType())
4941         AI = new BitCastInst(AI, MallocCall->getType(), "malloc_bc",
4942                              AI->getNextNode());
4943 
4944       A.changeValueAfterManifest(*MallocCall, *AI);
4945 
4946       if (auto *II = dyn_cast<InvokeInst>(MallocCall)) {
4947         auto *NBB = II->getNormalDest();
4948         BranchInst::Create(NBB, MallocCall->getParent());
4949         A.deleteAfterManifest(*MallocCall);
4950       } else {
4951         A.deleteAfterManifest(*MallocCall);
4952       }
4953 
4954       // Zero out the allocated memory if it was a calloc.
4955       if (isCallocLikeFn(MallocCall, TLI)) {
4956         auto *BI = new BitCastInst(AI, MallocCall->getType(), "calloc_bc",
4957                                    AI->getNextNode());
4958         Value *Ops[] = {
4959             BI, ConstantInt::get(F->getContext(), APInt(8, 0, false)), Size,
4960             ConstantInt::get(Type::getInt1Ty(F->getContext()), false)};
4961 
4962         Type *Tys[] = {BI->getType(), MallocCall->getOperand(0)->getType()};
4963         Module *M = F->getParent();
4964         Function *Fn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
4965         CallInst::Create(Fn, Ops, "", BI->getNextNode());
4966       }
4967       HasChanged = ChangeStatus::CHANGED;
4968     }
4969 
4970     return HasChanged;
4971   }
4972 
4973   /// Collection of all malloc calls in a function.
4974   SmallSetVector<Instruction *, 4> MallocCalls;
4975 
4976   /// Collection of malloc calls that cannot be converted.
4977   DenseSet<const Instruction *> BadMallocCalls;
4978 
4979   /// A map for each malloc call to the set of associated free calls.
4980   DenseMap<Instruction *, SmallPtrSet<Instruction *, 4>> FreesForMalloc;
4981 
4982   ChangeStatus updateImpl(Attributor &A) override;
4983 };
4984 
4985 ChangeStatus AAHeapToStackImpl::updateImpl(Attributor &A) {
4986   const Function *F = getAnchorScope();
4987   const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
4988 
4989   MustBeExecutedContextExplorer &Explorer =
4990       A.getInfoCache().getMustBeExecutedContextExplorer();
4991 
4992   auto FreeCheck = [&](Instruction &I) {
4993     const auto &Frees = FreesForMalloc.lookup(&I);
4994     if (Frees.size() != 1)
4995       return false;
4996     Instruction *UniqueFree = *Frees.begin();
4997     return Explorer.findInContextOf(UniqueFree, I.getNextNode());
4998   };
4999 
5000   auto UsesCheck = [&](Instruction &I) {
5001     bool ValidUsesOnly = true;
5002     bool MustUse = true;
5003     auto Pred = [&](const Use &U, bool &Follow) -> bool {
5004       Instruction *UserI = cast<Instruction>(U.getUser());
5005       if (isa<LoadInst>(UserI))
5006         return true;
5007       if (auto *SI = dyn_cast<StoreInst>(UserI)) {
5008         if (SI->getValueOperand() == U.get()) {
5009           LLVM_DEBUG(dbgs()
5010                      << "[H2S] escaping store to memory: " << *UserI << "\n");
5011           ValidUsesOnly = false;
5012         } else {
5013           // A store into the malloc'ed memory is fine.
5014         }
5015         return true;
5016       }
5017       if (auto *CB = dyn_cast<CallBase>(UserI)) {
5018         if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd())
5019           return true;
5020         // Record malloc.
5021         if (isFreeCall(UserI, TLI)) {
5022           if (MustUse) {
5023             FreesForMalloc[&I].insert(UserI);
5024           } else {
5025             LLVM_DEBUG(dbgs() << "[H2S] free potentially on different mallocs: "
5026                               << *UserI << "\n");
5027             ValidUsesOnly = false;
5028           }
5029           return true;
5030         }
5031 
5032         unsigned ArgNo = CB->getArgOperandNo(&U);
5033 
5034         const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
5035             *this, IRPosition::callsite_argument(*CB, ArgNo));
5036 
5037         // If a callsite argument use is nofree, we are fine.
5038         const auto &ArgNoFreeAA = A.getAAFor<AANoFree>(
5039             *this, IRPosition::callsite_argument(*CB, ArgNo));
5040 
5041         if (!NoCaptureAA.isAssumedNoCapture() ||
5042             !ArgNoFreeAA.isAssumedNoFree()) {
5043           LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n");
5044           ValidUsesOnly = false;
5045         }
5046         return true;
5047       }
5048 
5049       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
5050           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
5051         MustUse &= !(isa<PHINode>(UserI) || isa<SelectInst>(UserI));
5052         Follow = true;
5053         return true;
5054       }
5055       // Unknown user for which we can not track uses further (in a way that
5056       // makes sense).
5057       LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n");
5058       ValidUsesOnly = false;
5059       return true;
5060     };
5061     A.checkForAllUses(Pred, *this, I);
5062     return ValidUsesOnly;
5063   };
5064 
5065   auto MallocCallocCheck = [&](Instruction &I) {
5066     if (BadMallocCalls.count(&I))
5067       return true;
5068 
5069     bool IsMalloc = isMallocLikeFn(&I, TLI);
5070     bool IsAlignedAllocLike = isAlignedAllocLikeFn(&I, TLI);
5071     bool IsCalloc = !IsMalloc && isCallocLikeFn(&I, TLI);
5072     if (!IsMalloc && !IsAlignedAllocLike && !IsCalloc) {
5073       BadMallocCalls.insert(&I);
5074       return true;
5075     }
5076 
5077     if (IsMalloc) {
5078       if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(0)))
5079         if (Size->getValue().ule(MaxHeapToStackSize))
5080           if (UsesCheck(I) || FreeCheck(I)) {
5081             MallocCalls.insert(&I);
5082             return true;
5083           }
5084     } else if (IsAlignedAllocLike && isa<ConstantInt>(I.getOperand(0))) {
5085       // Only if the alignment and sizes are constant.
5086       if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1)))
5087         if (Size->getValue().ule(MaxHeapToStackSize))
5088           if (UsesCheck(I) || FreeCheck(I)) {
5089             MallocCalls.insert(&I);
5090             return true;
5091           }
5092     } else if (IsCalloc) {
5093       bool Overflow = false;
5094       if (auto *Num = dyn_cast<ConstantInt>(I.getOperand(0)))
5095         if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1)))
5096           if ((Size->getValue().umul_ov(Num->getValue(), Overflow))
5097                   .ule(MaxHeapToStackSize))
5098             if (!Overflow && (UsesCheck(I) || FreeCheck(I))) {
5099               MallocCalls.insert(&I);
5100               return true;
5101             }
5102     }
5103 
5104     BadMallocCalls.insert(&I);
5105     return true;
5106   };
5107 
5108   size_t NumBadMallocs = BadMallocCalls.size();
5109 
5110   A.checkForAllCallLikeInstructions(MallocCallocCheck, *this);
5111 
5112   if (NumBadMallocs != BadMallocCalls.size())
5113     return ChangeStatus::CHANGED;
5114 
5115   return ChangeStatus::UNCHANGED;
5116 }
5117 
5118 struct AAHeapToStackFunction final : public AAHeapToStackImpl {
5119   AAHeapToStackFunction(const IRPosition &IRP, Attributor &A)
5120       : AAHeapToStackImpl(IRP, A) {}
5121 
5122   /// See AbstractAttribute::trackStatistics().
5123   void trackStatistics() const override {
5124     STATS_DECL(
5125         MallocCalls, Function,
5126         "Number of malloc/calloc/aligned_alloc calls converted to allocas");
5127     for (auto *C : MallocCalls)
5128       if (!BadMallocCalls.count(C))
5129         ++BUILD_STAT_NAME(MallocCalls, Function);
5130   }
5131 };
5132 
5133 /// ----------------------- Privatizable Pointers ------------------------------
5134 struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
5135   AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A)
5136       : AAPrivatizablePtr(IRP, A), PrivatizableType(llvm::None) {}
5137 
5138   ChangeStatus indicatePessimisticFixpoint() override {
5139     AAPrivatizablePtr::indicatePessimisticFixpoint();
5140     PrivatizableType = nullptr;
5141     return ChangeStatus::CHANGED;
5142   }
5143 
5144   /// Identify the type we can chose for a private copy of the underlying
5145   /// argument. None means it is not clear yet, nullptr means there is none.
5146   virtual Optional<Type *> identifyPrivatizableType(Attributor &A) = 0;
5147 
5148   /// Return a privatizable type that encloses both T0 and T1.
5149   /// TODO: This is merely a stub for now as we should manage a mapping as well.
5150   Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) {
5151     if (!T0.hasValue())
5152       return T1;
5153     if (!T1.hasValue())
5154       return T0;
5155     if (T0 == T1)
5156       return T0;
5157     return nullptr;
5158   }
5159 
5160   Optional<Type *> getPrivatizableType() const override {
5161     return PrivatizableType;
5162   }
5163 
5164   const std::string getAsStr() const override {
5165     return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]";
5166   }
5167 
5168 protected:
5169   Optional<Type *> PrivatizableType;
5170 };
5171 
5172 // TODO: Do this for call site arguments (probably also other values) as well.
5173 
5174 struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
5175   AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A)
5176       : AAPrivatizablePtrImpl(IRP, A) {}
5177 
5178   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
5179   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
5180     // If this is a byval argument and we know all the call sites (so we can
5181     // rewrite them), there is no need to check them explicitly.
5182     bool AllCallSitesKnown;
5183     if (getIRPosition().hasAttr(Attribute::ByVal) &&
5184         A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this,
5185                                true, AllCallSitesKnown))
5186       return getAssociatedValue().getType()->getPointerElementType();
5187 
5188     Optional<Type *> Ty;
5189     unsigned ArgNo = getIRPosition().getArgNo();
5190 
5191     // Make sure the associated call site argument has the same type at all call
5192     // sites and it is an allocation we know is safe to privatize, for now that
5193     // means we only allow alloca instructions.
5194     // TODO: We can additionally analyze the accesses in the callee to  create
5195     //       the type from that information instead. That is a little more
5196     //       involved and will be done in a follow up patch.
5197     auto CallSiteCheck = [&](AbstractCallSite ACS) {
5198       IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
5199       // Check if a coresponding argument was found or if it is one not
5200       // associated (which can happen for callback calls).
5201       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
5202         return false;
5203 
5204       // Check that all call sites agree on a type.
5205       auto &PrivCSArgAA = A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos);
5206       Optional<Type *> CSTy = PrivCSArgAA.getPrivatizableType();
5207 
5208       LLVM_DEBUG({
5209         dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
5210         if (CSTy.hasValue() && CSTy.getValue())
5211           CSTy.getValue()->print(dbgs());
5212         else if (CSTy.hasValue())
5213           dbgs() << "<nullptr>";
5214         else
5215           dbgs() << "<none>";
5216       });
5217 
5218       Ty = combineTypes(Ty, CSTy);
5219 
5220       LLVM_DEBUG({
5221         dbgs() << " : New Type: ";
5222         if (Ty.hasValue() && Ty.getValue())
5223           Ty.getValue()->print(dbgs());
5224         else if (Ty.hasValue())
5225           dbgs() << "<nullptr>";
5226         else
5227           dbgs() << "<none>";
5228         dbgs() << "\n";
5229       });
5230 
5231       return !Ty.hasValue() || Ty.getValue();
5232     };
5233 
5234     if (!A.checkForAllCallSites(CallSiteCheck, *this, true, AllCallSitesKnown))
5235       return nullptr;
5236     return Ty;
5237   }
5238 
5239   /// See AbstractAttribute::updateImpl(...).
5240   ChangeStatus updateImpl(Attributor &A) override {
5241     PrivatizableType = identifyPrivatizableType(A);
5242     if (!PrivatizableType.hasValue())
5243       return ChangeStatus::UNCHANGED;
5244     if (!PrivatizableType.getValue())
5245       return indicatePessimisticFixpoint();
5246 
5247     // The dependence is optional so we don't give up once we give up on the
5248     // alignment.
5249     A.getAAFor<AAAlign>(*this, IRPosition::value(getAssociatedValue()),
5250                         /* TrackDependence */ true, DepClassTy::OPTIONAL);
5251 
5252     // Avoid arguments with padding for now.
5253     if (!getIRPosition().hasAttr(Attribute::ByVal) &&
5254         !ArgumentPromotionPass::isDenselyPacked(PrivatizableType.getValue(),
5255                                                 A.getInfoCache().getDL())) {
5256       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n");
5257       return indicatePessimisticFixpoint();
5258     }
5259 
5260     // Verify callee and caller agree on how the promoted argument would be
5261     // passed.
5262     // TODO: The use of the ArgumentPromotion interface here is ugly, we need a
5263     // specialized form of TargetTransformInfo::areFunctionArgsABICompatible
5264     // which doesn't require the arguments ArgumentPromotion wanted to pass.
5265     Function &Fn = *getIRPosition().getAnchorScope();
5266     SmallPtrSet<Argument *, 1> ArgsToPromote, Dummy;
5267     ArgsToPromote.insert(getAssociatedArgument());
5268     const auto *TTI =
5269         A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
5270     if (!TTI ||
5271         !ArgumentPromotionPass::areFunctionArgsABICompatible(
5272             Fn, *TTI, ArgsToPromote, Dummy) ||
5273         ArgsToPromote.empty()) {
5274       LLVM_DEBUG(
5275           dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for "
5276                  << Fn.getName() << "\n");
5277       return indicatePessimisticFixpoint();
5278     }
5279 
5280     // Collect the types that will replace the privatizable type in the function
5281     // signature.
5282     SmallVector<Type *, 16> ReplacementTypes;
5283     identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
5284 
5285     // Register a rewrite of the argument.
5286     Argument *Arg = getAssociatedArgument();
5287     if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
5288       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n");
5289       return indicatePessimisticFixpoint();
5290     }
5291 
5292     unsigned ArgNo = Arg->getArgNo();
5293 
5294     // Helper to check if for the given call site the associated argument is
5295     // passed to a callback where the privatization would be different.
5296     auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
5297       SmallVector<const Use *, 4> CallbackUses;
5298       AbstractCallSite::getCallbackUses(CB, CallbackUses);
5299       for (const Use *U : CallbackUses) {
5300         AbstractCallSite CBACS(U);
5301         assert(CBACS && CBACS.isCallbackCall());
5302         for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
5303           int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
5304 
5305           LLVM_DEBUG({
5306             dbgs()
5307                 << "[AAPrivatizablePtr] Argument " << *Arg
5308                 << "check if can be privatized in the context of its parent ("
5309                 << Arg->getParent()->getName()
5310                 << ")\n[AAPrivatizablePtr] because it is an argument in a "
5311                    "callback ("
5312                 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
5313                 << ")\n[AAPrivatizablePtr] " << CBArg << " : "
5314                 << CBACS.getCallArgOperand(CBArg) << " vs "
5315                 << CB.getArgOperand(ArgNo) << "\n"
5316                 << "[AAPrivatizablePtr] " << CBArg << " : "
5317                 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n";
5318           });
5319 
5320           if (CBArgNo != int(ArgNo))
5321             continue;
5322           const auto &CBArgPrivAA =
5323               A.getAAFor<AAPrivatizablePtr>(*this, IRPosition::argument(CBArg));
5324           if (CBArgPrivAA.isValidState()) {
5325             auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType();
5326             if (!CBArgPrivTy.hasValue())
5327               continue;
5328             if (CBArgPrivTy.getValue() == PrivatizableType)
5329               continue;
5330           }
5331 
5332           LLVM_DEBUG({
5333             dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5334                    << " cannot be privatized in the context of its parent ("
5335                    << Arg->getParent()->getName()
5336                    << ")\n[AAPrivatizablePtr] because it is an argument in a "
5337                       "callback ("
5338                    << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
5339                    << ").\n[AAPrivatizablePtr] for which the argument "
5340                       "privatization is not compatible.\n";
5341           });
5342           return false;
5343         }
5344       }
5345       return true;
5346     };
5347 
5348     // Helper to check if for the given call site the associated argument is
5349     // passed to a direct call where the privatization would be different.
5350     auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
5351       CallBase *DC = cast<CallBase>(ACS.getInstruction());
5352       int DCArgNo = ACS.getCallArgOperandNo(ArgNo);
5353       assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->getNumArgOperands() &&
5354              "Expected a direct call operand for callback call operand");
5355 
5356       LLVM_DEBUG({
5357         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5358                << " check if be privatized in the context of its parent ("
5359                << Arg->getParent()->getName()
5360                << ")\n[AAPrivatizablePtr] because it is an argument in a "
5361                   "direct call of ("
5362                << DCArgNo << "@" << DC->getCalledFunction()->getName()
5363                << ").\n";
5364       });
5365 
5366       Function *DCCallee = DC->getCalledFunction();
5367       if (unsigned(DCArgNo) < DCCallee->arg_size()) {
5368         const auto &DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
5369             *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)));
5370         if (DCArgPrivAA.isValidState()) {
5371           auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType();
5372           if (!DCArgPrivTy.hasValue())
5373             return true;
5374           if (DCArgPrivTy.getValue() == PrivatizableType)
5375             return true;
5376         }
5377       }
5378 
5379       LLVM_DEBUG({
5380         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5381                << " cannot be privatized in the context of its parent ("
5382                << Arg->getParent()->getName()
5383                << ")\n[AAPrivatizablePtr] because it is an argument in a "
5384                   "direct call of ("
5385                << ACS.getInstruction()->getCalledFunction()->getName()
5386                << ").\n[AAPrivatizablePtr] for which the argument "
5387                   "privatization is not compatible.\n";
5388       });
5389       return false;
5390     };
5391 
5392     // Helper to check if the associated argument is used at the given abstract
5393     // call site in a way that is incompatible with the privatization assumed
5394     // here.
5395     auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
5396       if (ACS.isDirectCall())
5397         return IsCompatiblePrivArgOfCallback(*ACS.getInstruction());
5398       if (ACS.isCallbackCall())
5399         return IsCompatiblePrivArgOfDirectCS(ACS);
5400       return false;
5401     };
5402 
5403     bool AllCallSitesKnown;
5404     if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true,
5405                                 AllCallSitesKnown))
5406       return indicatePessimisticFixpoint();
5407 
5408     return ChangeStatus::UNCHANGED;
5409   }
5410 
5411   /// Given a type to private \p PrivType, collect the constituates (which are
5412   /// used) in \p ReplacementTypes.
5413   static void
5414   identifyReplacementTypes(Type *PrivType,
5415                            SmallVectorImpl<Type *> &ReplacementTypes) {
5416     // TODO: For now we expand the privatization type to the fullest which can
5417     //       lead to dead arguments that need to be removed later.
5418     assert(PrivType && "Expected privatizable type!");
5419 
5420     // Traverse the type, extract constituate types on the outermost level.
5421     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5422       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
5423         ReplacementTypes.push_back(PrivStructType->getElementType(u));
5424     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5425       ReplacementTypes.append(PrivArrayType->getNumElements(),
5426                               PrivArrayType->getElementType());
5427     } else {
5428       ReplacementTypes.push_back(PrivType);
5429     }
5430   }
5431 
5432   /// Initialize \p Base according to the type \p PrivType at position \p IP.
5433   /// The values needed are taken from the arguments of \p F starting at
5434   /// position \p ArgNo.
5435   static void createInitialization(Type *PrivType, Value &Base, Function &F,
5436                                    unsigned ArgNo, Instruction &IP) {
5437     assert(PrivType && "Expected privatizable type!");
5438 
5439     IRBuilder<NoFolder> IRB(&IP);
5440     const DataLayout &DL = F.getParent()->getDataLayout();
5441 
5442     // Traverse the type, build GEPs and stores.
5443     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5444       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
5445       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
5446         Type *PointeeTy = PrivStructType->getElementType(u)->getPointerTo();
5447         Value *Ptr = constructPointer(
5448             PointeeTy, &Base, PrivStructLayout->getElementOffset(u), IRB, DL);
5449         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
5450       }
5451     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5452       Type *PointeePtrTy = PrivArrayType->getElementType()->getPointerTo();
5453       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeePtrTy);
5454       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
5455         Value *Ptr =
5456             constructPointer(PointeePtrTy, &Base, u * PointeeTySize, IRB, DL);
5457         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
5458       }
5459     } else {
5460       new StoreInst(F.getArg(ArgNo), &Base, &IP);
5461     }
5462   }
5463 
5464   /// Extract values from \p Base according to the type \p PrivType at the
5465   /// call position \p ACS. The values are appended to \p ReplacementValues.
5466   void createReplacementValues(Align Alignment, Type *PrivType,
5467                                AbstractCallSite ACS, Value *Base,
5468                                SmallVectorImpl<Value *> &ReplacementValues) {
5469     assert(Base && "Expected base value!");
5470     assert(PrivType && "Expected privatizable type!");
5471     Instruction *IP = ACS.getInstruction();
5472 
5473     IRBuilder<NoFolder> IRB(IP);
5474     const DataLayout &DL = IP->getModule()->getDataLayout();
5475 
5476     if (Base->getType()->getPointerElementType() != PrivType)
5477       Base = BitCastInst::CreateBitOrPointerCast(Base, PrivType->getPointerTo(),
5478                                                  "", ACS.getInstruction());
5479 
5480     // Traverse the type, build GEPs and loads.
5481     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5482       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
5483       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
5484         Type *PointeeTy = PrivStructType->getElementType(u);
5485         Value *Ptr =
5486             constructPointer(PointeeTy->getPointerTo(), Base,
5487                              PrivStructLayout->getElementOffset(u), IRB, DL);
5488         LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
5489         L->setAlignment(Alignment);
5490         ReplacementValues.push_back(L);
5491       }
5492     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5493       Type *PointeeTy = PrivArrayType->getElementType();
5494       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
5495       Type *PointeePtrTy = PointeeTy->getPointerTo();
5496       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
5497         Value *Ptr =
5498             constructPointer(PointeePtrTy, Base, u * PointeeTySize, IRB, DL);
5499         LoadInst *L = new LoadInst(PointeePtrTy, Ptr, "", IP);
5500         L->setAlignment(Alignment);
5501         ReplacementValues.push_back(L);
5502       }
5503     } else {
5504       LoadInst *L = new LoadInst(PrivType, Base, "", IP);
5505       L->setAlignment(Alignment);
5506       ReplacementValues.push_back(L);
5507     }
5508   }
5509 
5510   /// See AbstractAttribute::manifest(...)
5511   ChangeStatus manifest(Attributor &A) override {
5512     if (!PrivatizableType.hasValue())
5513       return ChangeStatus::UNCHANGED;
5514     assert(PrivatizableType.getValue() && "Expected privatizable type!");
5515 
5516     // Collect all tail calls in the function as we cannot allow new allocas to
5517     // escape into tail recursion.
5518     // TODO: Be smarter about new allocas escaping into tail calls.
5519     SmallVector<CallInst *, 16> TailCalls;
5520     if (!A.checkForAllInstructions(
5521             [&](Instruction &I) {
5522               CallInst &CI = cast<CallInst>(I);
5523               if (CI.isTailCall())
5524                 TailCalls.push_back(&CI);
5525               return true;
5526             },
5527             *this, {Instruction::Call}))
5528       return ChangeStatus::UNCHANGED;
5529 
5530     Argument *Arg = getAssociatedArgument();
5531     // Query AAAlign attribute for alignment of associated argument to
5532     // determine the best alignment of loads.
5533     const auto &AlignAA = A.getAAFor<AAAlign>(*this, IRPosition::value(*Arg));
5534 
5535     // Callback to repair the associated function. A new alloca is placed at the
5536     // beginning and initialized with the values passed through arguments. The
5537     // new alloca replaces the use of the old pointer argument.
5538     Attributor::ArgumentReplacementInfo::CalleeRepairCBTy FnRepairCB =
5539         [=](const Attributor::ArgumentReplacementInfo &ARI,
5540             Function &ReplacementFn, Function::arg_iterator ArgIt) {
5541           BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
5542           Instruction *IP = &*EntryBB.getFirstInsertionPt();
5543           auto *AI = new AllocaInst(PrivatizableType.getValue(), 0,
5544                                     Arg->getName() + ".priv", IP);
5545           createInitialization(PrivatizableType.getValue(), *AI, ReplacementFn,
5546                                ArgIt->getArgNo(), *IP);
5547           Arg->replaceAllUsesWith(AI);
5548 
5549           for (CallInst *CI : TailCalls)
5550             CI->setTailCall(false);
5551         };
5552 
5553     // Callback to repair a call site of the associated function. The elements
5554     // of the privatizable type are loaded prior to the call and passed to the
5555     // new function version.
5556     Attributor::ArgumentReplacementInfo::ACSRepairCBTy ACSRepairCB =
5557         [=, &AlignAA](const Attributor::ArgumentReplacementInfo &ARI,
5558                       AbstractCallSite ACS,
5559                       SmallVectorImpl<Value *> &NewArgOperands) {
5560           // When no alignment is specified for the load instruction,
5561           // natural alignment is assumed.
5562           createReplacementValues(
5563               assumeAligned(AlignAA.getAssumedAlign()),
5564               PrivatizableType.getValue(), ACS,
5565               ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()),
5566               NewArgOperands);
5567         };
5568 
5569     // Collect the types that will replace the privatizable type in the function
5570     // signature.
5571     SmallVector<Type *, 16> ReplacementTypes;
5572     identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
5573 
5574     // Register a rewrite of the argument.
5575     if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
5576                                            std::move(FnRepairCB),
5577                                            std::move(ACSRepairCB)))
5578       return ChangeStatus::CHANGED;
5579     return ChangeStatus::UNCHANGED;
5580   }
5581 
5582   /// See AbstractAttribute::trackStatistics()
5583   void trackStatistics() const override {
5584     STATS_DECLTRACK_ARG_ATTR(privatizable_ptr);
5585   }
5586 };
5587 
5588 struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl {
5589   AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A)
5590       : AAPrivatizablePtrImpl(IRP, A) {}
5591 
5592   /// See AbstractAttribute::initialize(...).
5593   virtual void initialize(Attributor &A) override {
5594     // TODO: We can privatize more than arguments.
5595     indicatePessimisticFixpoint();
5596   }
5597 
5598   ChangeStatus updateImpl(Attributor &A) override {
5599     llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::"
5600                      "updateImpl will not be called");
5601   }
5602 
5603   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
5604   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
5605     Value *Obj = getUnderlyingObject(&getAssociatedValue());
5606     if (!Obj) {
5607       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n");
5608       return nullptr;
5609     }
5610 
5611     if (auto *AI = dyn_cast<AllocaInst>(Obj))
5612       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
5613         if (CI->isOne())
5614           return Obj->getType()->getPointerElementType();
5615     if (auto *Arg = dyn_cast<Argument>(Obj)) {
5616       auto &PrivArgAA =
5617           A.getAAFor<AAPrivatizablePtr>(*this, IRPosition::argument(*Arg));
5618       if (PrivArgAA.isAssumedPrivatizablePtr())
5619         return Obj->getType()->getPointerElementType();
5620     }
5621 
5622     LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid "
5623                          "alloca nor privatizable argument: "
5624                       << *Obj << "!\n");
5625     return nullptr;
5626   }
5627 
5628   /// See AbstractAttribute::trackStatistics()
5629   void trackStatistics() const override {
5630     STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr);
5631   }
5632 };
5633 
5634 struct AAPrivatizablePtrCallSiteArgument final
5635     : public AAPrivatizablePtrFloating {
5636   AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A)
5637       : AAPrivatizablePtrFloating(IRP, A) {}
5638 
5639   /// See AbstractAttribute::initialize(...).
5640   void initialize(Attributor &A) override {
5641     if (getIRPosition().hasAttr(Attribute::ByVal))
5642       indicateOptimisticFixpoint();
5643   }
5644 
5645   /// See AbstractAttribute::updateImpl(...).
5646   ChangeStatus updateImpl(Attributor &A) override {
5647     PrivatizableType = identifyPrivatizableType(A);
5648     if (!PrivatizableType.hasValue())
5649       return ChangeStatus::UNCHANGED;
5650     if (!PrivatizableType.getValue())
5651       return indicatePessimisticFixpoint();
5652 
5653     const IRPosition &IRP = getIRPosition();
5654     auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, IRP);
5655     if (!NoCaptureAA.isAssumedNoCapture()) {
5656       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n");
5657       return indicatePessimisticFixpoint();
5658     }
5659 
5660     auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP);
5661     if (!NoAliasAA.isAssumedNoAlias()) {
5662       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n");
5663       return indicatePessimisticFixpoint();
5664     }
5665 
5666     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(*this, IRP);
5667     if (!MemBehaviorAA.isAssumedReadOnly()) {
5668       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n");
5669       return indicatePessimisticFixpoint();
5670     }
5671 
5672     return ChangeStatus::UNCHANGED;
5673   }
5674 
5675   /// See AbstractAttribute::trackStatistics()
5676   void trackStatistics() const override {
5677     STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr);
5678   }
5679 };
5680 
5681 struct AAPrivatizablePtrCallSiteReturned final
5682     : public AAPrivatizablePtrFloating {
5683   AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A)
5684       : AAPrivatizablePtrFloating(IRP, A) {}
5685 
5686   /// See AbstractAttribute::initialize(...).
5687   void initialize(Attributor &A) override {
5688     // TODO: We can privatize more than arguments.
5689     indicatePessimisticFixpoint();
5690   }
5691 
5692   /// See AbstractAttribute::trackStatistics()
5693   void trackStatistics() const override {
5694     STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr);
5695   }
5696 };
5697 
5698 struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating {
5699   AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A)
5700       : AAPrivatizablePtrFloating(IRP, A) {}
5701 
5702   /// See AbstractAttribute::initialize(...).
5703   void initialize(Attributor &A) override {
5704     // TODO: We can privatize more than arguments.
5705     indicatePessimisticFixpoint();
5706   }
5707 
5708   /// See AbstractAttribute::trackStatistics()
5709   void trackStatistics() const override {
5710     STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr);
5711   }
5712 };
5713 
5714 /// -------------------- Memory Behavior Attributes ----------------------------
5715 /// Includes read-none, read-only, and write-only.
5716 /// ----------------------------------------------------------------------------
5717 struct AAMemoryBehaviorImpl : public AAMemoryBehavior {
5718   AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A)
5719       : AAMemoryBehavior(IRP, A) {}
5720 
5721   /// See AbstractAttribute::initialize(...).
5722   void initialize(Attributor &A) override {
5723     intersectAssumedBits(BEST_STATE);
5724     getKnownStateFromValue(getIRPosition(), getState());
5725     IRAttribute::initialize(A);
5726   }
5727 
5728   /// Return the memory behavior information encoded in the IR for \p IRP.
5729   static void getKnownStateFromValue(const IRPosition &IRP,
5730                                      BitIntegerState &State,
5731                                      bool IgnoreSubsumingPositions = false) {
5732     SmallVector<Attribute, 2> Attrs;
5733     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
5734     for (const Attribute &Attr : Attrs) {
5735       switch (Attr.getKindAsEnum()) {
5736       case Attribute::ReadNone:
5737         State.addKnownBits(NO_ACCESSES);
5738         break;
5739       case Attribute::ReadOnly:
5740         State.addKnownBits(NO_WRITES);
5741         break;
5742       case Attribute::WriteOnly:
5743         State.addKnownBits(NO_READS);
5744         break;
5745       default:
5746         llvm_unreachable("Unexpected attribute!");
5747       }
5748     }
5749 
5750     if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) {
5751       if (!I->mayReadFromMemory())
5752         State.addKnownBits(NO_READS);
5753       if (!I->mayWriteToMemory())
5754         State.addKnownBits(NO_WRITES);
5755     }
5756   }
5757 
5758   /// See AbstractAttribute::getDeducedAttributes(...).
5759   void getDeducedAttributes(LLVMContext &Ctx,
5760                             SmallVectorImpl<Attribute> &Attrs) const override {
5761     assert(Attrs.size() == 0);
5762     if (isAssumedReadNone())
5763       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
5764     else if (isAssumedReadOnly())
5765       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
5766     else if (isAssumedWriteOnly())
5767       Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
5768     assert(Attrs.size() <= 1);
5769   }
5770 
5771   /// See AbstractAttribute::manifest(...).
5772   ChangeStatus manifest(Attributor &A) override {
5773     if (hasAttr(Attribute::ReadNone, /* IgnoreSubsumingPositions */ true))
5774       return ChangeStatus::UNCHANGED;
5775 
5776     const IRPosition &IRP = getIRPosition();
5777 
5778     // Check if we would improve the existing attributes first.
5779     SmallVector<Attribute, 4> DeducedAttrs;
5780     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
5781     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
5782           return IRP.hasAttr(Attr.getKindAsEnum(),
5783                              /* IgnoreSubsumingPositions */ true);
5784         }))
5785       return ChangeStatus::UNCHANGED;
5786 
5787     // Clear existing attributes.
5788     IRP.removeAttrs(AttrKinds);
5789 
5790     // Use the generic manifest method.
5791     return IRAttribute::manifest(A);
5792   }
5793 
5794   /// See AbstractState::getAsStr().
5795   const std::string getAsStr() const override {
5796     if (isAssumedReadNone())
5797       return "readnone";
5798     if (isAssumedReadOnly())
5799       return "readonly";
5800     if (isAssumedWriteOnly())
5801       return "writeonly";
5802     return "may-read/write";
5803   }
5804 
5805   /// The set of IR attributes AAMemoryBehavior deals with.
5806   static const Attribute::AttrKind AttrKinds[3];
5807 };
5808 
5809 const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = {
5810     Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
5811 
5812 /// Memory behavior attribute for a floating value.
5813 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
5814   AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A)
5815       : AAMemoryBehaviorImpl(IRP, A) {}
5816 
5817   /// See AbstractAttribute::initialize(...).
5818   void initialize(Attributor &A) override {
5819     AAMemoryBehaviorImpl::initialize(A);
5820     // Initialize the use vector with all direct uses of the associated value.
5821     for (const Use &U : getAssociatedValue().uses())
5822       Uses.insert(&U);
5823   }
5824 
5825   /// See AbstractAttribute::updateImpl(...).
5826   ChangeStatus updateImpl(Attributor &A) override;
5827 
5828   /// See AbstractAttribute::trackStatistics()
5829   void trackStatistics() const override {
5830     if (isAssumedReadNone())
5831       STATS_DECLTRACK_FLOATING_ATTR(readnone)
5832     else if (isAssumedReadOnly())
5833       STATS_DECLTRACK_FLOATING_ATTR(readonly)
5834     else if (isAssumedWriteOnly())
5835       STATS_DECLTRACK_FLOATING_ATTR(writeonly)
5836   }
5837 
5838 private:
5839   /// Return true if users of \p UserI might access the underlying
5840   /// variable/location described by \p U and should therefore be analyzed.
5841   bool followUsersOfUseIn(Attributor &A, const Use *U,
5842                           const Instruction *UserI);
5843 
5844   /// Update the state according to the effect of use \p U in \p UserI.
5845   void analyzeUseIn(Attributor &A, const Use *U, const Instruction *UserI);
5846 
5847 protected:
5848   /// Container for (transitive) uses of the associated argument.
5849   SetVector<const Use *> Uses;
5850 };
5851 
5852 /// Memory behavior attribute for function argument.
5853 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
5854   AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A)
5855       : AAMemoryBehaviorFloating(IRP, A) {}
5856 
5857   /// See AbstractAttribute::initialize(...).
5858   void initialize(Attributor &A) override {
5859     intersectAssumedBits(BEST_STATE);
5860     const IRPosition &IRP = getIRPosition();
5861     // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we
5862     // can query it when we use has/getAttr. That would allow us to reuse the
5863     // initialize of the base class here.
5864     bool HasByVal =
5865         IRP.hasAttr({Attribute::ByVal}, /* IgnoreSubsumingPositions */ true);
5866     getKnownStateFromValue(IRP, getState(),
5867                            /* IgnoreSubsumingPositions */ HasByVal);
5868 
5869     // Initialize the use vector with all direct uses of the associated value.
5870     Argument *Arg = getAssociatedArgument();
5871     if (!Arg || !A.isFunctionIPOAmendable(*(Arg->getParent()))) {
5872       indicatePessimisticFixpoint();
5873     } else {
5874       // Initialize the use vector with all direct uses of the associated value.
5875       for (const Use &U : Arg->uses())
5876         Uses.insert(&U);
5877     }
5878   }
5879 
5880   ChangeStatus manifest(Attributor &A) override {
5881     // TODO: Pointer arguments are not supported on vectors of pointers yet.
5882     if (!getAssociatedValue().getType()->isPointerTy())
5883       return ChangeStatus::UNCHANGED;
5884 
5885     // TODO: From readattrs.ll: "inalloca parameters are always
5886     //                           considered written"
5887     if (hasAttr({Attribute::InAlloca, Attribute::Preallocated})) {
5888       removeKnownBits(NO_WRITES);
5889       removeAssumedBits(NO_WRITES);
5890     }
5891     return AAMemoryBehaviorFloating::manifest(A);
5892   }
5893 
5894   /// See AbstractAttribute::trackStatistics()
5895   void trackStatistics() const override {
5896     if (isAssumedReadNone())
5897       STATS_DECLTRACK_ARG_ATTR(readnone)
5898     else if (isAssumedReadOnly())
5899       STATS_DECLTRACK_ARG_ATTR(readonly)
5900     else if (isAssumedWriteOnly())
5901       STATS_DECLTRACK_ARG_ATTR(writeonly)
5902   }
5903 };
5904 
5905 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
5906   AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A)
5907       : AAMemoryBehaviorArgument(IRP, A) {}
5908 
5909   /// See AbstractAttribute::initialize(...).
5910   void initialize(Attributor &A) override {
5911     if (Argument *Arg = getAssociatedArgument()) {
5912       if (Arg->hasByValAttr()) {
5913         addKnownBits(NO_WRITES);
5914         removeKnownBits(NO_READS);
5915         removeAssumedBits(NO_READS);
5916       }
5917     }
5918     AAMemoryBehaviorArgument::initialize(A);
5919   }
5920 
5921   /// See AbstractAttribute::updateImpl(...).
5922   ChangeStatus updateImpl(Attributor &A) override {
5923     // TODO: Once we have call site specific value information we can provide
5924     //       call site specific liveness liveness information and then it makes
5925     //       sense to specialize attributes for call sites arguments instead of
5926     //       redirecting requests to the callee argument.
5927     Argument *Arg = getAssociatedArgument();
5928     const IRPosition &ArgPos = IRPosition::argument(*Arg);
5929     auto &ArgAA = A.getAAFor<AAMemoryBehavior>(*this, ArgPos);
5930     return clampStateAndIndicateChange(getState(), ArgAA.getState());
5931   }
5932 
5933   /// See AbstractAttribute::trackStatistics()
5934   void trackStatistics() const override {
5935     if (isAssumedReadNone())
5936       STATS_DECLTRACK_CSARG_ATTR(readnone)
5937     else if (isAssumedReadOnly())
5938       STATS_DECLTRACK_CSARG_ATTR(readonly)
5939     else if (isAssumedWriteOnly())
5940       STATS_DECLTRACK_CSARG_ATTR(writeonly)
5941   }
5942 };
5943 
5944 /// Memory behavior attribute for a call site return position.
5945 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
5946   AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A)
5947       : AAMemoryBehaviorFloating(IRP, A) {}
5948 
5949   /// See AbstractAttribute::manifest(...).
5950   ChangeStatus manifest(Attributor &A) override {
5951     // We do not annotate returned values.
5952     return ChangeStatus::UNCHANGED;
5953   }
5954 
5955   /// See AbstractAttribute::trackStatistics()
5956   void trackStatistics() const override {}
5957 };
5958 
5959 /// An AA to represent the memory behavior function attributes.
5960 struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl {
5961   AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A)
5962       : AAMemoryBehaviorImpl(IRP, A) {}
5963 
5964   /// See AbstractAttribute::updateImpl(Attributor &A).
5965   virtual ChangeStatus updateImpl(Attributor &A) override;
5966 
5967   /// See AbstractAttribute::manifest(...).
5968   ChangeStatus manifest(Attributor &A) override {
5969     Function &F = cast<Function>(getAnchorValue());
5970     if (isAssumedReadNone()) {
5971       F.removeFnAttr(Attribute::ArgMemOnly);
5972       F.removeFnAttr(Attribute::InaccessibleMemOnly);
5973       F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
5974     }
5975     return AAMemoryBehaviorImpl::manifest(A);
5976   }
5977 
5978   /// See AbstractAttribute::trackStatistics()
5979   void trackStatistics() const override {
5980     if (isAssumedReadNone())
5981       STATS_DECLTRACK_FN_ATTR(readnone)
5982     else if (isAssumedReadOnly())
5983       STATS_DECLTRACK_FN_ATTR(readonly)
5984     else if (isAssumedWriteOnly())
5985       STATS_DECLTRACK_FN_ATTR(writeonly)
5986   }
5987 };
5988 
5989 /// AAMemoryBehavior attribute for call sites.
5990 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl {
5991   AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A)
5992       : AAMemoryBehaviorImpl(IRP, A) {}
5993 
5994   /// See AbstractAttribute::initialize(...).
5995   void initialize(Attributor &A) override {
5996     AAMemoryBehaviorImpl::initialize(A);
5997     Function *F = getAssociatedFunction();
5998     if (!F || !A.isFunctionIPOAmendable(*F)) {
5999       indicatePessimisticFixpoint();
6000       return;
6001     }
6002   }
6003 
6004   /// See AbstractAttribute::updateImpl(...).
6005   ChangeStatus updateImpl(Attributor &A) override {
6006     // TODO: Once we have call site specific value information we can provide
6007     //       call site specific liveness liveness information and then it makes
6008     //       sense to specialize attributes for call sites arguments instead of
6009     //       redirecting requests to the callee argument.
6010     Function *F = getAssociatedFunction();
6011     const IRPosition &FnPos = IRPosition::function(*F);
6012     auto &FnAA = A.getAAFor<AAMemoryBehavior>(*this, FnPos);
6013     return clampStateAndIndicateChange(getState(), FnAA.getState());
6014   }
6015 
6016   /// See AbstractAttribute::trackStatistics()
6017   void trackStatistics() const override {
6018     if (isAssumedReadNone())
6019       STATS_DECLTRACK_CS_ATTR(readnone)
6020     else if (isAssumedReadOnly())
6021       STATS_DECLTRACK_CS_ATTR(readonly)
6022     else if (isAssumedWriteOnly())
6023       STATS_DECLTRACK_CS_ATTR(writeonly)
6024   }
6025 };
6026 
6027 ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) {
6028 
6029   // The current assumed state used to determine a change.
6030   auto AssumedState = getAssumed();
6031 
6032   auto CheckRWInst = [&](Instruction &I) {
6033     // If the instruction has an own memory behavior state, use it to restrict
6034     // the local state. No further analysis is required as the other memory
6035     // state is as optimistic as it gets.
6036     if (const auto *CB = dyn_cast<CallBase>(&I)) {
6037       const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
6038           *this, IRPosition::callsite_function(*CB));
6039       intersectAssumedBits(MemBehaviorAA.getAssumed());
6040       return !isAtFixpoint();
6041     }
6042 
6043     // Remove access kind modifiers if necessary.
6044     if (I.mayReadFromMemory())
6045       removeAssumedBits(NO_READS);
6046     if (I.mayWriteToMemory())
6047       removeAssumedBits(NO_WRITES);
6048     return !isAtFixpoint();
6049   };
6050 
6051   if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this))
6052     return indicatePessimisticFixpoint();
6053 
6054   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
6055                                         : ChangeStatus::UNCHANGED;
6056 }
6057 
6058 ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) {
6059 
6060   const IRPosition &IRP = getIRPosition();
6061   const IRPosition &FnPos = IRPosition::function_scope(IRP);
6062   AAMemoryBehavior::StateType &S = getState();
6063 
6064   // First, check the function scope. We take the known information and we avoid
6065   // work if the assumed information implies the current assumed information for
6066   // this attribute. This is a valid for all but byval arguments.
6067   Argument *Arg = IRP.getAssociatedArgument();
6068   AAMemoryBehavior::base_t FnMemAssumedState =
6069       AAMemoryBehavior::StateType::getWorstState();
6070   if (!Arg || !Arg->hasByValAttr()) {
6071     const auto &FnMemAA = A.getAAFor<AAMemoryBehavior>(
6072         *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
6073     FnMemAssumedState = FnMemAA.getAssumed();
6074     S.addKnownBits(FnMemAA.getKnown());
6075     if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed())
6076       return ChangeStatus::UNCHANGED;
6077   }
6078 
6079   // Make sure the value is not captured (except through "return"), if
6080   // it is, any information derived would be irrelevant anyway as we cannot
6081   // check the potential aliases introduced by the capture. However, no need
6082   // to fall back to anythign less optimistic than the function state.
6083   const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
6084       *this, IRP, /* TrackDependence */ true, DepClassTy::OPTIONAL);
6085   if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
6086     S.intersectAssumedBits(FnMemAssumedState);
6087     return ChangeStatus::CHANGED;
6088   }
6089 
6090   // The current assumed state used to determine a change.
6091   auto AssumedState = S.getAssumed();
6092 
6093   // Liveness information to exclude dead users.
6094   // TODO: Take the FnPos once we have call site specific liveness information.
6095   const auto &LivenessAA = A.getAAFor<AAIsDead>(
6096       *this, IRPosition::function(*IRP.getAssociatedFunction()),
6097       /* TrackDependence */ false);
6098 
6099   // Visit and expand uses until all are analyzed or a fixpoint is reached.
6100   for (unsigned i = 0; i < Uses.size() && !isAtFixpoint(); i++) {
6101     const Use *U = Uses[i];
6102     Instruction *UserI = cast<Instruction>(U->getUser());
6103     LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << **U << " in " << *UserI
6104                       << " [Dead: " << (A.isAssumedDead(*U, this, &LivenessAA))
6105                       << "]\n");
6106     if (A.isAssumedDead(*U, this, &LivenessAA))
6107       continue;
6108 
6109     // Droppable users, e.g., llvm::assume does not actually perform any action.
6110     if (UserI->isDroppable())
6111       continue;
6112 
6113     // Check if the users of UserI should also be visited.
6114     if (followUsersOfUseIn(A, U, UserI))
6115       for (const Use &UserIUse : UserI->uses())
6116         Uses.insert(&UserIUse);
6117 
6118     // If UserI might touch memory we analyze the use in detail.
6119     if (UserI->mayReadOrWriteMemory())
6120       analyzeUseIn(A, U, UserI);
6121   }
6122 
6123   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
6124                                         : ChangeStatus::UNCHANGED;
6125 }
6126 
6127 bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use *U,
6128                                                   const Instruction *UserI) {
6129   // The loaded value is unrelated to the pointer argument, no need to
6130   // follow the users of the load.
6131   if (isa<LoadInst>(UserI))
6132     return false;
6133 
6134   // By default we follow all uses assuming UserI might leak information on U,
6135   // we have special handling for call sites operands though.
6136   const auto *CB = dyn_cast<CallBase>(UserI);
6137   if (!CB || !CB->isArgOperand(U))
6138     return true;
6139 
6140   // If the use is a call argument known not to be captured, the users of
6141   // the call do not need to be visited because they have to be unrelated to
6142   // the input. Note that this check is not trivial even though we disallow
6143   // general capturing of the underlying argument. The reason is that the
6144   // call might the argument "through return", which we allow and for which we
6145   // need to check call users.
6146   if (U->get()->getType()->isPointerTy()) {
6147     unsigned ArgNo = CB->getArgOperandNo(U);
6148     const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
6149         *this, IRPosition::callsite_argument(*CB, ArgNo),
6150         /* TrackDependence */ true, DepClassTy::OPTIONAL);
6151     return !ArgNoCaptureAA.isAssumedNoCapture();
6152   }
6153 
6154   return true;
6155 }
6156 
6157 void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use *U,
6158                                             const Instruction *UserI) {
6159   assert(UserI->mayReadOrWriteMemory());
6160 
6161   switch (UserI->getOpcode()) {
6162   default:
6163     // TODO: Handle all atomics and other side-effect operations we know of.
6164     break;
6165   case Instruction::Load:
6166     // Loads cause the NO_READS property to disappear.
6167     removeAssumedBits(NO_READS);
6168     return;
6169 
6170   case Instruction::Store:
6171     // Stores cause the NO_WRITES property to disappear if the use is the
6172     // pointer operand. Note that we do assume that capturing was taken care of
6173     // somewhere else.
6174     if (cast<StoreInst>(UserI)->getPointerOperand() == U->get())
6175       removeAssumedBits(NO_WRITES);
6176     return;
6177 
6178   case Instruction::Call:
6179   case Instruction::CallBr:
6180   case Instruction::Invoke: {
6181     // For call sites we look at the argument memory behavior attribute (this
6182     // could be recursive!) in order to restrict our own state.
6183     const auto *CB = cast<CallBase>(UserI);
6184 
6185     // Give up on operand bundles.
6186     if (CB->isBundleOperand(U)) {
6187       indicatePessimisticFixpoint();
6188       return;
6189     }
6190 
6191     // Calling a function does read the function pointer, maybe write it if the
6192     // function is self-modifying.
6193     if (CB->isCallee(U)) {
6194       removeAssumedBits(NO_READS);
6195       break;
6196     }
6197 
6198     // Adjust the possible access behavior based on the information on the
6199     // argument.
6200     IRPosition Pos;
6201     if (U->get()->getType()->isPointerTy())
6202       Pos = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(U));
6203     else
6204       Pos = IRPosition::callsite_function(*CB);
6205     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
6206         *this, Pos,
6207         /* TrackDependence */ true, DepClassTy::OPTIONAL);
6208     // "assumed" has at most the same bits as the MemBehaviorAA assumed
6209     // and at least "known".
6210     intersectAssumedBits(MemBehaviorAA.getAssumed());
6211     return;
6212   }
6213   };
6214 
6215   // Generally, look at the "may-properties" and adjust the assumed state if we
6216   // did not trigger special handling before.
6217   if (UserI->mayReadFromMemory())
6218     removeAssumedBits(NO_READS);
6219   if (UserI->mayWriteToMemory())
6220     removeAssumedBits(NO_WRITES);
6221 }
6222 
6223 } // namespace
6224 
6225 /// -------------------- Memory Locations Attributes ---------------------------
6226 /// Includes read-none, argmemonly, inaccessiblememonly,
6227 /// inaccessiblememorargmemonly
6228 /// ----------------------------------------------------------------------------
6229 
6230 std::string AAMemoryLocation::getMemoryLocationsAsStr(
6231     AAMemoryLocation::MemoryLocationsKind MLK) {
6232   if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS))
6233     return "all memory";
6234   if (MLK == AAMemoryLocation::NO_LOCATIONS)
6235     return "no memory";
6236   std::string S = "memory:";
6237   if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM))
6238     S += "stack,";
6239   if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM))
6240     S += "constant,";
6241   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_INTERNAL_MEM))
6242     S += "internal global,";
6243   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_EXTERNAL_MEM))
6244     S += "external global,";
6245   if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM))
6246     S += "argument,";
6247   if (0 == (MLK & AAMemoryLocation::NO_INACCESSIBLE_MEM))
6248     S += "inaccessible,";
6249   if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM))
6250     S += "malloced,";
6251   if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM))
6252     S += "unknown,";
6253   S.pop_back();
6254   return S;
6255 }
6256 
6257 namespace {
6258 struct AAMemoryLocationImpl : public AAMemoryLocation {
6259 
6260   AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A)
6261       : AAMemoryLocation(IRP, A), Allocator(A.Allocator) {
6262     for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u)
6263       AccessKind2Accesses[u] = nullptr;
6264   }
6265 
6266   ~AAMemoryLocationImpl() {
6267     // The AccessSets are allocated via a BumpPtrAllocator, we call
6268     // the destructor manually.
6269     for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u)
6270       if (AccessKind2Accesses[u])
6271         AccessKind2Accesses[u]->~AccessSet();
6272   }
6273 
6274   /// See AbstractAttribute::initialize(...).
6275   void initialize(Attributor &A) override {
6276     intersectAssumedBits(BEST_STATE);
6277     getKnownStateFromValue(A, getIRPosition(), getState());
6278     IRAttribute::initialize(A);
6279   }
6280 
6281   /// Return the memory behavior information encoded in the IR for \p IRP.
6282   static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP,
6283                                      BitIntegerState &State,
6284                                      bool IgnoreSubsumingPositions = false) {
6285     // For internal functions we ignore `argmemonly` and
6286     // `inaccessiblememorargmemonly` as we might break it via interprocedural
6287     // constant propagation. It is unclear if this is the best way but it is
6288     // unlikely this will cause real performance problems. If we are deriving
6289     // attributes for the anchor function we even remove the attribute in
6290     // addition to ignoring it.
6291     bool UseArgMemOnly = true;
6292     Function *AnchorFn = IRP.getAnchorScope();
6293     if (AnchorFn && A.isRunOn(*AnchorFn))
6294       UseArgMemOnly = !AnchorFn->hasLocalLinkage();
6295 
6296     SmallVector<Attribute, 2> Attrs;
6297     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
6298     for (const Attribute &Attr : Attrs) {
6299       switch (Attr.getKindAsEnum()) {
6300       case Attribute::ReadNone:
6301         State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM);
6302         break;
6303       case Attribute::InaccessibleMemOnly:
6304         State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
6305         break;
6306       case Attribute::ArgMemOnly:
6307         if (UseArgMemOnly)
6308           State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true));
6309         else
6310           IRP.removeAttrs({Attribute::ArgMemOnly});
6311         break;
6312       case Attribute::InaccessibleMemOrArgMemOnly:
6313         if (UseArgMemOnly)
6314           State.addKnownBits(inverseLocation(
6315               NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true));
6316         else
6317           IRP.removeAttrs({Attribute::InaccessibleMemOrArgMemOnly});
6318         break;
6319       default:
6320         llvm_unreachable("Unexpected attribute!");
6321       }
6322     }
6323   }
6324 
6325   /// See AbstractAttribute::getDeducedAttributes(...).
6326   void getDeducedAttributes(LLVMContext &Ctx,
6327                             SmallVectorImpl<Attribute> &Attrs) const override {
6328     assert(Attrs.size() == 0);
6329     if (isAssumedReadNone()) {
6330       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
6331     } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) {
6332       if (isAssumedInaccessibleMemOnly())
6333         Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly));
6334       else if (isAssumedArgMemOnly())
6335         Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly));
6336       else if (isAssumedInaccessibleOrArgMemOnly())
6337         Attrs.push_back(
6338             Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly));
6339     }
6340     assert(Attrs.size() <= 1);
6341   }
6342 
6343   /// See AbstractAttribute::manifest(...).
6344   ChangeStatus manifest(Attributor &A) override {
6345     const IRPosition &IRP = getIRPosition();
6346 
6347     // Check if we would improve the existing attributes first.
6348     SmallVector<Attribute, 4> DeducedAttrs;
6349     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
6350     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
6351           return IRP.hasAttr(Attr.getKindAsEnum(),
6352                              /* IgnoreSubsumingPositions */ true);
6353         }))
6354       return ChangeStatus::UNCHANGED;
6355 
6356     // Clear existing attributes.
6357     IRP.removeAttrs(AttrKinds);
6358     if (isAssumedReadNone())
6359       IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds);
6360 
6361     // Use the generic manifest method.
6362     return IRAttribute::manifest(A);
6363   }
6364 
6365   /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...).
6366   bool checkForAllAccessesToMemoryKind(
6367       function_ref<bool(const Instruction *, const Value *, AccessKind,
6368                         MemoryLocationsKind)>
6369           Pred,
6370       MemoryLocationsKind RequestedMLK) const override {
6371     if (!isValidState())
6372       return false;
6373 
6374     MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
6375     if (AssumedMLK == NO_LOCATIONS)
6376       return true;
6377 
6378     unsigned Idx = 0;
6379     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS;
6380          CurMLK *= 2, ++Idx) {
6381       if (CurMLK & RequestedMLK)
6382         continue;
6383 
6384       if (const AccessSet *Accesses = AccessKind2Accesses[Idx])
6385         for (const AccessInfo &AI : *Accesses)
6386           if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
6387             return false;
6388     }
6389 
6390     return true;
6391   }
6392 
6393   ChangeStatus indicatePessimisticFixpoint() override {
6394     // If we give up and indicate a pessimistic fixpoint this instruction will
6395     // become an access for all potential access kinds:
6396     // TODO: Add pointers for argmemonly and globals to improve the results of
6397     //       checkForAllAccessesToMemoryKind.
6398     bool Changed = false;
6399     MemoryLocationsKind KnownMLK = getKnown();
6400     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
6401     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
6402       if (!(CurMLK & KnownMLK))
6403         updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed,
6404                                   getAccessKindFromInst(I));
6405     return AAMemoryLocation::indicatePessimisticFixpoint();
6406   }
6407 
6408 protected:
6409   /// Helper struct to tie together an instruction that has a read or write
6410   /// effect with the pointer it accesses (if any).
6411   struct AccessInfo {
6412 
6413     /// The instruction that caused the access.
6414     const Instruction *I;
6415 
6416     /// The base pointer that is accessed, or null if unknown.
6417     const Value *Ptr;
6418 
6419     /// The kind of access (read/write/read+write).
6420     AccessKind Kind;
6421 
6422     bool operator==(const AccessInfo &RHS) const {
6423       return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind;
6424     }
6425     bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const {
6426       if (LHS.I != RHS.I)
6427         return LHS.I < RHS.I;
6428       if (LHS.Ptr != RHS.Ptr)
6429         return LHS.Ptr < RHS.Ptr;
6430       if (LHS.Kind != RHS.Kind)
6431         return LHS.Kind < RHS.Kind;
6432       return false;
6433     }
6434   };
6435 
6436   /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the
6437   /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind.
6438   using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>;
6439   AccessSet *AccessKind2Accesses[llvm::CTLog2<VALID_STATE>()];
6440 
6441   /// Categorize the pointer arguments of CB that might access memory in
6442   /// AccessedLoc and update the state and access map accordingly.
6443   void
6444   categorizeArgumentPointerLocations(Attributor &A, CallBase &CB,
6445                                      AAMemoryLocation::StateType &AccessedLocs,
6446                                      bool &Changed);
6447 
6448   /// Return the kind(s) of location that may be accessed by \p V.
6449   AAMemoryLocation::MemoryLocationsKind
6450   categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed);
6451 
6452   /// Return the access kind as determined by \p I.
6453   AccessKind getAccessKindFromInst(const Instruction *I) {
6454     AccessKind AK = READ_WRITE;
6455     if (I) {
6456       AK = I->mayReadFromMemory() ? READ : NONE;
6457       AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE));
6458     }
6459     return AK;
6460   }
6461 
6462   /// Update the state \p State and the AccessKind2Accesses given that \p I is
6463   /// an access of kind \p AK to a \p MLK memory location with the access
6464   /// pointer \p Ptr.
6465   void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
6466                                  MemoryLocationsKind MLK, const Instruction *I,
6467                                  const Value *Ptr, bool &Changed,
6468                                  AccessKind AK = READ_WRITE) {
6469 
6470     assert(isPowerOf2_32(MLK) && "Expected a single location set!");
6471     auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)];
6472     if (!Accesses)
6473       Accesses = new (Allocator) AccessSet();
6474     Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second;
6475     State.removeAssumedBits(MLK);
6476   }
6477 
6478   /// Determine the underlying locations kinds for \p Ptr, e.g., globals or
6479   /// arguments, and update the state and access map accordingly.
6480   void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr,
6481                           AAMemoryLocation::StateType &State, bool &Changed);
6482 
6483   /// Used to allocate access sets.
6484   BumpPtrAllocator &Allocator;
6485 
6486   /// The set of IR attributes AAMemoryLocation deals with.
6487   static const Attribute::AttrKind AttrKinds[4];
6488 };
6489 
6490 const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = {
6491     Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly,
6492     Attribute::InaccessibleMemOrArgMemOnly};
6493 
6494 void AAMemoryLocationImpl::categorizePtrValue(
6495     Attributor &A, const Instruction &I, const Value &Ptr,
6496     AAMemoryLocation::StateType &State, bool &Changed) {
6497   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for "
6498                     << Ptr << " ["
6499                     << getMemoryLocationsAsStr(State.getAssumed()) << "]\n");
6500 
6501   auto StripGEPCB = [](Value *V) -> Value * {
6502     auto *GEP = dyn_cast<GEPOperator>(V);
6503     while (GEP) {
6504       V = GEP->getPointerOperand();
6505       GEP = dyn_cast<GEPOperator>(V);
6506     }
6507     return V;
6508   };
6509 
6510   auto VisitValueCB = [&](Value &V, const Instruction *,
6511                           AAMemoryLocation::StateType &T,
6512                           bool Stripped) -> bool {
6513     MemoryLocationsKind MLK = NO_LOCATIONS;
6514     assert(!isa<GEPOperator>(V) && "GEPs should have been stripped.");
6515     if (isa<UndefValue>(V))
6516       return true;
6517     if (auto *Arg = dyn_cast<Argument>(&V)) {
6518       if (Arg->hasByValAttr())
6519         MLK = NO_LOCAL_MEM;
6520       else
6521         MLK = NO_ARGUMENT_MEM;
6522     } else if (auto *GV = dyn_cast<GlobalValue>(&V)) {
6523       if (GV->hasLocalLinkage())
6524         MLK = NO_GLOBAL_INTERNAL_MEM;
6525       else
6526         MLK = NO_GLOBAL_EXTERNAL_MEM;
6527     } else if (isa<ConstantPointerNull>(V) &&
6528                !NullPointerIsDefined(getAssociatedFunction(),
6529                                      V.getType()->getPointerAddressSpace())) {
6530       return true;
6531     } else if (isa<AllocaInst>(V)) {
6532       MLK = NO_LOCAL_MEM;
6533     } else if (const auto *CB = dyn_cast<CallBase>(&V)) {
6534       const auto &NoAliasAA =
6535           A.getAAFor<AANoAlias>(*this, IRPosition::callsite_returned(*CB));
6536       if (NoAliasAA.isAssumedNoAlias())
6537         MLK = NO_MALLOCED_MEM;
6538       else
6539         MLK = NO_UNKOWN_MEM;
6540     } else {
6541       MLK = NO_UNKOWN_MEM;
6542     }
6543 
6544     assert(MLK != NO_LOCATIONS && "No location specified!");
6545     updateStateAndAccessesMap(T, MLK, &I, &V, Changed,
6546                               getAccessKindFromInst(&I));
6547     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value cannot be categorized: "
6548                       << V << " -> " << getMemoryLocationsAsStr(T.getAssumed())
6549                       << "\n");
6550     return true;
6551   };
6552 
6553   if (!genericValueTraversal<AAMemoryLocation, AAMemoryLocation::StateType>(
6554           A, IRPosition::value(Ptr), *this, State, VisitValueCB, getCtxI(),
6555           /* UseValueSimplify */ true,
6556           /* MaxValues */ 32, StripGEPCB)) {
6557     LLVM_DEBUG(
6558         dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n");
6559     updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed,
6560                               getAccessKindFromInst(&I));
6561   } else {
6562     LLVM_DEBUG(
6563         dbgs()
6564         << "[AAMemoryLocation] Accessed locations with pointer locations: "
6565         << getMemoryLocationsAsStr(State.getAssumed()) << "\n");
6566   }
6567 }
6568 
6569 void AAMemoryLocationImpl::categorizeArgumentPointerLocations(
6570     Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs,
6571     bool &Changed) {
6572   for (unsigned ArgNo = 0, E = CB.getNumArgOperands(); ArgNo < E; ++ArgNo) {
6573 
6574     // Skip non-pointer arguments.
6575     const Value *ArgOp = CB.getArgOperand(ArgNo);
6576     if (!ArgOp->getType()->isPtrOrPtrVectorTy())
6577       continue;
6578 
6579     // Skip readnone arguments.
6580     const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo);
6581     const auto &ArgOpMemLocationAA = A.getAAFor<AAMemoryBehavior>(
6582         *this, ArgOpIRP, /* TrackDependence */ true, DepClassTy::OPTIONAL);
6583 
6584     if (ArgOpMemLocationAA.isAssumedReadNone())
6585       continue;
6586 
6587     // Categorize potentially accessed pointer arguments as if there was an
6588     // access instruction with them as pointer.
6589     categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed);
6590   }
6591 }
6592 
6593 AAMemoryLocation::MemoryLocationsKind
6594 AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I,
6595                                                   bool &Changed) {
6596   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for "
6597                     << I << "\n");
6598 
6599   AAMemoryLocation::StateType AccessedLocs;
6600   AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
6601 
6602   if (auto *CB = dyn_cast<CallBase>(&I)) {
6603 
6604     // First check if we assume any memory is access is visible.
6605     const auto &CBMemLocationAA =
6606         A.getAAFor<AAMemoryLocation>(*this, IRPosition::callsite_function(*CB));
6607     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I
6608                       << " [" << CBMemLocationAA << "]\n");
6609 
6610     if (CBMemLocationAA.isAssumedReadNone())
6611       return NO_LOCATIONS;
6612 
6613     if (CBMemLocationAA.isAssumedInaccessibleMemOnly()) {
6614       updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr,
6615                                 Changed, getAccessKindFromInst(&I));
6616       return AccessedLocs.getAssumed();
6617     }
6618 
6619     uint32_t CBAssumedNotAccessedLocs =
6620         CBMemLocationAA.getAssumedNotAccessedLocation();
6621 
6622     // Set the argmemonly and global bit as we handle them separately below.
6623     uint32_t CBAssumedNotAccessedLocsNoArgMem =
6624         CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
6625 
6626     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
6627       if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
6628         continue;
6629       updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed,
6630                                 getAccessKindFromInst(&I));
6631     }
6632 
6633     // Now handle global memory if it might be accessed. This is slightly tricky
6634     // as NO_GLOBAL_MEM has multiple bits set.
6635     bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
6636     if (HasGlobalAccesses) {
6637       auto AccessPred = [&](const Instruction *, const Value *Ptr,
6638                             AccessKind Kind, MemoryLocationsKind MLK) {
6639         updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed,
6640                                   getAccessKindFromInst(&I));
6641         return true;
6642       };
6643       if (!CBMemLocationAA.checkForAllAccessesToMemoryKind(
6644               AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false)))
6645         return AccessedLocs.getWorstState();
6646     }
6647 
6648     LLVM_DEBUG(
6649         dbgs() << "[AAMemoryLocation] Accessed state before argument handling: "
6650                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
6651 
6652     // Now handle argument memory if it might be accessed.
6653     bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
6654     if (HasArgAccesses)
6655       categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed);
6656 
6657     LLVM_DEBUG(
6658         dbgs() << "[AAMemoryLocation] Accessed state after argument handling: "
6659                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
6660 
6661     return AccessedLocs.getAssumed();
6662   }
6663 
6664   if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) {
6665     LLVM_DEBUG(
6666         dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: "
6667                << I << " [" << *Ptr << "]\n");
6668     categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed);
6669     return AccessedLocs.getAssumed();
6670   }
6671 
6672   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: "
6673                     << I << "\n");
6674   updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed,
6675                             getAccessKindFromInst(&I));
6676   return AccessedLocs.getAssumed();
6677 }
6678 
6679 /// An AA to represent the memory behavior function attributes.
6680 struct AAMemoryLocationFunction final : public AAMemoryLocationImpl {
6681   AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A)
6682       : AAMemoryLocationImpl(IRP, A) {}
6683 
6684   /// See AbstractAttribute::updateImpl(Attributor &A).
6685   virtual ChangeStatus updateImpl(Attributor &A) override {
6686 
6687     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
6688         *this, getIRPosition(), /* TrackDependence */ false);
6689     if (MemBehaviorAA.isAssumedReadNone()) {
6690       if (MemBehaviorAA.isKnownReadNone())
6691         return indicateOptimisticFixpoint();
6692       assert(isAssumedReadNone() &&
6693              "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
6694       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
6695       return ChangeStatus::UNCHANGED;
6696     }
6697 
6698     // The current assumed state used to determine a change.
6699     auto AssumedState = getAssumed();
6700     bool Changed = false;
6701 
6702     auto CheckRWInst = [&](Instruction &I) {
6703       MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed);
6704       LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I
6705                         << ": " << getMemoryLocationsAsStr(MLK) << "\n");
6706       removeAssumedBits(inverseLocation(MLK, false, false));
6707       // Stop once only the valid bit set in the *not assumed location*, thus
6708       // once we don't actually exclude any memory locations in the state.
6709       return getAssumedNotAccessedLocation() != VALID_STATE;
6710     };
6711 
6712     if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this))
6713       return indicatePessimisticFixpoint();
6714 
6715     Changed |= AssumedState != getAssumed();
6716     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
6717   }
6718 
6719   /// See AbstractAttribute::trackStatistics()
6720   void trackStatistics() const override {
6721     if (isAssumedReadNone())
6722       STATS_DECLTRACK_FN_ATTR(readnone)
6723     else if (isAssumedArgMemOnly())
6724       STATS_DECLTRACK_FN_ATTR(argmemonly)
6725     else if (isAssumedInaccessibleMemOnly())
6726       STATS_DECLTRACK_FN_ATTR(inaccessiblememonly)
6727     else if (isAssumedInaccessibleOrArgMemOnly())
6728       STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly)
6729   }
6730 };
6731 
6732 /// AAMemoryLocation attribute for call sites.
6733 struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
6734   AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A)
6735       : AAMemoryLocationImpl(IRP, A) {}
6736 
6737   /// See AbstractAttribute::initialize(...).
6738   void initialize(Attributor &A) override {
6739     AAMemoryLocationImpl::initialize(A);
6740     Function *F = getAssociatedFunction();
6741     if (!F || !A.isFunctionIPOAmendable(*F)) {
6742       indicatePessimisticFixpoint();
6743       return;
6744     }
6745   }
6746 
6747   /// See AbstractAttribute::updateImpl(...).
6748   ChangeStatus updateImpl(Attributor &A) override {
6749     // TODO: Once we have call site specific value information we can provide
6750     //       call site specific liveness liveness information and then it makes
6751     //       sense to specialize attributes for call sites arguments instead of
6752     //       redirecting requests to the callee argument.
6753     Function *F = getAssociatedFunction();
6754     const IRPosition &FnPos = IRPosition::function(*F);
6755     auto &FnAA = A.getAAFor<AAMemoryLocation>(*this, FnPos);
6756     bool Changed = false;
6757     auto AccessPred = [&](const Instruction *I, const Value *Ptr,
6758                           AccessKind Kind, MemoryLocationsKind MLK) {
6759       updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed,
6760                                 getAccessKindFromInst(I));
6761       return true;
6762     };
6763     if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
6764       return indicatePessimisticFixpoint();
6765     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
6766   }
6767 
6768   /// See AbstractAttribute::trackStatistics()
6769   void trackStatistics() const override {
6770     if (isAssumedReadNone())
6771       STATS_DECLTRACK_CS_ATTR(readnone)
6772   }
6773 };
6774 
6775 /// ------------------ Value Constant Range Attribute -------------------------
6776 
6777 struct AAValueConstantRangeImpl : AAValueConstantRange {
6778   using StateType = IntegerRangeState;
6779   AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A)
6780       : AAValueConstantRange(IRP, A) {}
6781 
6782   /// See AbstractAttribute::getAsStr().
6783   const std::string getAsStr() const override {
6784     std::string Str;
6785     llvm::raw_string_ostream OS(Str);
6786     OS << "range(" << getBitWidth() << ")<";
6787     getKnown().print(OS);
6788     OS << " / ";
6789     getAssumed().print(OS);
6790     OS << ">";
6791     return OS.str();
6792   }
6793 
6794   /// Helper function to get a SCEV expr for the associated value at program
6795   /// point \p I.
6796   const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const {
6797     if (!getAnchorScope())
6798       return nullptr;
6799 
6800     ScalarEvolution *SE =
6801         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
6802             *getAnchorScope());
6803 
6804     LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
6805         *getAnchorScope());
6806 
6807     if (!SE || !LI)
6808       return nullptr;
6809 
6810     const SCEV *S = SE->getSCEV(&getAssociatedValue());
6811     if (!I)
6812       return S;
6813 
6814     return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent()));
6815   }
6816 
6817   /// Helper function to get a range from SCEV for the associated value at
6818   /// program point \p I.
6819   ConstantRange getConstantRangeFromSCEV(Attributor &A,
6820                                          const Instruction *I = nullptr) const {
6821     if (!getAnchorScope())
6822       return getWorstState(getBitWidth());
6823 
6824     ScalarEvolution *SE =
6825         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
6826             *getAnchorScope());
6827 
6828     const SCEV *S = getSCEV(A, I);
6829     if (!SE || !S)
6830       return getWorstState(getBitWidth());
6831 
6832     return SE->getUnsignedRange(S);
6833   }
6834 
6835   /// Helper function to get a range from LVI for the associated value at
6836   /// program point \p I.
6837   ConstantRange
6838   getConstantRangeFromLVI(Attributor &A,
6839                           const Instruction *CtxI = nullptr) const {
6840     if (!getAnchorScope())
6841       return getWorstState(getBitWidth());
6842 
6843     LazyValueInfo *LVI =
6844         A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
6845             *getAnchorScope());
6846 
6847     if (!LVI || !CtxI)
6848       return getWorstState(getBitWidth());
6849     return LVI->getConstantRange(&getAssociatedValue(),
6850                                  const_cast<BasicBlock *>(CtxI->getParent()),
6851                                  const_cast<Instruction *>(CtxI));
6852   }
6853 
6854   /// See AAValueConstantRange::getKnownConstantRange(..).
6855   ConstantRange
6856   getKnownConstantRange(Attributor &A,
6857                         const Instruction *CtxI = nullptr) const override {
6858     if (!CtxI || CtxI == getCtxI())
6859       return getKnown();
6860 
6861     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
6862     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
6863     return getKnown().intersectWith(SCEVR).intersectWith(LVIR);
6864   }
6865 
6866   /// See AAValueConstantRange::getAssumedConstantRange(..).
6867   ConstantRange
6868   getAssumedConstantRange(Attributor &A,
6869                           const Instruction *CtxI = nullptr) const override {
6870     // TODO: Make SCEV use Attributor assumption.
6871     //       We may be able to bound a variable range via assumptions in
6872     //       Attributor. ex.) If x is assumed to be in [1, 3] and y is known to
6873     //       evolve to x^2 + x, then we can say that y is in [2, 12].
6874 
6875     if (!CtxI || CtxI == getCtxI())
6876       return getAssumed();
6877 
6878     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
6879     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
6880     return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
6881   }
6882 
6883   /// See AbstractAttribute::initialize(..).
6884   void initialize(Attributor &A) override {
6885     // Intersect a range given by SCEV.
6886     intersectKnown(getConstantRangeFromSCEV(A, getCtxI()));
6887 
6888     // Intersect a range given by LVI.
6889     intersectKnown(getConstantRangeFromLVI(A, getCtxI()));
6890   }
6891 
6892   /// Helper function to create MDNode for range metadata.
6893   static MDNode *
6894   getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx,
6895                             const ConstantRange &AssumedConstantRange) {
6896     Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get(
6897                                   Ty, AssumedConstantRange.getLower())),
6898                               ConstantAsMetadata::get(ConstantInt::get(
6899                                   Ty, AssumedConstantRange.getUpper()))};
6900     return MDNode::get(Ctx, LowAndHigh);
6901   }
6902 
6903   /// Return true if \p Assumed is included in \p KnownRanges.
6904   static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) {
6905 
6906     if (Assumed.isFullSet())
6907       return false;
6908 
6909     if (!KnownRanges)
6910       return true;
6911 
6912     // If multiple ranges are annotated in IR, we give up to annotate assumed
6913     // range for now.
6914 
6915     // TODO:  If there exists a known range which containts assumed range, we
6916     // can say assumed range is better.
6917     if (KnownRanges->getNumOperands() > 2)
6918       return false;
6919 
6920     ConstantInt *Lower =
6921         mdconst::extract<ConstantInt>(KnownRanges->getOperand(0));
6922     ConstantInt *Upper =
6923         mdconst::extract<ConstantInt>(KnownRanges->getOperand(1));
6924 
6925     ConstantRange Known(Lower->getValue(), Upper->getValue());
6926     return Known.contains(Assumed) && Known != Assumed;
6927   }
6928 
6929   /// Helper function to set range metadata.
6930   static bool
6931   setRangeMetadataIfisBetterRange(Instruction *I,
6932                                   const ConstantRange &AssumedConstantRange) {
6933     auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range);
6934     if (isBetterRange(AssumedConstantRange, OldRangeMD)) {
6935       if (!AssumedConstantRange.isEmptySet()) {
6936         I->setMetadata(LLVMContext::MD_range,
6937                        getMDNodeForConstantRange(I->getType(), I->getContext(),
6938                                                  AssumedConstantRange));
6939         return true;
6940       }
6941     }
6942     return false;
6943   }
6944 
6945   /// See AbstractAttribute::manifest()
6946   ChangeStatus manifest(Attributor &A) override {
6947     ChangeStatus Changed = ChangeStatus::UNCHANGED;
6948     ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
6949     assert(!AssumedConstantRange.isFullSet() && "Invalid state");
6950 
6951     auto &V = getAssociatedValue();
6952     if (!AssumedConstantRange.isEmptySet() &&
6953         !AssumedConstantRange.isSingleElement()) {
6954       if (Instruction *I = dyn_cast<Instruction>(&V))
6955         if (isa<CallInst>(I) || isa<LoadInst>(I))
6956           if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange))
6957             Changed = ChangeStatus::CHANGED;
6958     }
6959 
6960     return Changed;
6961   }
6962 };
6963 
6964 struct AAValueConstantRangeArgument final
6965     : AAArgumentFromCallSiteArguments<
6966           AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState> {
6967   using Base = AAArgumentFromCallSiteArguments<
6968       AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState>;
6969   AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A)
6970       : Base(IRP, A) {}
6971 
6972   /// See AbstractAttribute::initialize(..).
6973   void initialize(Attributor &A) override {
6974     if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
6975       indicatePessimisticFixpoint();
6976     } else {
6977       Base::initialize(A);
6978     }
6979   }
6980 
6981   /// See AbstractAttribute::trackStatistics()
6982   void trackStatistics() const override {
6983     STATS_DECLTRACK_ARG_ATTR(value_range)
6984   }
6985 };
6986 
6987 struct AAValueConstantRangeReturned
6988     : AAReturnedFromReturnedValues<AAValueConstantRange,
6989                                    AAValueConstantRangeImpl> {
6990   using Base = AAReturnedFromReturnedValues<AAValueConstantRange,
6991                                             AAValueConstantRangeImpl>;
6992   AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A)
6993       : Base(IRP, A) {}
6994 
6995   /// See AbstractAttribute::initialize(...).
6996   void initialize(Attributor &A) override {}
6997 
6998   /// See AbstractAttribute::trackStatistics()
6999   void trackStatistics() const override {
7000     STATS_DECLTRACK_FNRET_ATTR(value_range)
7001   }
7002 };
7003 
7004 struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
7005   AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A)
7006       : AAValueConstantRangeImpl(IRP, A) {}
7007 
7008   /// See AbstractAttribute::initialize(...).
7009   void initialize(Attributor &A) override {
7010     AAValueConstantRangeImpl::initialize(A);
7011     Value &V = getAssociatedValue();
7012 
7013     if (auto *C = dyn_cast<ConstantInt>(&V)) {
7014       unionAssumed(ConstantRange(C->getValue()));
7015       indicateOptimisticFixpoint();
7016       return;
7017     }
7018 
7019     if (isa<UndefValue>(&V)) {
7020       // Collapse the undef state to 0.
7021       unionAssumed(ConstantRange(APInt(getBitWidth(), 0)));
7022       indicateOptimisticFixpoint();
7023       return;
7024     }
7025 
7026     if (isa<CallBase>(&V))
7027       return;
7028 
7029     if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V))
7030       return;
7031     // If it is a load instruction with range metadata, use it.
7032     if (LoadInst *LI = dyn_cast<LoadInst>(&V))
7033       if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
7034         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
7035         return;
7036       }
7037 
7038     // We can work with PHI and select instruction as we traverse their operands
7039     // during update.
7040     if (isa<SelectInst>(V) || isa<PHINode>(V))
7041       return;
7042 
7043     // Otherwise we give up.
7044     indicatePessimisticFixpoint();
7045 
7046     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: "
7047                       << getAssociatedValue() << "\n");
7048   }
7049 
7050   bool calculateBinaryOperator(
7051       Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T,
7052       const Instruction *CtxI,
7053       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
7054     Value *LHS = BinOp->getOperand(0);
7055     Value *RHS = BinOp->getOperand(1);
7056     // TODO: Allow non integers as well.
7057     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
7058       return false;
7059 
7060     auto &LHSAA =
7061         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*LHS));
7062     QuerriedAAs.push_back(&LHSAA);
7063     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
7064 
7065     auto &RHSAA =
7066         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*RHS));
7067     QuerriedAAs.push_back(&RHSAA);
7068     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
7069 
7070     auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange);
7071 
7072     T.unionAssumed(AssumedRange);
7073 
7074     // TODO: Track a known state too.
7075 
7076     return T.isValidState();
7077   }
7078 
7079   bool calculateCastInst(
7080       Attributor &A, CastInst *CastI, IntegerRangeState &T,
7081       const Instruction *CtxI,
7082       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
7083     assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!");
7084     // TODO: Allow non integers as well.
7085     Value &OpV = *CastI->getOperand(0);
7086     if (!OpV.getType()->isIntegerTy())
7087       return false;
7088 
7089     auto &OpAA =
7090         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(OpV));
7091     QuerriedAAs.push_back(&OpAA);
7092     T.unionAssumed(
7093         OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth()));
7094     return T.isValidState();
7095   }
7096 
7097   bool
7098   calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T,
7099                    const Instruction *CtxI,
7100                    SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
7101     Value *LHS = CmpI->getOperand(0);
7102     Value *RHS = CmpI->getOperand(1);
7103     // TODO: Allow non integers as well.
7104     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
7105       return false;
7106 
7107     auto &LHSAA =
7108         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*LHS));
7109     QuerriedAAs.push_back(&LHSAA);
7110     auto &RHSAA =
7111         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*RHS));
7112     QuerriedAAs.push_back(&RHSAA);
7113 
7114     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
7115     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
7116 
7117     // If one of them is empty set, we can't decide.
7118     if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
7119       return true;
7120 
7121     bool MustTrue = false, MustFalse = false;
7122 
7123     auto AllowedRegion =
7124         ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange);
7125 
7126     auto SatisfyingRegion = ConstantRange::makeSatisfyingICmpRegion(
7127         CmpI->getPredicate(), RHSAARange);
7128 
7129     if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
7130       MustFalse = true;
7131 
7132     if (SatisfyingRegion.contains(LHSAARange))
7133       MustTrue = true;
7134 
7135     assert((!MustTrue || !MustFalse) &&
7136            "Either MustTrue or MustFalse should be false!");
7137 
7138     if (MustTrue)
7139       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1)));
7140     else if (MustFalse)
7141       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0)));
7142     else
7143       T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true));
7144 
7145     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA
7146                       << " " << RHSAA << "\n");
7147 
7148     // TODO: Track a known state too.
7149     return T.isValidState();
7150   }
7151 
7152   /// See AbstractAttribute::updateImpl(...).
7153   ChangeStatus updateImpl(Attributor &A) override {
7154     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
7155                             IntegerRangeState &T, bool Stripped) -> bool {
7156       Instruction *I = dyn_cast<Instruction>(&V);
7157       if (!I || isa<CallBase>(I)) {
7158 
7159         // If the value is not instruction, we query AA to Attributor.
7160         const auto &AA =
7161             A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(V));
7162 
7163         // Clamp operator is not used to utilize a program point CtxI.
7164         T.unionAssumed(AA.getAssumedConstantRange(A, CtxI));
7165 
7166         return T.isValidState();
7167       }
7168 
7169       SmallVector<const AAValueConstantRange *, 4> QuerriedAAs;
7170       if (auto *BinOp = dyn_cast<BinaryOperator>(I)) {
7171         if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs))
7172           return false;
7173       } else if (auto *CmpI = dyn_cast<CmpInst>(I)) {
7174         if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs))
7175           return false;
7176       } else if (auto *CastI = dyn_cast<CastInst>(I)) {
7177         if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs))
7178           return false;
7179       } else {
7180         // Give up with other instructions.
7181         // TODO: Add other instructions
7182 
7183         T.indicatePessimisticFixpoint();
7184         return false;
7185       }
7186 
7187       // Catch circular reasoning in a pessimistic way for now.
7188       // TODO: Check how the range evolves and if we stripped anything, see also
7189       //       AADereferenceable or AAAlign for similar situations.
7190       for (const AAValueConstantRange *QueriedAA : QuerriedAAs) {
7191         if (QueriedAA != this)
7192           continue;
7193         // If we are in a stady state we do not need to worry.
7194         if (T.getAssumed() == getState().getAssumed())
7195           continue;
7196         T.indicatePessimisticFixpoint();
7197       }
7198 
7199       return T.isValidState();
7200     };
7201 
7202     IntegerRangeState T(getBitWidth());
7203 
7204     if (!genericValueTraversal<AAValueConstantRange, IntegerRangeState>(
7205             A, getIRPosition(), *this, T, VisitValueCB, getCtxI(),
7206             /* UseValueSimplify */ false))
7207       return indicatePessimisticFixpoint();
7208 
7209     return clampStateAndIndicateChange(getState(), T);
7210   }
7211 
7212   /// See AbstractAttribute::trackStatistics()
7213   void trackStatistics() const override {
7214     STATS_DECLTRACK_FLOATING_ATTR(value_range)
7215   }
7216 };
7217 
7218 struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
7219   AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A)
7220       : AAValueConstantRangeImpl(IRP, A) {}
7221 
7222   /// See AbstractAttribute::initialize(...).
7223   ChangeStatus updateImpl(Attributor &A) override {
7224     llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will "
7225                      "not be called");
7226   }
7227 
7228   /// See AbstractAttribute::trackStatistics()
7229   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) }
7230 };
7231 
7232 struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
7233   AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A)
7234       : AAValueConstantRangeFunction(IRP, A) {}
7235 
7236   /// See AbstractAttribute::trackStatistics()
7237   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) }
7238 };
7239 
7240 struct AAValueConstantRangeCallSiteReturned
7241     : AACallSiteReturnedFromReturned<AAValueConstantRange,
7242                                      AAValueConstantRangeImpl> {
7243   AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A)
7244       : AACallSiteReturnedFromReturned<AAValueConstantRange,
7245                                        AAValueConstantRangeImpl>(IRP, A) {}
7246 
7247   /// See AbstractAttribute::initialize(...).
7248   void initialize(Attributor &A) override {
7249     // If it is a load instruction with range metadata, use the metadata.
7250     if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue()))
7251       if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range))
7252         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
7253 
7254     AAValueConstantRangeImpl::initialize(A);
7255   }
7256 
7257   /// See AbstractAttribute::trackStatistics()
7258   void trackStatistics() const override {
7259     STATS_DECLTRACK_CSRET_ATTR(value_range)
7260   }
7261 };
7262 struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
7263   AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A)
7264       : AAValueConstantRangeFloating(IRP, A) {}
7265 
7266   /// See AbstractAttribute::trackStatistics()
7267   void trackStatistics() const override {
7268     STATS_DECLTRACK_CSARG_ATTR(value_range)
7269   }
7270 };
7271 
7272 /// ------------------ Potential Values Attribute -------------------------
7273 
7274 struct AAPotentialValuesImpl : AAPotentialValues {
7275   using StateType = PotentialConstantIntValuesState;
7276 
7277   AAPotentialValuesImpl(const IRPosition &IRP, Attributor &A)
7278       : AAPotentialValues(IRP, A) {}
7279 
7280   /// See AbstractAttribute::getAsStr().
7281   const std::string getAsStr() const override {
7282     std::string Str;
7283     llvm::raw_string_ostream OS(Str);
7284     OS << getState();
7285     return OS.str();
7286   }
7287 
7288   /// See AbstractAttribute::updateImpl(...).
7289   ChangeStatus updateImpl(Attributor &A) override {
7290     return indicatePessimisticFixpoint();
7291   }
7292 };
7293 
7294 struct AAPotentialValuesArgument final
7295     : AAArgumentFromCallSiteArguments<AAPotentialValues, AAPotentialValuesImpl,
7296                                       PotentialConstantIntValuesState> {
7297   using Base =
7298       AAArgumentFromCallSiteArguments<AAPotentialValues, AAPotentialValuesImpl,
7299                                       PotentialConstantIntValuesState>;
7300   AAPotentialValuesArgument(const IRPosition &IRP, Attributor &A)
7301       : Base(IRP, A) {}
7302 
7303   /// See AbstractAttribute::initialize(..).
7304   void initialize(Attributor &A) override {
7305     if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
7306       indicatePessimisticFixpoint();
7307     } else {
7308       Base::initialize(A);
7309     }
7310   }
7311 
7312   /// See AbstractAttribute::trackStatistics()
7313   void trackStatistics() const override {
7314     STATS_DECLTRACK_ARG_ATTR(potential_values)
7315   }
7316 };
7317 
7318 struct AAPotentialValuesReturned
7319     : AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl> {
7320   using Base =
7321       AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl>;
7322   AAPotentialValuesReturned(const IRPosition &IRP, Attributor &A)
7323       : Base(IRP, A) {}
7324 
7325   /// See AbstractAttribute::trackStatistics()
7326   void trackStatistics() const override {
7327     STATS_DECLTRACK_FNRET_ATTR(potential_values)
7328   }
7329 };
7330 
7331 struct AAPotentialValuesFloating : AAPotentialValuesImpl {
7332   AAPotentialValuesFloating(const IRPosition &IRP, Attributor &A)
7333       : AAPotentialValuesImpl(IRP, A) {}
7334 
7335   /// See AbstractAttribute::initialize(..).
7336   void initialize(Attributor &A) override {
7337     Value &V = getAssociatedValue();
7338 
7339     if (auto *C = dyn_cast<ConstantInt>(&V)) {
7340       unionAssumed(C->getValue());
7341       indicateOptimisticFixpoint();
7342       return;
7343     }
7344 
7345     if (isa<UndefValue>(&V)) {
7346       // Collapse the undef state to 0.
7347       unionAssumed(
7348           APInt(/* numBits */ getAssociatedType()->getIntegerBitWidth(),
7349                 /* val */ 0));
7350       indicateOptimisticFixpoint();
7351       return;
7352     }
7353 
7354     if (isa<BinaryOperator>(&V) || isa<ICmpInst>(&V) || isa<CastInst>(&V))
7355       return;
7356 
7357     if (isa<SelectInst>(V) || isa<PHINode>(V))
7358       return;
7359 
7360     indicatePessimisticFixpoint();
7361 
7362     LLVM_DEBUG(dbgs() << "[AAPotentialValues] We give up: "
7363                       << getAssociatedValue() << "\n");
7364   }
7365 
7366   static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS,
7367                                 const APInt &RHS) {
7368     ICmpInst::Predicate Pred = ICI->getPredicate();
7369     switch (Pred) {
7370     case ICmpInst::ICMP_UGT:
7371       return LHS.ugt(RHS);
7372     case ICmpInst::ICMP_SGT:
7373       return LHS.sgt(RHS);
7374     case ICmpInst::ICMP_EQ:
7375       return LHS.eq(RHS);
7376     case ICmpInst::ICMP_UGE:
7377       return LHS.uge(RHS);
7378     case ICmpInst::ICMP_SGE:
7379       return LHS.sge(RHS);
7380     case ICmpInst::ICMP_ULT:
7381       return LHS.ult(RHS);
7382     case ICmpInst::ICMP_SLT:
7383       return LHS.slt(RHS);
7384     case ICmpInst::ICMP_NE:
7385       return LHS.ne(RHS);
7386     case ICmpInst::ICMP_ULE:
7387       return LHS.ule(RHS);
7388     case ICmpInst::ICMP_SLE:
7389       return LHS.sle(RHS);
7390     default:
7391       llvm_unreachable("Invalid ICmp predicate!");
7392     }
7393   }
7394 
7395   static APInt calculateCastInst(const CastInst *CI, const APInt &Src,
7396                                  uint32_t ResultBitWidth) {
7397     Instruction::CastOps CastOp = CI->getOpcode();
7398     switch (CastOp) {
7399     default:
7400       llvm_unreachable("unsupported or not integer cast");
7401     case Instruction::Trunc:
7402       return Src.trunc(ResultBitWidth);
7403     case Instruction::SExt:
7404       return Src.sext(ResultBitWidth);
7405     case Instruction::ZExt:
7406       return Src.zext(ResultBitWidth);
7407     case Instruction::BitCast:
7408       return Src;
7409     }
7410   }
7411 
7412   static APInt calculateBinaryOperator(const BinaryOperator *BinOp,
7413                                        const APInt &LHS, const APInt &RHS,
7414                                        bool &SkipOperation, bool &Unsupported) {
7415     Instruction::BinaryOps BinOpcode = BinOp->getOpcode();
7416     // Unsupported is set to true when the binary operator is not supported.
7417     // SkipOperation is set to true when UB occur with the given operand pair
7418     // (LHS, RHS).
7419     // TODO: we should look at nsw and nuw keywords to handle operations
7420     //       that create poison or undef value.
7421     switch (BinOpcode) {
7422     default:
7423       Unsupported = true;
7424       return LHS;
7425     case Instruction::Add:
7426       return LHS + RHS;
7427     case Instruction::Sub:
7428       return LHS - RHS;
7429     case Instruction::Mul:
7430       return LHS * RHS;
7431     case Instruction::UDiv:
7432       if (RHS.isNullValue()) {
7433         SkipOperation = true;
7434         return LHS;
7435       }
7436       return LHS.udiv(RHS);
7437     case Instruction::SDiv:
7438       if (RHS.isNullValue()) {
7439         SkipOperation = true;
7440         return LHS;
7441       }
7442       return LHS.sdiv(RHS);
7443     case Instruction::URem:
7444       if (RHS.isNullValue()) {
7445         SkipOperation = true;
7446         return LHS;
7447       }
7448       return LHS.urem(RHS);
7449     case Instruction::SRem:
7450       if (RHS.isNullValue()) {
7451         SkipOperation = true;
7452         return LHS;
7453       }
7454       return LHS.srem(RHS);
7455     case Instruction::Shl:
7456       return LHS.shl(RHS);
7457     case Instruction::LShr:
7458       return LHS.lshr(RHS);
7459     case Instruction::AShr:
7460       return LHS.ashr(RHS);
7461     case Instruction::And:
7462       return LHS & RHS;
7463     case Instruction::Or:
7464       return LHS | RHS;
7465     case Instruction::Xor:
7466       return LHS ^ RHS;
7467     }
7468   }
7469 
7470   ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) {
7471     auto AssumedBefore = getAssumed();
7472     Value *LHS = ICI->getOperand(0);
7473     Value *RHS = ICI->getOperand(1);
7474     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
7475       return indicatePessimisticFixpoint();
7476 
7477     auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS));
7478     if (!LHSAA.isValidState())
7479       return indicatePessimisticFixpoint();
7480 
7481     auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS));
7482     if (!RHSAA.isValidState())
7483       return indicatePessimisticFixpoint();
7484 
7485     const DenseSet<APInt> &LHSAAPVS = LHSAA.getAssumedSet();
7486     const DenseSet<APInt> &RHSAAPVS = RHSAA.getAssumedSet();
7487 
7488     // TODO: Handle undef correctly.
7489     bool MaybeTrue = false, MaybeFalse = false;
7490     for (const APInt &L : LHSAAPVS) {
7491       for (const APInt &R : RHSAAPVS) {
7492         bool CmpResult = calculateICmpInst(ICI, L, R);
7493         MaybeTrue |= CmpResult;
7494         MaybeFalse |= !CmpResult;
7495         if (MaybeTrue & MaybeFalse)
7496           return indicatePessimisticFixpoint();
7497       }
7498     }
7499     if (MaybeTrue)
7500       unionAssumed(APInt(/* numBits */ 1, /* val */ 1));
7501     if (MaybeFalse)
7502       unionAssumed(APInt(/* numBits */ 1, /* val */ 0));
7503     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
7504                                          : ChangeStatus::CHANGED;
7505   }
7506 
7507   ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) {
7508     auto AssumedBefore = getAssumed();
7509     Value *LHS = SI->getTrueValue();
7510     Value *RHS = SI->getFalseValue();
7511     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
7512       return indicatePessimisticFixpoint();
7513 
7514     // TODO: Use assumed simplified condition value
7515     auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS));
7516     if (!LHSAA.isValidState())
7517       return indicatePessimisticFixpoint();
7518 
7519     auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS));
7520     if (!RHSAA.isValidState())
7521       return indicatePessimisticFixpoint();
7522 
7523     unionAssumed(LHSAA);
7524     unionAssumed(RHSAA);
7525     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
7526                                          : ChangeStatus::CHANGED;
7527   }
7528 
7529   ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) {
7530     auto AssumedBefore = getAssumed();
7531     if (!CI->isIntegerCast())
7532       return indicatePessimisticFixpoint();
7533     assert(CI->getNumOperands() == 1 && "Expected cast to be unary!");
7534     uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth();
7535     Value *Src = CI->getOperand(0);
7536     auto &SrcAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*Src));
7537     if (!SrcAA.isValidState())
7538       return indicatePessimisticFixpoint();
7539     const DenseSet<APInt> &SrcAAPVS = SrcAA.getAssumedSet();
7540     for (const APInt &S : SrcAAPVS) {
7541       APInt T = calculateCastInst(CI, S, ResultBitWidth);
7542       unionAssumed(T);
7543     }
7544     // TODO: Handle undef correctly.
7545     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
7546                                          : ChangeStatus::CHANGED;
7547   }
7548 
7549   ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) {
7550     auto AssumedBefore = getAssumed();
7551     Value *LHS = BinOp->getOperand(0);
7552     Value *RHS = BinOp->getOperand(1);
7553     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
7554       return indicatePessimisticFixpoint();
7555 
7556     auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS));
7557     if (!LHSAA.isValidState())
7558       return indicatePessimisticFixpoint();
7559 
7560     auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS));
7561     if (!RHSAA.isValidState())
7562       return indicatePessimisticFixpoint();
7563 
7564     const DenseSet<APInt> &LHSAAPVS = LHSAA.getAssumedSet();
7565     const DenseSet<APInt> &RHSAAPVS = RHSAA.getAssumedSet();
7566 
7567     // TODO: Handle undef correctly
7568     for (const APInt &L : LHSAAPVS) {
7569       for (const APInt &R : RHSAAPVS) {
7570         bool SkipOperation = false;
7571         bool Unsupported = false;
7572         APInt Result =
7573             calculateBinaryOperator(BinOp, L, R, SkipOperation, Unsupported);
7574         if (Unsupported)
7575           return indicatePessimisticFixpoint();
7576         // If SkipOperation is true, we can ignore this operand pair (L, R).
7577         if (!SkipOperation)
7578           unionAssumed(Result);
7579       }
7580     }
7581     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
7582                                          : ChangeStatus::CHANGED;
7583   }
7584 
7585   ChangeStatus updateWithPHINode(Attributor &A, PHINode *PHI) {
7586     auto AssumedBefore = getAssumed();
7587     for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
7588       Value *IncomingValue = PHI->getIncomingValue(u);
7589       auto &PotentialValuesAA = A.getAAFor<AAPotentialValues>(
7590           *this, IRPosition::value(*IncomingValue));
7591       if (!PotentialValuesAA.isValidState())
7592         return indicatePessimisticFixpoint();
7593       unionAssumed(PotentialValuesAA.getAssumed());
7594     }
7595     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
7596                                          : ChangeStatus::CHANGED;
7597   }
7598 
7599   /// See AbstractAttribute::updateImpl(...).
7600   ChangeStatus updateImpl(Attributor &A) override {
7601     Value &V = getAssociatedValue();
7602     Instruction *I = dyn_cast<Instruction>(&V);
7603 
7604     if (auto *ICI = dyn_cast<ICmpInst>(I))
7605       return updateWithICmpInst(A, ICI);
7606 
7607     if (auto *SI = dyn_cast<SelectInst>(I))
7608       return updateWithSelectInst(A, SI);
7609 
7610     if (auto *CI = dyn_cast<CastInst>(I))
7611       return updateWithCastInst(A, CI);
7612 
7613     if (auto *BinOp = dyn_cast<BinaryOperator>(I))
7614       return updateWithBinaryOperator(A, BinOp);
7615 
7616     if (auto *PHI = dyn_cast<PHINode>(I))
7617       return updateWithPHINode(A, PHI);
7618 
7619     return indicatePessimisticFixpoint();
7620   }
7621 
7622   /// See AbstractAttribute::trackStatistics()
7623   void trackStatistics() const override {
7624     STATS_DECLTRACK_FLOATING_ATTR(potential_values)
7625   }
7626 };
7627 
7628 struct AAPotentialValuesFunction : AAPotentialValuesImpl {
7629   AAPotentialValuesFunction(const IRPosition &IRP, Attributor &A)
7630       : AAPotentialValuesImpl(IRP, A) {}
7631 
7632   /// See AbstractAttribute::initialize(...).
7633   ChangeStatus updateImpl(Attributor &A) override {
7634     llvm_unreachable("AAPotentialValues(Function|CallSite)::updateImpl will "
7635                      "not be called");
7636   }
7637 
7638   /// See AbstractAttribute::trackStatistics()
7639   void trackStatistics() const override {
7640     STATS_DECLTRACK_FN_ATTR(potential_values)
7641   }
7642 };
7643 
7644 struct AAPotentialValuesCallSite : AAPotentialValuesFunction {
7645   AAPotentialValuesCallSite(const IRPosition &IRP, Attributor &A)
7646       : AAPotentialValuesFunction(IRP, A) {}
7647 
7648   /// See AbstractAttribute::trackStatistics()
7649   void trackStatistics() const override {
7650     STATS_DECLTRACK_CS_ATTR(potential_values)
7651   }
7652 };
7653 
7654 struct AAPotentialValuesCallSiteReturned
7655     : AACallSiteReturnedFromReturned<AAPotentialValues, AAPotentialValuesImpl> {
7656   AAPotentialValuesCallSiteReturned(const IRPosition &IRP, Attributor &A)
7657       : AACallSiteReturnedFromReturned<AAPotentialValues,
7658                                        AAPotentialValuesImpl>(IRP, A) {}
7659 
7660   /// See AbstractAttribute::trackStatistics()
7661   void trackStatistics() const override {
7662     STATS_DECLTRACK_CSRET_ATTR(potential_values)
7663   }
7664 };
7665 
7666 struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating {
7667   AAPotentialValuesCallSiteArgument(const IRPosition &IRP, Attributor &A)
7668       : AAPotentialValuesFloating(IRP, A) {}
7669 
7670   /// See AbstractAttribute::initialize(..).
7671   void initialize(Attributor &A) override {
7672     Value &V = getAssociatedValue();
7673 
7674     if (auto *C = dyn_cast<ConstantInt>(&V)) {
7675       unionAssumed(C->getValue());
7676       indicateOptimisticFixpoint();
7677       return;
7678     }
7679 
7680     if (isa<UndefValue>(&V)) {
7681       // Collapse the undef state to 0.
7682       unionAssumed(
7683           APInt(/* numBits */ getAssociatedType()->getIntegerBitWidth(),
7684                 /* val */ 0));
7685       indicateOptimisticFixpoint();
7686       return;
7687     }
7688   }
7689 
7690   /// See AbstractAttribute::updateImpl(...).
7691   ChangeStatus updateImpl(Attributor &A) override {
7692     Value &V = getAssociatedValue();
7693     auto AssumedBefore = getAssumed();
7694     auto &AA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(V));
7695     const auto &S = AA.getAssumed();
7696     unionAssumed(S);
7697     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
7698                                          : ChangeStatus::CHANGED;
7699   }
7700 
7701   /// See AbstractAttribute::trackStatistics()
7702   void trackStatistics() const override {
7703     STATS_DECLTRACK_CSARG_ATTR(potential_values)
7704   }
7705 };
7706 
7707 /// ------------------------ NoUndef Attribute ---------------------------------
7708 struct AANoUndefImpl : AANoUndef {
7709   AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {}
7710 
7711   /// See AbstractAttribute::initialize(...).
7712   void initialize(Attributor &A) override {
7713     Value &V = getAssociatedValue();
7714     if (isa<UndefValue>(V))
7715       indicatePessimisticFixpoint();
7716     else if (isa<FreezeInst>(V))
7717       indicateOptimisticFixpoint();
7718     else if (getPositionKind() != IRPosition::IRP_RETURNED &&
7719              isGuaranteedNotToBeUndefOrPoison(&V))
7720       indicateOptimisticFixpoint();
7721     else
7722       AANoUndef::initialize(A);
7723   }
7724 
7725   /// See followUsesInMBEC
7726   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
7727                        AANoUndef::StateType &State) {
7728     const Value *UseV = U->get();
7729     const DominatorTree *DT = nullptr;
7730     if (Function *F = getAnchorScope())
7731       DT = A.getInfoCache().getAnalysisResultForFunction<DominatorTreeAnalysis>(
7732           *F);
7733     State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, I, DT));
7734     bool TrackUse = false;
7735     // Track use for instructions which must produce undef or poison bits when
7736     // at least one operand contains such bits.
7737     if (isa<CastInst>(*I) || isa<GetElementPtrInst>(*I))
7738       TrackUse = true;
7739     return TrackUse;
7740   }
7741 
7742   /// See AbstractAttribute::getAsStr().
7743   const std::string getAsStr() const override {
7744     return getAssumed() ? "noundef" : "may-undef-or-poison";
7745   }
7746 };
7747 
7748 struct AANoUndefFloating : public AANoUndefImpl {
7749   AANoUndefFloating(const IRPosition &IRP, Attributor &A)
7750       : AANoUndefImpl(IRP, A) {}
7751 
7752   /// See AbstractAttribute::initialize(...).
7753   void initialize(Attributor &A) override {
7754     AANoUndefImpl::initialize(A);
7755     if (!getState().isAtFixpoint())
7756       if (Instruction *CtxI = getCtxI())
7757         followUsesInMBEC(*this, A, getState(), *CtxI);
7758   }
7759 
7760   /// See AbstractAttribute::updateImpl(...).
7761   ChangeStatus updateImpl(Attributor &A) override {
7762     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
7763                             AANoUndef::StateType &T, bool Stripped) -> bool {
7764       const auto &AA = A.getAAFor<AANoUndef>(*this, IRPosition::value(V));
7765       if (!Stripped && this == &AA) {
7766         T.indicatePessimisticFixpoint();
7767       } else {
7768         const AANoUndef::StateType &S =
7769             static_cast<const AANoUndef::StateType &>(AA.getState());
7770         T ^= S;
7771       }
7772       return T.isValidState();
7773     };
7774 
7775     StateType T;
7776     if (!genericValueTraversal<AANoUndef, StateType>(
7777             A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
7778       return indicatePessimisticFixpoint();
7779 
7780     return clampStateAndIndicateChange(getState(), T);
7781   }
7782 
7783   /// See AbstractAttribute::trackStatistics()
7784   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
7785 };
7786 
7787 struct AANoUndefReturned final
7788     : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> {
7789   AANoUndefReturned(const IRPosition &IRP, Attributor &A)
7790       : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>(IRP, A) {}
7791 
7792   /// See AbstractAttribute::trackStatistics()
7793   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
7794 };
7795 
7796 struct AANoUndefArgument final
7797     : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> {
7798   AANoUndefArgument(const IRPosition &IRP, Attributor &A)
7799       : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {}
7800 
7801   /// See AbstractAttribute::trackStatistics()
7802   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) }
7803 };
7804 
7805 struct AANoUndefCallSiteArgument final : AANoUndefFloating {
7806   AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A)
7807       : AANoUndefFloating(IRP, A) {}
7808 
7809   /// See AbstractAttribute::trackStatistics()
7810   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) }
7811 };
7812 
7813 struct AANoUndefCallSiteReturned final
7814     : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl> {
7815   AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A)
7816       : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl>(IRP, A) {}
7817 
7818   /// See AbstractAttribute::trackStatistics()
7819   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) }
7820 };
7821 } // namespace
7822 
7823 const char AAReturnedValues::ID = 0;
7824 const char AANoUnwind::ID = 0;
7825 const char AANoSync::ID = 0;
7826 const char AANoFree::ID = 0;
7827 const char AANonNull::ID = 0;
7828 const char AANoRecurse::ID = 0;
7829 const char AAWillReturn::ID = 0;
7830 const char AAUndefinedBehavior::ID = 0;
7831 const char AANoAlias::ID = 0;
7832 const char AAReachability::ID = 0;
7833 const char AANoReturn::ID = 0;
7834 const char AAIsDead::ID = 0;
7835 const char AADereferenceable::ID = 0;
7836 const char AAAlign::ID = 0;
7837 const char AANoCapture::ID = 0;
7838 const char AAValueSimplify::ID = 0;
7839 const char AAHeapToStack::ID = 0;
7840 const char AAPrivatizablePtr::ID = 0;
7841 const char AAMemoryBehavior::ID = 0;
7842 const char AAMemoryLocation::ID = 0;
7843 const char AAValueConstantRange::ID = 0;
7844 const char AAPotentialValues::ID = 0;
7845 const char AANoUndef::ID = 0;
7846 
7847 // Macro magic to create the static generator function for attributes that
7848 // follow the naming scheme.
7849 
7850 #define SWITCH_PK_INV(CLASS, PK, POS_NAME)                                     \
7851   case IRPosition::PK:                                                         \
7852     llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
7853 
7854 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX)                               \
7855   case IRPosition::PK:                                                         \
7856     AA = new (A.Allocator) CLASS##SUFFIX(IRP, A);                              \
7857     ++NumAAs;                                                                  \
7858     break;
7859 
7860 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                 \
7861   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7862     CLASS *AA = nullptr;                                                       \
7863     switch (IRP.getPositionKind()) {                                           \
7864       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7865       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
7866       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
7867       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
7868       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
7869       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
7870       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7871       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
7872     }                                                                          \
7873     return *AA;                                                                \
7874   }
7875 
7876 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                    \
7877   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7878     CLASS *AA = nullptr;                                                       \
7879     switch (IRP.getPositionKind()) {                                           \
7880       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7881       SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function")                           \
7882       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
7883       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
7884       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
7885       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
7886       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
7887       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
7888     }                                                                          \
7889     return *AA;                                                                \
7890   }
7891 
7892 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                      \
7893   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7894     CLASS *AA = nullptr;                                                       \
7895     switch (IRP.getPositionKind()) {                                           \
7896       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7897       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7898       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
7899       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
7900       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
7901       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
7902       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
7903       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
7904     }                                                                          \
7905     return *AA;                                                                \
7906   }
7907 
7908 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)            \
7909   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7910     CLASS *AA = nullptr;                                                       \
7911     switch (IRP.getPositionKind()) {                                           \
7912       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7913       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
7914       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
7915       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
7916       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
7917       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
7918       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
7919       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7920     }                                                                          \
7921     return *AA;                                                                \
7922   }
7923 
7924 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                  \
7925   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7926     CLASS *AA = nullptr;                                                       \
7927     switch (IRP.getPositionKind()) {                                           \
7928       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7929       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
7930       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7931       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
7932       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
7933       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
7934       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
7935       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
7936     }                                                                          \
7937     return *AA;                                                                \
7938   }
7939 
7940 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind)
7941 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync)
7942 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse)
7943 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn)
7944 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn)
7945 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues)
7946 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation)
7947 
7948 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull)
7949 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias)
7950 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr)
7951 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable)
7952 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign)
7953 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture)
7954 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange)
7955 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialValues)
7956 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUndef)
7957 
7958 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify)
7959 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead)
7960 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree)
7961 
7962 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack)
7963 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability)
7964 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior)
7965 
7966 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior)
7967 
7968 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
7969 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
7970 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
7971 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
7972 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
7973 #undef SWITCH_PK_CREATE
7974 #undef SWITCH_PK_INV
7975