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/APInt.h"
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumeBundleQueries.h"
28 #include "llvm/Analysis/AssumptionCache.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/Analysis/InstructionSimplify.h"
31 #include "llvm/Analysis/LazyValueInfo.h"
32 #include "llvm/Analysis/MemoryBuiltins.h"
33 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
34 #include "llvm/Analysis/ScalarEvolution.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/IR/Argument.h"
38 #include "llvm/IR/Assumptions.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/IRBuilder.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/NoFolder.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/IR/ValueHandle.h"
53 #include "llvm/Support/Alignment.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/GraphWriter.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Transforms/Utils/Local.h"
61 #include "llvm/Transforms/Utils/ValueMapper.h"
62 #include <cassert>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "attributor"
67 
68 static cl::opt<bool> ManifestInternal(
69     "attributor-manifest-internal", cl::Hidden,
70     cl::desc("Manifest Attributor internal string attributes."),
71     cl::init(false));
72 
73 static cl::opt<int> MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128),
74                                        cl::Hidden);
75 
76 template <>
77 unsigned llvm::PotentialConstantIntValuesState::MaxPotentialValues = 0;
78 
79 template <> unsigned llvm::PotentialLLVMValuesState::MaxPotentialValues = -1;
80 
81 static cl::opt<unsigned, true> MaxPotentialValues(
82     "attributor-max-potential-values", cl::Hidden,
83     cl::desc("Maximum number of potential values to be "
84              "tracked for each position."),
85     cl::location(llvm::PotentialConstantIntValuesState::MaxPotentialValues),
86     cl::init(7));
87 
88 static cl::opt<int> MaxPotentialValuesIterations(
89     "attributor-max-potential-values-iterations", cl::Hidden,
90     cl::desc(
91         "Maximum number of iterations we keep dismantling potential values."),
92     cl::init(64));
93 
94 static cl::opt<unsigned> MaxInterferingAccesses(
95     "attributor-max-interfering-accesses", cl::Hidden,
96     cl::desc("Maximum number of interfering accesses to "
97              "check before assuming all might interfere."),
98     cl::init(6));
99 
100 STATISTIC(NumAAs, "Number of abstract attributes created");
101 
102 // Some helper macros to deal with statistics tracking.
103 //
104 // Usage:
105 // For simple IR attribute tracking overload trackStatistics in the abstract
106 // attribute and choose the right STATS_DECLTRACK_********* macro,
107 // e.g.,:
108 //  void trackStatistics() const override {
109 //    STATS_DECLTRACK_ARG_ATTR(returned)
110 //  }
111 // If there is a single "increment" side one can use the macro
112 // STATS_DECLTRACK with a custom message. If there are multiple increment
113 // sides, STATS_DECL and STATS_TRACK can also be used separately.
114 //
115 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME)                                     \
116   ("Number of " #TYPE " marked '" #NAME "'")
117 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
118 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG);
119 #define STATS_DECL(NAME, TYPE, MSG)                                            \
120   STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG);
121 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
122 #define STATS_DECLTRACK(NAME, TYPE, MSG)                                       \
123   {                                                                            \
124     STATS_DECL(NAME, TYPE, MSG)                                                \
125     STATS_TRACK(NAME, TYPE)                                                    \
126   }
127 #define STATS_DECLTRACK_ARG_ATTR(NAME)                                         \
128   STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
129 #define STATS_DECLTRACK_CSARG_ATTR(NAME)                                       \
130   STATS_DECLTRACK(NAME, CSArguments,                                           \
131                   BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
132 #define STATS_DECLTRACK_FN_ATTR(NAME)                                          \
133   STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
134 #define STATS_DECLTRACK_CS_ATTR(NAME)                                          \
135   STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
136 #define STATS_DECLTRACK_FNRET_ATTR(NAME)                                       \
137   STATS_DECLTRACK(NAME, FunctionReturn,                                        \
138                   BUILD_STAT_MSG_IR_ATTR(function returns, NAME))
139 #define STATS_DECLTRACK_CSRET_ATTR(NAME)                                       \
140   STATS_DECLTRACK(NAME, CSReturn,                                              \
141                   BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
142 #define STATS_DECLTRACK_FLOATING_ATTR(NAME)                                    \
143   STATS_DECLTRACK(NAME, Floating,                                              \
144                   ("Number of floating values known to be '" #NAME "'"))
145 
146 // Specialization of the operator<< for abstract attributes subclasses. This
147 // disambiguates situations where multiple operators are applicable.
148 namespace llvm {
149 #define PIPE_OPERATOR(CLASS)                                                   \
150   raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) {                  \
151     return OS << static_cast<const AbstractAttribute &>(AA);                   \
152   }
153 
154 PIPE_OPERATOR(AAIsDead)
155 PIPE_OPERATOR(AANoUnwind)
156 PIPE_OPERATOR(AANoSync)
157 PIPE_OPERATOR(AANoRecurse)
158 PIPE_OPERATOR(AAWillReturn)
159 PIPE_OPERATOR(AANoReturn)
160 PIPE_OPERATOR(AAReturnedValues)
161 PIPE_OPERATOR(AANonNull)
162 PIPE_OPERATOR(AANoAlias)
163 PIPE_OPERATOR(AADereferenceable)
164 PIPE_OPERATOR(AAAlign)
165 PIPE_OPERATOR(AAInstanceInfo)
166 PIPE_OPERATOR(AANoCapture)
167 PIPE_OPERATOR(AAValueSimplify)
168 PIPE_OPERATOR(AANoFree)
169 PIPE_OPERATOR(AAHeapToStack)
170 PIPE_OPERATOR(AAReachability)
171 PIPE_OPERATOR(AAMemoryBehavior)
172 PIPE_OPERATOR(AAMemoryLocation)
173 PIPE_OPERATOR(AAValueConstantRange)
174 PIPE_OPERATOR(AAPrivatizablePtr)
175 PIPE_OPERATOR(AAUndefinedBehavior)
176 PIPE_OPERATOR(AAPotentialConstantValues)
177 PIPE_OPERATOR(AAPotentialValues)
178 PIPE_OPERATOR(AANoUndef)
179 PIPE_OPERATOR(AACallEdges)
180 PIPE_OPERATOR(AAFunctionReachability)
181 PIPE_OPERATOR(AAPointerInfo)
182 PIPE_OPERATOR(AAAssumptionInfo)
183 
184 #undef PIPE_OPERATOR
185 
186 template <>
187 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S,
188                                                      const DerefState &R) {
189   ChangeStatus CS0 =
190       clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState);
191   ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState);
192   return CS0 | CS1;
193 }
194 
195 } // namespace llvm
196 
197 /// Checks if a type could have padding bytes.
198 static bool isDenselyPacked(Type *Ty, const DataLayout &DL) {
199   // There is no size information, so be conservative.
200   if (!Ty->isSized())
201     return false;
202 
203   // If the alloc size is not equal to the storage size, then there are padding
204   // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
205   if (DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty))
206     return false;
207 
208   // FIXME: This isn't the right way to check for padding in vectors with
209   // non-byte-size elements.
210   if (VectorType *SeqTy = dyn_cast<VectorType>(Ty))
211     return isDenselyPacked(SeqTy->getElementType(), DL);
212 
213   // For array types, check for padding within members.
214   if (ArrayType *SeqTy = dyn_cast<ArrayType>(Ty))
215     return isDenselyPacked(SeqTy->getElementType(), DL);
216 
217   if (!isa<StructType>(Ty))
218     return true;
219 
220   // Check for padding within and between elements of a struct.
221   StructType *StructTy = cast<StructType>(Ty);
222   const StructLayout *Layout = DL.getStructLayout(StructTy);
223   uint64_t StartPos = 0;
224   for (unsigned I = 0, E = StructTy->getNumElements(); I < E; ++I) {
225     Type *ElTy = StructTy->getElementType(I);
226     if (!isDenselyPacked(ElTy, DL))
227       return false;
228     if (StartPos != Layout->getElementOffsetInBits(I))
229       return false;
230     StartPos += DL.getTypeAllocSizeInBits(ElTy);
231   }
232 
233   return true;
234 }
235 
236 /// Get pointer operand of memory accessing instruction. If \p I is
237 /// not a memory accessing instruction, return nullptr. If \p AllowVolatile,
238 /// is set to false and the instruction is volatile, return nullptr.
239 static const Value *getPointerOperand(const Instruction *I,
240                                       bool AllowVolatile) {
241   if (!AllowVolatile && I->isVolatile())
242     return nullptr;
243 
244   if (auto *LI = dyn_cast<LoadInst>(I)) {
245     return LI->getPointerOperand();
246   }
247 
248   if (auto *SI = dyn_cast<StoreInst>(I)) {
249     return SI->getPointerOperand();
250   }
251 
252   if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) {
253     return CXI->getPointerOperand();
254   }
255 
256   if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) {
257     return RMWI->getPointerOperand();
258   }
259 
260   return nullptr;
261 }
262 
263 /// Helper function to create a pointer of type \p ResTy, based on \p Ptr, and
264 /// advanced by \p Offset bytes. To aid later analysis the method tries to build
265 /// getelement pointer instructions that traverse the natural type of \p Ptr if
266 /// possible. If that fails, the remaining offset is adjusted byte-wise, hence
267 /// through a cast to i8*.
268 ///
269 /// TODO: This could probably live somewhere more prominantly if it doesn't
270 ///       already exist.
271 static Value *constructPointer(Type *ResTy, Type *PtrElemTy, Value *Ptr,
272                                int64_t Offset, IRBuilder<NoFolder> &IRB,
273                                const DataLayout &DL) {
274   assert(Offset >= 0 && "Negative offset not supported yet!");
275   LLVM_DEBUG(dbgs() << "Construct pointer: " << *Ptr << " + " << Offset
276                     << "-bytes as " << *ResTy << "\n");
277 
278   if (Offset) {
279     Type *Ty = PtrElemTy;
280     APInt IntOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), Offset);
281     SmallVector<APInt> IntIndices = DL.getGEPIndicesForOffset(Ty, IntOffset);
282 
283     SmallVector<Value *, 4> ValIndices;
284     std::string GEPName = Ptr->getName().str();
285     for (const APInt &Index : IntIndices) {
286       ValIndices.push_back(IRB.getInt(Index));
287       GEPName += "." + std::to_string(Index.getZExtValue());
288     }
289 
290     // Create a GEP for the indices collected above.
291     Ptr = IRB.CreateGEP(PtrElemTy, Ptr, ValIndices, GEPName);
292 
293     // If an offset is left we use byte-wise adjustment.
294     if (IntOffset != 0) {
295       Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy());
296       Ptr = IRB.CreateGEP(IRB.getInt8Ty(), Ptr, IRB.getInt(IntOffset),
297                           GEPName + ".b" + Twine(IntOffset.getZExtValue()));
298     }
299   }
300 
301   // Ensure the result has the requested type.
302   Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, ResTy,
303                                                 Ptr->getName() + ".cast");
304 
305   LLVM_DEBUG(dbgs() << "Constructed pointer: " << *Ptr << "\n");
306   return Ptr;
307 }
308 
309 bool AA::getAssumedUnderlyingObjects(Attributor &A, const Value &Ptr,
310                                      SmallSetVector<Value *, 8> &Objects,
311                                      const AbstractAttribute &QueryingAA,
312                                      const Instruction *CtxI,
313                                      bool &UsedAssumedInformation,
314                                      AA::ValueScope S,
315                                      SmallPtrSetImpl<Value *> *SeenObjects) {
316   SmallPtrSet<Value *, 8> LocalSeenObjects;
317   if (!SeenObjects)
318     SeenObjects = &LocalSeenObjects;
319 
320   SmallVector<AA::ValueAndContext> Values;
321   if (!A.getAssumedSimplifiedValues(IRPosition::value(Ptr), &QueryingAA, Values,
322                                     S, UsedAssumedInformation)) {
323     Objects.insert(const_cast<Value *>(&Ptr));
324     return true;
325   }
326 
327   for (auto &VAC : Values) {
328     Value *UO = getUnderlyingObject(VAC.getValue());
329     if (UO && UO != VAC.getValue() && SeenObjects->insert(UO).second) {
330       if (!getAssumedUnderlyingObjects(A, *UO, Objects, QueryingAA,
331                                        VAC.getCtxI(), UsedAssumedInformation, S,
332                                        SeenObjects))
333         return false;
334       continue;
335     }
336     Objects.insert(VAC.getValue());
337   }
338   return true;
339 }
340 
341 static const Value *
342 stripAndAccumulateOffsets(Attributor &A, const AbstractAttribute &QueryingAA,
343                           const Value *Val, const DataLayout &DL, APInt &Offset,
344                           bool GetMinOffset, bool AllowNonInbounds,
345                           bool UseAssumed = false) {
346 
347   auto AttributorAnalysis = [&](Value &V, APInt &ROffset) -> bool {
348     const IRPosition &Pos = IRPosition::value(V);
349     // Only track dependence if we are going to use the assumed info.
350     const AAValueConstantRange &ValueConstantRangeAA =
351         A.getAAFor<AAValueConstantRange>(QueryingAA, Pos,
352                                          UseAssumed ? DepClassTy::OPTIONAL
353                                                     : DepClassTy::NONE);
354     ConstantRange Range = UseAssumed ? ValueConstantRangeAA.getAssumed()
355                                      : ValueConstantRangeAA.getKnown();
356     if (Range.isFullSet())
357       return false;
358 
359     // We can only use the lower part of the range because the upper part can
360     // be higher than what the value can really be.
361     if (GetMinOffset)
362       ROffset = Range.getSignedMin();
363     else
364       ROffset = Range.getSignedMax();
365     return true;
366   };
367 
368   return Val->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds,
369                                                 /* AllowInvariant */ true,
370                                                 AttributorAnalysis);
371 }
372 
373 static const Value *
374 getMinimalBaseOfPointer(Attributor &A, const AbstractAttribute &QueryingAA,
375                         const Value *Ptr, int64_t &BytesOffset,
376                         const DataLayout &DL, bool AllowNonInbounds = false) {
377   APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
378   const Value *Base =
379       stripAndAccumulateOffsets(A, QueryingAA, Ptr, DL, OffsetAPInt,
380                                 /* GetMinOffset */ true, AllowNonInbounds);
381 
382   BytesOffset = OffsetAPInt.getSExtValue();
383   return Base;
384 }
385 
386 /// Clamp the information known for all returned values of a function
387 /// (identified by \p QueryingAA) into \p S.
388 template <typename AAType, typename StateType = typename AAType::StateType>
389 static void clampReturnedValueStates(
390     Attributor &A, const AAType &QueryingAA, StateType &S,
391     const IRPosition::CallBaseContext *CBContext = nullptr) {
392   LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for "
393                     << QueryingAA << " into " << S << "\n");
394 
395   assert((QueryingAA.getIRPosition().getPositionKind() ==
396               IRPosition::IRP_RETURNED ||
397           QueryingAA.getIRPosition().getPositionKind() ==
398               IRPosition::IRP_CALL_SITE_RETURNED) &&
399          "Can only clamp returned value states for a function returned or call "
400          "site returned position!");
401 
402   // Use an optional state as there might not be any return values and we want
403   // to join (IntegerState::operator&) the state of all there are.
404   Optional<StateType> T;
405 
406   // Callback for each possibly returned value.
407   auto CheckReturnValue = [&](Value &RV) -> bool {
408     const IRPosition &RVPos = IRPosition::value(RV, CBContext);
409     const AAType &AA =
410         A.getAAFor<AAType>(QueryingAA, RVPos, DepClassTy::REQUIRED);
411     LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr()
412                       << " @ " << RVPos << "\n");
413     const StateType &AAS = AA.getState();
414     if (!T)
415       T = StateType::getBestState(AAS);
416     *T &= AAS;
417     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T
418                       << "\n");
419     return T->isValidState();
420   };
421 
422   if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA))
423     S.indicatePessimisticFixpoint();
424   else if (T)
425     S ^= *T;
426 }
427 
428 namespace {
429 /// Helper class for generic deduction: return value -> returned position.
430 template <typename AAType, typename BaseType,
431           typename StateType = typename BaseType::StateType,
432           bool PropagateCallBaseContext = false>
433 struct AAReturnedFromReturnedValues : public BaseType {
434   AAReturnedFromReturnedValues(const IRPosition &IRP, Attributor &A)
435       : BaseType(IRP, A) {}
436 
437   /// See AbstractAttribute::updateImpl(...).
438   ChangeStatus updateImpl(Attributor &A) override {
439     StateType S(StateType::getBestState(this->getState()));
440     clampReturnedValueStates<AAType, StateType>(
441         A, *this, S,
442         PropagateCallBaseContext ? this->getCallBaseContext() : nullptr);
443     // TODO: If we know we visited all returned values, thus no are assumed
444     // dead, we can take the known information from the state T.
445     return clampStateAndIndicateChange<StateType>(this->getState(), S);
446   }
447 };
448 
449 /// Clamp the information known at all call sites for a given argument
450 /// (identified by \p QueryingAA) into \p S.
451 template <typename AAType, typename StateType = typename AAType::StateType>
452 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA,
453                                         StateType &S) {
454   LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for "
455                     << QueryingAA << " into " << S << "\n");
456 
457   assert(QueryingAA.getIRPosition().getPositionKind() ==
458              IRPosition::IRP_ARGUMENT &&
459          "Can only clamp call site argument states for an argument position!");
460 
461   // Use an optional state as there might not be any return values and we want
462   // to join (IntegerState::operator&) the state of all there are.
463   Optional<StateType> T;
464 
465   // The argument number which is also the call site argument number.
466   unsigned ArgNo = QueryingAA.getIRPosition().getCallSiteArgNo();
467 
468   auto CallSiteCheck = [&](AbstractCallSite ACS) {
469     const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
470     // Check if a coresponding argument was found or if it is on not associated
471     // (which can happen for callback calls).
472     if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
473       return false;
474 
475     const AAType &AA =
476         A.getAAFor<AAType>(QueryingAA, ACSArgPos, DepClassTy::REQUIRED);
477     LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction()
478                       << " AA: " << AA.getAsStr() << " @" << ACSArgPos << "\n");
479     const StateType &AAS = AA.getState();
480     if (!T)
481       T = StateType::getBestState(AAS);
482     *T &= AAS;
483     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T
484                       << "\n");
485     return T->isValidState();
486   };
487 
488   bool UsedAssumedInformation = false;
489   if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true,
490                               UsedAssumedInformation))
491     S.indicatePessimisticFixpoint();
492   else if (T)
493     S ^= *T;
494 }
495 
496 /// This function is the bridge between argument position and the call base
497 /// context.
498 template <typename AAType, typename BaseType,
499           typename StateType = typename AAType::StateType>
500 bool getArgumentStateFromCallBaseContext(Attributor &A,
501                                          BaseType &QueryingAttribute,
502                                          IRPosition &Pos, StateType &State) {
503   assert((Pos.getPositionKind() == IRPosition::IRP_ARGUMENT) &&
504          "Expected an 'argument' position !");
505   const CallBase *CBContext = Pos.getCallBaseContext();
506   if (!CBContext)
507     return false;
508 
509   int ArgNo = Pos.getCallSiteArgNo();
510   assert(ArgNo >= 0 && "Invalid Arg No!");
511 
512   const auto &AA = A.getAAFor<AAType>(
513       QueryingAttribute, IRPosition::callsite_argument(*CBContext, ArgNo),
514       DepClassTy::REQUIRED);
515   const StateType &CBArgumentState =
516       static_cast<const StateType &>(AA.getState());
517 
518   LLVM_DEBUG(dbgs() << "[Attributor] Briding Call site context to argument"
519                     << "Position:" << Pos << "CB Arg state:" << CBArgumentState
520                     << "\n");
521 
522   // NOTE: If we want to do call site grouping it should happen here.
523   State ^= CBArgumentState;
524   return true;
525 }
526 
527 /// Helper class for generic deduction: call site argument -> argument position.
528 template <typename AAType, typename BaseType,
529           typename StateType = typename AAType::StateType,
530           bool BridgeCallBaseContext = false>
531 struct AAArgumentFromCallSiteArguments : public BaseType {
532   AAArgumentFromCallSiteArguments(const IRPosition &IRP, Attributor &A)
533       : BaseType(IRP, A) {}
534 
535   /// See AbstractAttribute::updateImpl(...).
536   ChangeStatus updateImpl(Attributor &A) override {
537     StateType S = StateType::getBestState(this->getState());
538 
539     if (BridgeCallBaseContext) {
540       bool Success =
541           getArgumentStateFromCallBaseContext<AAType, BaseType, StateType>(
542               A, *this, this->getIRPosition(), S);
543       if (Success)
544         return clampStateAndIndicateChange<StateType>(this->getState(), S);
545     }
546     clampCallSiteArgumentStates<AAType, StateType>(A, *this, S);
547 
548     // TODO: If we know we visited all incoming values, thus no are assumed
549     // dead, we can take the known information from the state T.
550     return clampStateAndIndicateChange<StateType>(this->getState(), S);
551   }
552 };
553 
554 /// Helper class for generic replication: function returned -> cs returned.
555 template <typename AAType, typename BaseType,
556           typename StateType = typename BaseType::StateType,
557           bool IntroduceCallBaseContext = false>
558 struct AACallSiteReturnedFromReturned : public BaseType {
559   AACallSiteReturnedFromReturned(const IRPosition &IRP, Attributor &A)
560       : BaseType(IRP, A) {}
561 
562   /// See AbstractAttribute::updateImpl(...).
563   ChangeStatus updateImpl(Attributor &A) override {
564     assert(this->getIRPosition().getPositionKind() ==
565                IRPosition::IRP_CALL_SITE_RETURNED &&
566            "Can only wrap function returned positions for call site returned "
567            "positions!");
568     auto &S = this->getState();
569 
570     const Function *AssociatedFunction =
571         this->getIRPosition().getAssociatedFunction();
572     if (!AssociatedFunction)
573       return S.indicatePessimisticFixpoint();
574 
575     CallBase &CBContext = cast<CallBase>(this->getAnchorValue());
576     if (IntroduceCallBaseContext)
577       LLVM_DEBUG(dbgs() << "[Attributor] Introducing call base context:"
578                         << CBContext << "\n");
579 
580     IRPosition FnPos = IRPosition::returned(
581         *AssociatedFunction, IntroduceCallBaseContext ? &CBContext : nullptr);
582     const AAType &AA = A.getAAFor<AAType>(*this, FnPos, DepClassTy::REQUIRED);
583     return clampStateAndIndicateChange(S, AA.getState());
584   }
585 };
586 
587 /// Helper function to accumulate uses.
588 template <class AAType, typename StateType = typename AAType::StateType>
589 static void followUsesInContext(AAType &AA, Attributor &A,
590                                 MustBeExecutedContextExplorer &Explorer,
591                                 const Instruction *CtxI,
592                                 SetVector<const Use *> &Uses,
593                                 StateType &State) {
594   auto EIt = Explorer.begin(CtxI), EEnd = Explorer.end(CtxI);
595   for (unsigned u = 0; u < Uses.size(); ++u) {
596     const Use *U = Uses[u];
597     if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) {
598       bool Found = Explorer.findInContextOf(UserI, EIt, EEnd);
599       if (Found && AA.followUseInMBEC(A, U, UserI, State))
600         for (const Use &Us : UserI->uses())
601           Uses.insert(&Us);
602     }
603   }
604 }
605 
606 /// Use the must-be-executed-context around \p I to add information into \p S.
607 /// The AAType class is required to have `followUseInMBEC` method with the
608 /// following signature and behaviour:
609 ///
610 /// bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I)
611 /// U - Underlying use.
612 /// I - The user of the \p U.
613 /// Returns true if the value should be tracked transitively.
614 ///
615 template <class AAType, typename StateType = typename AAType::StateType>
616 static void followUsesInMBEC(AAType &AA, Attributor &A, StateType &S,
617                              Instruction &CtxI) {
618 
619   // Container for (transitive) uses of the associated value.
620   SetVector<const Use *> Uses;
621   for (const Use &U : AA.getIRPosition().getAssociatedValue().uses())
622     Uses.insert(&U);
623 
624   MustBeExecutedContextExplorer &Explorer =
625       A.getInfoCache().getMustBeExecutedContextExplorer();
626 
627   followUsesInContext<AAType>(AA, A, Explorer, &CtxI, Uses, S);
628 
629   if (S.isAtFixpoint())
630     return;
631 
632   SmallVector<const BranchInst *, 4> BrInsts;
633   auto Pred = [&](const Instruction *I) {
634     if (const BranchInst *Br = dyn_cast<BranchInst>(I))
635       if (Br->isConditional())
636         BrInsts.push_back(Br);
637     return true;
638   };
639 
640   // Here, accumulate conditional branch instructions in the context. We
641   // explore the child paths and collect the known states. The disjunction of
642   // those states can be merged to its own state. Let ParentState_i be a state
643   // to indicate the known information for an i-th branch instruction in the
644   // context. ChildStates are created for its successors respectively.
645   //
646   // ParentS_1 = ChildS_{1, 1} /\ ChildS_{1, 2} /\ ... /\ ChildS_{1, n_1}
647   // ParentS_2 = ChildS_{2, 1} /\ ChildS_{2, 2} /\ ... /\ ChildS_{2, n_2}
648   //      ...
649   // ParentS_m = ChildS_{m, 1} /\ ChildS_{m, 2} /\ ... /\ ChildS_{m, n_m}
650   //
651   // Known State |= ParentS_1 \/ ParentS_2 \/... \/ ParentS_m
652   //
653   // FIXME: Currently, recursive branches are not handled. For example, we
654   // can't deduce that ptr must be dereferenced in below function.
655   //
656   // void f(int a, int c, int *ptr) {
657   //    if(a)
658   //      if (b) {
659   //        *ptr = 0;
660   //      } else {
661   //        *ptr = 1;
662   //      }
663   //    else {
664   //      if (b) {
665   //        *ptr = 0;
666   //      } else {
667   //        *ptr = 1;
668   //      }
669   //    }
670   // }
671 
672   Explorer.checkForAllContext(&CtxI, Pred);
673   for (const BranchInst *Br : BrInsts) {
674     StateType ParentState;
675 
676     // The known state of the parent state is a conjunction of children's
677     // known states so it is initialized with a best state.
678     ParentState.indicateOptimisticFixpoint();
679 
680     for (const BasicBlock *BB : Br->successors()) {
681       StateType ChildState;
682 
683       size_t BeforeSize = Uses.size();
684       followUsesInContext(AA, A, Explorer, &BB->front(), Uses, ChildState);
685 
686       // Erase uses which only appear in the child.
687       for (auto It = Uses.begin() + BeforeSize; It != Uses.end();)
688         It = Uses.erase(It);
689 
690       ParentState &= ChildState;
691     }
692 
693     // Use only known state.
694     S += ParentState;
695   }
696 }
697 } // namespace
698 
699 /// ------------------------ PointerInfo ---------------------------------------
700 
701 namespace llvm {
702 namespace AA {
703 namespace PointerInfo {
704 
705 struct State;
706 
707 } // namespace PointerInfo
708 } // namespace AA
709 
710 /// Helper for AA::PointerInfo::Acccess DenseMap/Set usage.
711 template <>
712 struct DenseMapInfo<AAPointerInfo::Access> : DenseMapInfo<Instruction *> {
713   using Access = AAPointerInfo::Access;
714   static inline Access getEmptyKey();
715   static inline Access getTombstoneKey();
716   static unsigned getHashValue(const Access &A);
717   static bool isEqual(const Access &LHS, const Access &RHS);
718 };
719 
720 /// Helper that allows OffsetAndSize as a key in a DenseMap.
721 template <>
722 struct DenseMapInfo<AAPointerInfo ::OffsetAndSize>
723     : DenseMapInfo<std::pair<int64_t, int64_t>> {};
724 
725 /// Helper for AA::PointerInfo::Acccess DenseMap/Set usage ignoring everythign
726 /// but the instruction
727 struct AccessAsInstructionInfo : DenseMapInfo<Instruction *> {
728   using Base = DenseMapInfo<Instruction *>;
729   using Access = AAPointerInfo::Access;
730   static inline Access getEmptyKey();
731   static inline Access getTombstoneKey();
732   static unsigned getHashValue(const Access &A);
733   static bool isEqual(const Access &LHS, const Access &RHS);
734 };
735 
736 } // namespace llvm
737 
738 /// A type to track pointer/struct usage and accesses for AAPointerInfo.
739 struct AA::PointerInfo::State : public AbstractState {
740 
741   ~State() {
742     // We do not delete the Accesses objects but need to destroy them still.
743     for (auto &It : AccessBins)
744       It.second->~Accesses();
745   }
746 
747   /// Return the best possible representable state.
748   static State getBestState(const State &SIS) { return State(); }
749 
750   /// Return the worst possible representable state.
751   static State getWorstState(const State &SIS) {
752     State R;
753     R.indicatePessimisticFixpoint();
754     return R;
755   }
756 
757   State() = default;
758   State(State &&SIS) : AccessBins(std::move(SIS.AccessBins)) {
759     SIS.AccessBins.clear();
760   }
761 
762   const State &getAssumed() const { return *this; }
763 
764   /// See AbstractState::isValidState().
765   bool isValidState() const override { return BS.isValidState(); }
766 
767   /// See AbstractState::isAtFixpoint().
768   bool isAtFixpoint() const override { return BS.isAtFixpoint(); }
769 
770   /// See AbstractState::indicateOptimisticFixpoint().
771   ChangeStatus indicateOptimisticFixpoint() override {
772     BS.indicateOptimisticFixpoint();
773     return ChangeStatus::UNCHANGED;
774   }
775 
776   /// See AbstractState::indicatePessimisticFixpoint().
777   ChangeStatus indicatePessimisticFixpoint() override {
778     BS.indicatePessimisticFixpoint();
779     return ChangeStatus::CHANGED;
780   }
781 
782   State &operator=(const State &R) {
783     if (this == &R)
784       return *this;
785     BS = R.BS;
786     AccessBins = R.AccessBins;
787     return *this;
788   }
789 
790   State &operator=(State &&R) {
791     if (this == &R)
792       return *this;
793     std::swap(BS, R.BS);
794     std::swap(AccessBins, R.AccessBins);
795     return *this;
796   }
797 
798   bool operator==(const State &R) const {
799     if (BS != R.BS)
800       return false;
801     if (AccessBins.size() != R.AccessBins.size())
802       return false;
803     auto It = begin(), RIt = R.begin(), E = end();
804     while (It != E) {
805       if (It->getFirst() != RIt->getFirst())
806         return false;
807       auto &Accs = It->getSecond();
808       auto &RAccs = RIt->getSecond();
809       if (Accs->size() != RAccs->size())
810         return false;
811       for (const auto &ZipIt : llvm::zip(*Accs, *RAccs))
812         if (std::get<0>(ZipIt) != std::get<1>(ZipIt))
813           return false;
814       ++It;
815       ++RIt;
816     }
817     return true;
818   }
819   bool operator!=(const State &R) const { return !(*this == R); }
820 
821   /// We store accesses in a set with the instruction as key.
822   struct Accesses {
823     SmallVector<AAPointerInfo::Access, 4> Accesses;
824     DenseMap<const Instruction *, unsigned> Map;
825 
826     unsigned size() const { return Accesses.size(); }
827 
828     using vec_iterator = decltype(Accesses)::iterator;
829     vec_iterator begin() { return Accesses.begin(); }
830     vec_iterator end() { return Accesses.end(); }
831 
832     using iterator = decltype(Map)::const_iterator;
833     iterator find(AAPointerInfo::Access &Acc) {
834       return Map.find(Acc.getRemoteInst());
835     }
836     iterator find_end() { return Map.end(); }
837 
838     AAPointerInfo::Access &get(iterator &It) {
839       return Accesses[It->getSecond()];
840     }
841 
842     void insert(AAPointerInfo::Access &Acc) {
843       Map[Acc.getRemoteInst()] = Accesses.size();
844       Accesses.push_back(Acc);
845     }
846   };
847 
848   /// We store all accesses in bins denoted by their offset and size.
849   using AccessBinsTy = DenseMap<AAPointerInfo::OffsetAndSize, Accesses *>;
850 
851   AccessBinsTy::const_iterator begin() const { return AccessBins.begin(); }
852   AccessBinsTy::const_iterator end() const { return AccessBins.end(); }
853 
854 protected:
855   /// The bins with all the accesses for the associated pointer.
856   AccessBinsTy AccessBins;
857 
858   /// Add a new access to the state at offset \p Offset and with size \p Size.
859   /// The access is associated with \p I, writes \p Content (if anything), and
860   /// is of kind \p Kind.
861   /// \Returns CHANGED, if the state changed, UNCHANGED otherwise.
862   ChangeStatus addAccess(Attributor &A, int64_t Offset, int64_t Size,
863                          Instruction &I, Optional<Value *> Content,
864                          AAPointerInfo::AccessKind Kind, Type *Ty,
865                          Instruction *RemoteI = nullptr,
866                          Accesses *BinPtr = nullptr) {
867     AAPointerInfo::OffsetAndSize Key{Offset, Size};
868     Accesses *&Bin = BinPtr ? BinPtr : AccessBins[Key];
869     if (!Bin)
870       Bin = new (A.Allocator) Accesses;
871     AAPointerInfo::Access Acc(&I, RemoteI ? RemoteI : &I, Content, Kind, Ty);
872     // Check if we have an access for this instruction in this bin, if not,
873     // simply add it.
874     auto It = Bin->find(Acc);
875     if (It == Bin->find_end()) {
876       Bin->insert(Acc);
877       return ChangeStatus::CHANGED;
878     }
879     // If the existing access is the same as then new one, nothing changed.
880     AAPointerInfo::Access &Current = Bin->get(It);
881     AAPointerInfo::Access Before = Current;
882     // The new one will be combined with the existing one.
883     Current &= Acc;
884     return Current == Before ? ChangeStatus::UNCHANGED : ChangeStatus::CHANGED;
885   }
886 
887   /// See AAPointerInfo::forallInterferingAccesses.
888   bool forallInterferingAccesses(
889       AAPointerInfo::OffsetAndSize OAS,
890       function_ref<bool(const AAPointerInfo::Access &, bool)> CB) const {
891     if (!isValidState())
892       return false;
893 
894     for (auto &It : AccessBins) {
895       AAPointerInfo::OffsetAndSize ItOAS = It.getFirst();
896       if (!OAS.mayOverlap(ItOAS))
897         continue;
898       bool IsExact = OAS == ItOAS && !OAS.offsetOrSizeAreUnknown();
899       for (auto &Access : *It.getSecond())
900         if (!CB(Access, IsExact))
901           return false;
902     }
903     return true;
904   }
905 
906   /// See AAPointerInfo::forallInterferingAccesses.
907   bool forallInterferingAccesses(
908       Instruction &I,
909       function_ref<bool(const AAPointerInfo::Access &, bool)> CB) const {
910     if (!isValidState())
911       return false;
912 
913     // First find the offset and size of I.
914     AAPointerInfo::OffsetAndSize OAS(-1, -1);
915     for (auto &It : AccessBins) {
916       for (auto &Access : *It.getSecond()) {
917         if (Access.getRemoteInst() == &I) {
918           OAS = It.getFirst();
919           break;
920         }
921       }
922       if (OAS.getSize() != -1)
923         break;
924     }
925     // No access for I was found, we are done.
926     if (OAS.getSize() == -1)
927       return true;
928 
929     // Now that we have an offset and size, find all overlapping ones and use
930     // the callback on the accesses.
931     return forallInterferingAccesses(OAS, CB);
932   }
933 
934 private:
935   /// State to track fixpoint and validity.
936   BooleanState BS;
937 };
938 
939 namespace {
940 struct AAPointerInfoImpl
941     : public StateWrapper<AA::PointerInfo::State, AAPointerInfo> {
942   using BaseTy = StateWrapper<AA::PointerInfo::State, AAPointerInfo>;
943   AAPointerInfoImpl(const IRPosition &IRP, Attributor &A) : BaseTy(IRP) {}
944 
945   /// See AbstractAttribute::initialize(...).
946   void initialize(Attributor &A) override { AAPointerInfo::initialize(A); }
947 
948   /// See AbstractAttribute::getAsStr().
949   const std::string getAsStr() const override {
950     return std::string("PointerInfo ") +
951            (isValidState() ? (std::string("#") +
952                               std::to_string(AccessBins.size()) + " bins")
953                            : "<invalid>");
954   }
955 
956   /// See AbstractAttribute::manifest(...).
957   ChangeStatus manifest(Attributor &A) override {
958     return AAPointerInfo::manifest(A);
959   }
960 
961   bool forallInterferingAccesses(
962       OffsetAndSize OAS,
963       function_ref<bool(const AAPointerInfo::Access &, bool)> CB)
964       const override {
965     return State::forallInterferingAccesses(OAS, CB);
966   }
967   bool forallInterferingAccesses(
968       Attributor &A, const AbstractAttribute &QueryingAA, Instruction &I,
969       function_ref<bool(const Access &, bool)> UserCB) const override {
970     SmallPtrSet<const Access *, 8> DominatingWrites;
971     SmallVector<std::pair<const Access *, bool>, 8> InterferingAccesses;
972 
973     Function &Scope = *I.getFunction();
974     const auto &NoSyncAA = A.getAAFor<AANoSync>(
975         QueryingAA, IRPosition::function(Scope), DepClassTy::OPTIONAL);
976     const auto *ExecDomainAA = A.lookupAAFor<AAExecutionDomain>(
977         IRPosition::function(Scope), &QueryingAA, DepClassTy::OPTIONAL);
978     const bool NoSync = NoSyncAA.isAssumedNoSync();
979 
980     // Helper to determine if we need to consider threading, which we cannot
981     // right now. However, if the function is (assumed) nosync or the thread
982     // executing all instructions is the main thread only we can ignore
983     // threading.
984     auto CanIgnoreThreading = [&](const Instruction &I) -> bool {
985       if (NoSync)
986         return true;
987       if (ExecDomainAA && ExecDomainAA->isExecutedByInitialThreadOnly(I))
988         return true;
989       return false;
990     };
991 
992     // Helper to determine if the access is executed by the same thread as the
993     // load, for now it is sufficient to avoid any potential threading effects
994     // as we cannot deal with them anyway.
995     auto IsSameThreadAsLoad = [&](const Access &Acc) -> bool {
996       return CanIgnoreThreading(*Acc.getLocalInst());
997     };
998 
999     // TODO: Use inter-procedural reachability and dominance.
1000     const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
1001         QueryingAA, IRPosition::function(Scope), DepClassTy::OPTIONAL);
1002 
1003     const bool FindInterferingWrites = I.mayReadFromMemory();
1004     const bool FindInterferingReads = I.mayWriteToMemory();
1005     const bool UseDominanceReasoning = FindInterferingWrites;
1006     const bool CanUseCFGResoning = CanIgnoreThreading(I);
1007     InformationCache &InfoCache = A.getInfoCache();
1008     const DominatorTree *DT =
1009         NoRecurseAA.isKnownNoRecurse() && UseDominanceReasoning
1010             ? InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
1011                   Scope)
1012             : nullptr;
1013 
1014     enum GPUAddressSpace : unsigned {
1015       Generic = 0,
1016       Global = 1,
1017       Shared = 3,
1018       Constant = 4,
1019       Local = 5,
1020     };
1021 
1022     // Helper to check if a value has "kernel lifetime", that is it will not
1023     // outlive a GPU kernel. This is true for shared, constant, and local
1024     // globals on AMD and NVIDIA GPUs.
1025     auto HasKernelLifetime = [&](Value *V, Module &M) {
1026       Triple T(M.getTargetTriple());
1027       if (!(T.isAMDGPU() || T.isNVPTX()))
1028         return false;
1029       switch (V->getType()->getPointerAddressSpace()) {
1030       case GPUAddressSpace::Shared:
1031       case GPUAddressSpace::Constant:
1032       case GPUAddressSpace::Local:
1033         return true;
1034       default:
1035         return false;
1036       };
1037     };
1038 
1039     // The IsLiveInCalleeCB will be used by the AA::isPotentiallyReachable query
1040     // to determine if we should look at reachability from the callee. For
1041     // certain pointers we know the lifetime and we do not have to step into the
1042     // callee to determine reachability as the pointer would be dead in the
1043     // callee. See the conditional initialization below.
1044     std::function<bool(const Function &)> IsLiveInCalleeCB;
1045 
1046     if (auto *AI = dyn_cast<AllocaInst>(&getAssociatedValue())) {
1047       // If the alloca containing function is not recursive the alloca
1048       // must be dead in the callee.
1049       const Function *AIFn = AI->getFunction();
1050       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
1051           *this, IRPosition::function(*AIFn), DepClassTy::OPTIONAL);
1052       if (NoRecurseAA.isAssumedNoRecurse()) {
1053         IsLiveInCalleeCB = [AIFn](const Function &Fn) { return AIFn != &Fn; };
1054       }
1055     } else if (auto *GV = dyn_cast<GlobalValue>(&getAssociatedValue())) {
1056       // If the global has kernel lifetime we can stop if we reach a kernel
1057       // as it is "dead" in the (unknown) callees.
1058       if (HasKernelLifetime(GV, *GV->getParent()))
1059         IsLiveInCalleeCB = [](const Function &Fn) {
1060           return !Fn.hasFnAttribute("kernel");
1061         };
1062     }
1063 
1064     auto AccessCB = [&](const Access &Acc, bool Exact) {
1065       if ((!FindInterferingWrites || !Acc.isWrite()) &&
1066           (!FindInterferingReads || !Acc.isRead()))
1067         return true;
1068 
1069       // For now we only filter accesses based on CFG reasoning which does not
1070       // work yet if we have threading effects, or the access is complicated.
1071       if (CanUseCFGResoning) {
1072         if ((!Acc.isWrite() ||
1073              !AA::isPotentiallyReachable(A, *Acc.getLocalInst(), I, QueryingAA,
1074                                          IsLiveInCalleeCB)) &&
1075             (!Acc.isRead() ||
1076              !AA::isPotentiallyReachable(A, I, *Acc.getLocalInst(), QueryingAA,
1077                                          IsLiveInCalleeCB)))
1078           return true;
1079         if (DT && Exact && (Acc.getLocalInst()->getFunction() == &Scope) &&
1080             IsSameThreadAsLoad(Acc)) {
1081           if (DT->dominates(Acc.getLocalInst(), &I))
1082             DominatingWrites.insert(&Acc);
1083         }
1084       }
1085 
1086       InterferingAccesses.push_back({&Acc, Exact});
1087       return true;
1088     };
1089     if (!State::forallInterferingAccesses(I, AccessCB))
1090       return false;
1091 
1092     // If we cannot use CFG reasoning we only filter the non-write accesses
1093     // and are done here.
1094     if (!CanUseCFGResoning) {
1095       for (auto &It : InterferingAccesses)
1096         if (!UserCB(*It.first, It.second))
1097           return false;
1098       return true;
1099     }
1100 
1101     // Helper to determine if we can skip a specific write access. This is in
1102     // the worst case quadratic as we are looking for another write that will
1103     // hide the effect of this one.
1104     auto CanSkipAccess = [&](const Access &Acc, bool Exact) {
1105       if (!IsSameThreadAsLoad(Acc))
1106         return false;
1107       if (!DominatingWrites.count(&Acc))
1108         return false;
1109       for (const Access *DomAcc : DominatingWrites) {
1110         assert(Acc.getLocalInst()->getFunction() ==
1111                    DomAcc->getLocalInst()->getFunction() &&
1112                "Expected dominating writes to be in the same function!");
1113 
1114         if (DomAcc != &Acc &&
1115             DT->dominates(Acc.getLocalInst(), DomAcc->getLocalInst())) {
1116           return true;
1117         }
1118       }
1119       return false;
1120     };
1121 
1122     // Run the user callback on all accesses we cannot skip and return if that
1123     // succeeded for all or not.
1124     unsigned NumInterferingAccesses = InterferingAccesses.size();
1125     for (auto &It : InterferingAccesses) {
1126       if (!DT || NumInterferingAccesses > MaxInterferingAccesses ||
1127           !CanSkipAccess(*It.first, It.second)) {
1128         if (!UserCB(*It.first, It.second))
1129           return false;
1130       }
1131     }
1132     return true;
1133   }
1134 
1135   ChangeStatus translateAndAddState(Attributor &A, const AAPointerInfo &OtherAA,
1136                                     int64_t Offset, CallBase &CB,
1137                                     bool FromCallee = false) {
1138     using namespace AA::PointerInfo;
1139     if (!OtherAA.getState().isValidState() || !isValidState())
1140       return indicatePessimisticFixpoint();
1141 
1142     const auto &OtherAAImpl = static_cast<const AAPointerInfoImpl &>(OtherAA);
1143     bool IsByval =
1144         FromCallee && OtherAAImpl.getAssociatedArgument()->hasByValAttr();
1145 
1146     // Combine the accesses bin by bin.
1147     ChangeStatus Changed = ChangeStatus::UNCHANGED;
1148     for (auto &It : OtherAAImpl.getState()) {
1149       OffsetAndSize OAS = OffsetAndSize::getUnknown();
1150       if (Offset != OffsetAndSize::Unknown)
1151         OAS = OffsetAndSize(It.first.getOffset() + Offset, It.first.getSize());
1152       Accesses *Bin = AccessBins.lookup(OAS);
1153       for (const AAPointerInfo::Access &RAcc : *It.second) {
1154         if (IsByval && !RAcc.isRead())
1155           continue;
1156         bool UsedAssumedInformation = false;
1157         AccessKind AK = RAcc.getKind();
1158         Optional<Value *> Content = RAcc.getContent();
1159         if (FromCallee) {
1160           Content = A.translateArgumentToCallSiteContent(
1161               RAcc.getContent(), CB, *this, UsedAssumedInformation);
1162           AK = AccessKind(
1163               AK & (IsByval ? AccessKind::AK_READ : AccessKind::AK_READ_WRITE));
1164         }
1165         Changed =
1166             Changed | addAccess(A, OAS.getOffset(), OAS.getSize(), CB, Content,
1167                                 AK, RAcc.getType(), RAcc.getRemoteInst(), Bin);
1168       }
1169     }
1170     return Changed;
1171   }
1172 
1173   /// Statistic tracking for all AAPointerInfo implementations.
1174   /// See AbstractAttribute::trackStatistics().
1175   void trackPointerInfoStatistics(const IRPosition &IRP) const {}
1176 
1177   /// Dump the state into \p O.
1178   void dumpState(raw_ostream &O) {
1179     for (auto &It : AccessBins) {
1180       O << "[" << It.first.getOffset() << "-"
1181         << It.first.getOffset() + It.first.getSize()
1182         << "] : " << It.getSecond()->size() << "\n";
1183       for (auto &Acc : *It.getSecond()) {
1184         O << "     - " << Acc.getKind() << " - " << *Acc.getLocalInst() << "\n";
1185         if (Acc.getLocalInst() != Acc.getRemoteInst())
1186           O << "     -->                         " << *Acc.getRemoteInst()
1187             << "\n";
1188         if (!Acc.isWrittenValueYetUndetermined()) {
1189           if (Acc.getWrittenValue())
1190             O << "       - c: " << *Acc.getWrittenValue() << "\n";
1191           else
1192             O << "       - c: <unknown>\n";
1193         }
1194       }
1195     }
1196   }
1197 };
1198 
1199 struct AAPointerInfoFloating : public AAPointerInfoImpl {
1200   using AccessKind = AAPointerInfo::AccessKind;
1201   AAPointerInfoFloating(const IRPosition &IRP, Attributor &A)
1202       : AAPointerInfoImpl(IRP, A) {}
1203 
1204   /// See AbstractAttribute::initialize(...).
1205   void initialize(Attributor &A) override { AAPointerInfoImpl::initialize(A); }
1206 
1207   /// Deal with an access and signal if it was handled successfully.
1208   bool handleAccess(Attributor &A, Instruction &I, Value &Ptr,
1209                     Optional<Value *> Content, AccessKind Kind, int64_t Offset,
1210                     ChangeStatus &Changed, Type *Ty,
1211                     int64_t Size = OffsetAndSize::Unknown) {
1212     using namespace AA::PointerInfo;
1213     // No need to find a size if one is given or the offset is unknown.
1214     if (Offset != OffsetAndSize::Unknown && Size == OffsetAndSize::Unknown &&
1215         Ty) {
1216       const DataLayout &DL = A.getDataLayout();
1217       TypeSize AccessSize = DL.getTypeStoreSize(Ty);
1218       if (!AccessSize.isScalable())
1219         Size = AccessSize.getFixedSize();
1220     }
1221     Changed = Changed | addAccess(A, Offset, Size, I, Content, Kind, Ty);
1222     return true;
1223   };
1224 
1225   /// Helper struct, will support ranges eventually.
1226   struct OffsetInfo {
1227     int64_t Offset = OffsetAndSize::Unknown;
1228 
1229     bool operator==(const OffsetInfo &OI) const { return Offset == OI.Offset; }
1230   };
1231 
1232   /// See AbstractAttribute::updateImpl(...).
1233   ChangeStatus updateImpl(Attributor &A) override {
1234     using namespace AA::PointerInfo;
1235     ChangeStatus Changed = ChangeStatus::UNCHANGED;
1236     Value &AssociatedValue = getAssociatedValue();
1237 
1238     const DataLayout &DL = A.getDataLayout();
1239     DenseMap<Value *, OffsetInfo> OffsetInfoMap;
1240     OffsetInfoMap[&AssociatedValue] = OffsetInfo{0};
1241 
1242     auto HandlePassthroughUser = [&](Value *Usr, OffsetInfo PtrOI,
1243                                      bool &Follow) {
1244       OffsetInfo &UsrOI = OffsetInfoMap[Usr];
1245       UsrOI = PtrOI;
1246       Follow = true;
1247       return true;
1248     };
1249 
1250     const auto *TLI = getAnchorScope()
1251                           ? A.getInfoCache().getTargetLibraryInfoForFunction(
1252                                 *getAnchorScope())
1253                           : nullptr;
1254     auto UsePred = [&](const Use &U, bool &Follow) -> bool {
1255       Value *CurPtr = U.get();
1256       User *Usr = U.getUser();
1257       LLVM_DEBUG(dbgs() << "[AAPointerInfo] Analyze " << *CurPtr << " in "
1258                         << *Usr << "\n");
1259       assert(OffsetInfoMap.count(CurPtr) &&
1260              "The current pointer offset should have been seeded!");
1261 
1262       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Usr)) {
1263         if (CE->isCast())
1264           return HandlePassthroughUser(Usr, OffsetInfoMap[CurPtr], Follow);
1265         if (CE->isCompare())
1266           return true;
1267         if (!isa<GEPOperator>(CE)) {
1268           LLVM_DEBUG(dbgs() << "[AAPointerInfo] Unhandled constant user " << *CE
1269                             << "\n");
1270           return false;
1271         }
1272       }
1273       if (auto *GEP = dyn_cast<GEPOperator>(Usr)) {
1274         // Note the order here, the Usr access might change the map, CurPtr is
1275         // already in it though.
1276         OffsetInfo &UsrOI = OffsetInfoMap[Usr];
1277         OffsetInfo &PtrOI = OffsetInfoMap[CurPtr];
1278         UsrOI = PtrOI;
1279 
1280         // TODO: Use range information.
1281         if (PtrOI.Offset == OffsetAndSize::Unknown ||
1282             !GEP->hasAllConstantIndices()) {
1283           UsrOI.Offset = OffsetAndSize::Unknown;
1284           Follow = true;
1285           return true;
1286         }
1287 
1288         SmallVector<Value *, 8> Indices;
1289         for (Use &Idx : GEP->indices()) {
1290           if (auto *CIdx = dyn_cast<ConstantInt>(Idx)) {
1291             Indices.push_back(CIdx);
1292             continue;
1293           }
1294 
1295           LLVM_DEBUG(dbgs() << "[AAPointerInfo] Non constant GEP index " << *GEP
1296                             << " : " << *Idx << "\n");
1297           return false;
1298         }
1299         UsrOI.Offset = PtrOI.Offset + DL.getIndexedOffsetInType(
1300                                           GEP->getSourceElementType(), Indices);
1301         Follow = true;
1302         return true;
1303       }
1304       if (isa<CastInst>(Usr) || isa<SelectInst>(Usr) || isa<ReturnInst>(Usr))
1305         return HandlePassthroughUser(Usr, OffsetInfoMap[CurPtr], Follow);
1306 
1307       // For PHIs we need to take care of the recurrence explicitly as the value
1308       // might change while we iterate through a loop. For now, we give up if
1309       // the PHI is not invariant.
1310       if (isa<PHINode>(Usr)) {
1311         // Note the order here, the Usr access might change the map, CurPtr is
1312         // already in it though.
1313         bool IsFirstPHIUser = !OffsetInfoMap.count(Usr);
1314         OffsetInfo &UsrOI = OffsetInfoMap[Usr];
1315         OffsetInfo &PtrOI = OffsetInfoMap[CurPtr];
1316         // Check if the PHI is invariant (so far).
1317         if (UsrOI == PtrOI)
1318           return true;
1319 
1320         // Check if the PHI operand has already an unknown offset as we can't
1321         // improve on that anymore.
1322         if (PtrOI.Offset == OffsetAndSize::Unknown) {
1323           UsrOI = PtrOI;
1324           Follow = true;
1325           return true;
1326         }
1327 
1328         // Check if the PHI operand is not dependent on the PHI itself.
1329         APInt Offset(
1330             DL.getIndexSizeInBits(CurPtr->getType()->getPointerAddressSpace()),
1331             0);
1332         Value *CurPtrBase = CurPtr->stripAndAccumulateConstantOffsets(
1333             DL, Offset, /* AllowNonInbounds */ true);
1334         auto It = OffsetInfoMap.find(CurPtrBase);
1335         if (It != OffsetInfoMap.end()) {
1336           Offset += It->getSecond().Offset;
1337           if (IsFirstPHIUser || Offset == UsrOI.Offset)
1338             return HandlePassthroughUser(Usr, PtrOI, Follow);
1339           LLVM_DEBUG(dbgs()
1340                      << "[AAPointerInfo] PHI operand pointer offset mismatch "
1341                      << *CurPtr << " in " << *Usr << "\n");
1342         } else {
1343           LLVM_DEBUG(dbgs() << "[AAPointerInfo] PHI operand is too complex "
1344                             << *CurPtr << " in " << *Usr << "\n");
1345         }
1346 
1347         // TODO: Approximate in case we know the direction of the recurrence.
1348         UsrOI = PtrOI;
1349         UsrOI.Offset = OffsetAndSize::Unknown;
1350         Follow = true;
1351         return true;
1352       }
1353 
1354       if (auto *LoadI = dyn_cast<LoadInst>(Usr))
1355         return handleAccess(A, *LoadI, *CurPtr, /* Content */ nullptr,
1356                             AccessKind::AK_READ, OffsetInfoMap[CurPtr].Offset,
1357                             Changed, LoadI->getType());
1358       if (auto *StoreI = dyn_cast<StoreInst>(Usr)) {
1359         if (StoreI->getValueOperand() == CurPtr) {
1360           LLVM_DEBUG(dbgs() << "[AAPointerInfo] Escaping use in store "
1361                             << *StoreI << "\n");
1362           return false;
1363         }
1364         bool UsedAssumedInformation = false;
1365         Optional<Value *> Content =
1366             A.getAssumedSimplified(*StoreI->getValueOperand(), *this,
1367                                    UsedAssumedInformation, AA::Interprocedural);
1368         return handleAccess(A, *StoreI, *CurPtr, Content, AccessKind::AK_WRITE,
1369                             OffsetInfoMap[CurPtr].Offset, Changed,
1370                             StoreI->getValueOperand()->getType());
1371       }
1372       if (auto *CB = dyn_cast<CallBase>(Usr)) {
1373         if (CB->isLifetimeStartOrEnd())
1374           return true;
1375         if (TLI && isFreeCall(CB, TLI))
1376           return true;
1377         if (CB->isArgOperand(&U)) {
1378           unsigned ArgNo = CB->getArgOperandNo(&U);
1379           const auto &CSArgPI = A.getAAFor<AAPointerInfo>(
1380               *this, IRPosition::callsite_argument(*CB, ArgNo),
1381               DepClassTy::REQUIRED);
1382           Changed = translateAndAddState(A, CSArgPI,
1383                                          OffsetInfoMap[CurPtr].Offset, *CB) |
1384                     Changed;
1385           return isValidState();
1386         }
1387         LLVM_DEBUG(dbgs() << "[AAPointerInfo] Call user not handled " << *CB
1388                           << "\n");
1389         // TODO: Allow some call uses
1390         return false;
1391       }
1392 
1393       LLVM_DEBUG(dbgs() << "[AAPointerInfo] User not handled " << *Usr << "\n");
1394       return false;
1395     };
1396     auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
1397       if (OffsetInfoMap.count(NewU)) {
1398         LLVM_DEBUG({
1399           if (!(OffsetInfoMap[NewU] == OffsetInfoMap[OldU])) {
1400             dbgs() << "[AAPointerInfo] Equivalent use callback failed: "
1401                    << OffsetInfoMap[NewU].Offset << " vs "
1402                    << OffsetInfoMap[OldU].Offset << "\n";
1403           }
1404         });
1405         return OffsetInfoMap[NewU] == OffsetInfoMap[OldU];
1406       }
1407       OffsetInfoMap[NewU] = OffsetInfoMap[OldU];
1408       return true;
1409     };
1410     if (!A.checkForAllUses(UsePred, *this, AssociatedValue,
1411                            /* CheckBBLivenessOnly */ true, DepClassTy::OPTIONAL,
1412                            /* IgnoreDroppableUses */ true, EquivalentUseCB)) {
1413       LLVM_DEBUG(
1414           dbgs() << "[AAPointerInfo] Check for all uses failed, abort!\n");
1415       return indicatePessimisticFixpoint();
1416     }
1417 
1418     LLVM_DEBUG({
1419       dbgs() << "Accesses by bin after update:\n";
1420       dumpState(dbgs());
1421     });
1422 
1423     return Changed;
1424   }
1425 
1426   /// See AbstractAttribute::trackStatistics()
1427   void trackStatistics() const override {
1428     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1429   }
1430 };
1431 
1432 struct AAPointerInfoReturned final : AAPointerInfoImpl {
1433   AAPointerInfoReturned(const IRPosition &IRP, Attributor &A)
1434       : AAPointerInfoImpl(IRP, A) {}
1435 
1436   /// See AbstractAttribute::updateImpl(...).
1437   ChangeStatus updateImpl(Attributor &A) override {
1438     return indicatePessimisticFixpoint();
1439   }
1440 
1441   /// See AbstractAttribute::trackStatistics()
1442   void trackStatistics() const override {
1443     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1444   }
1445 };
1446 
1447 struct AAPointerInfoArgument final : AAPointerInfoFloating {
1448   AAPointerInfoArgument(const IRPosition &IRP, Attributor &A)
1449       : AAPointerInfoFloating(IRP, A) {}
1450 
1451   /// See AbstractAttribute::initialize(...).
1452   void initialize(Attributor &A) override {
1453     AAPointerInfoFloating::initialize(A);
1454     if (getAnchorScope()->isDeclaration())
1455       indicatePessimisticFixpoint();
1456   }
1457 
1458   /// See AbstractAttribute::trackStatistics()
1459   void trackStatistics() const override {
1460     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1461   }
1462 };
1463 
1464 struct AAPointerInfoCallSiteArgument final : AAPointerInfoFloating {
1465   AAPointerInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
1466       : AAPointerInfoFloating(IRP, A) {}
1467 
1468   /// See AbstractAttribute::updateImpl(...).
1469   ChangeStatus updateImpl(Attributor &A) override {
1470     using namespace AA::PointerInfo;
1471     // We handle memory intrinsics explicitly, at least the first (=
1472     // destination) and second (=source) arguments as we know how they are
1473     // accessed.
1474     if (auto *MI = dyn_cast_or_null<MemIntrinsic>(getCtxI())) {
1475       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1476       int64_t LengthVal = OffsetAndSize::Unknown;
1477       if (Length)
1478         LengthVal = Length->getSExtValue();
1479       Value &Ptr = getAssociatedValue();
1480       unsigned ArgNo = getIRPosition().getCallSiteArgNo();
1481       ChangeStatus Changed = ChangeStatus::UNCHANGED;
1482       if (ArgNo == 0) {
1483         handleAccess(A, *MI, Ptr, nullptr, AccessKind::AK_WRITE, 0, Changed,
1484                      nullptr, LengthVal);
1485       } else if (ArgNo == 1) {
1486         handleAccess(A, *MI, Ptr, nullptr, AccessKind::AK_READ, 0, Changed,
1487                      nullptr, LengthVal);
1488       } else {
1489         LLVM_DEBUG(dbgs() << "[AAPointerInfo] Unhandled memory intrinsic "
1490                           << *MI << "\n");
1491         return indicatePessimisticFixpoint();
1492       }
1493 
1494       LLVM_DEBUG({
1495         dbgs() << "Accesses by bin after update:\n";
1496         dumpState(dbgs());
1497       });
1498 
1499       return Changed;
1500     }
1501 
1502     // TODO: Once we have call site specific value information we can provide
1503     //       call site specific liveness information and then it makes
1504     //       sense to specialize attributes for call sites arguments instead of
1505     //       redirecting requests to the callee argument.
1506     Argument *Arg = getAssociatedArgument();
1507     if (!Arg)
1508       return indicatePessimisticFixpoint();
1509     const IRPosition &ArgPos = IRPosition::argument(*Arg);
1510     auto &ArgAA =
1511         A.getAAFor<AAPointerInfo>(*this, ArgPos, DepClassTy::REQUIRED);
1512     return translateAndAddState(A, ArgAA, 0, *cast<CallBase>(getCtxI()),
1513                                 /* FromCallee */ true);
1514   }
1515 
1516   /// See AbstractAttribute::trackStatistics()
1517   void trackStatistics() const override {
1518     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1519   }
1520 };
1521 
1522 struct AAPointerInfoCallSiteReturned final : AAPointerInfoFloating {
1523   AAPointerInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
1524       : AAPointerInfoFloating(IRP, A) {}
1525 
1526   /// See AbstractAttribute::trackStatistics()
1527   void trackStatistics() const override {
1528     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1529   }
1530 };
1531 } // namespace
1532 
1533 /// -----------------------NoUnwind Function Attribute--------------------------
1534 
1535 namespace {
1536 struct AANoUnwindImpl : AANoUnwind {
1537   AANoUnwindImpl(const IRPosition &IRP, Attributor &A) : AANoUnwind(IRP, A) {}
1538 
1539   const std::string getAsStr() const override {
1540     return getAssumed() ? "nounwind" : "may-unwind";
1541   }
1542 
1543   /// See AbstractAttribute::updateImpl(...).
1544   ChangeStatus updateImpl(Attributor &A) override {
1545     auto Opcodes = {
1546         (unsigned)Instruction::Invoke,      (unsigned)Instruction::CallBr,
1547         (unsigned)Instruction::Call,        (unsigned)Instruction::CleanupRet,
1548         (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
1549 
1550     auto CheckForNoUnwind = [&](Instruction &I) {
1551       if (!I.mayThrow())
1552         return true;
1553 
1554       if (const auto *CB = dyn_cast<CallBase>(&I)) {
1555         const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(
1556             *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED);
1557         return NoUnwindAA.isAssumedNoUnwind();
1558       }
1559       return false;
1560     };
1561 
1562     bool UsedAssumedInformation = false;
1563     if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes,
1564                                    UsedAssumedInformation))
1565       return indicatePessimisticFixpoint();
1566 
1567     return ChangeStatus::UNCHANGED;
1568   }
1569 };
1570 
1571 struct AANoUnwindFunction final : public AANoUnwindImpl {
1572   AANoUnwindFunction(const IRPosition &IRP, Attributor &A)
1573       : AANoUnwindImpl(IRP, A) {}
1574 
1575   /// See AbstractAttribute::trackStatistics()
1576   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
1577 };
1578 
1579 /// NoUnwind attribute deduction for a call sites.
1580 struct AANoUnwindCallSite final : AANoUnwindImpl {
1581   AANoUnwindCallSite(const IRPosition &IRP, Attributor &A)
1582       : AANoUnwindImpl(IRP, A) {}
1583 
1584   /// See AbstractAttribute::initialize(...).
1585   void initialize(Attributor &A) override {
1586     AANoUnwindImpl::initialize(A);
1587     Function *F = getAssociatedFunction();
1588     if (!F || F->isDeclaration())
1589       indicatePessimisticFixpoint();
1590   }
1591 
1592   /// See AbstractAttribute::updateImpl(...).
1593   ChangeStatus updateImpl(Attributor &A) override {
1594     // TODO: Once we have call site specific value information we can provide
1595     //       call site specific liveness information and then it makes
1596     //       sense to specialize attributes for call sites arguments instead of
1597     //       redirecting requests to the callee argument.
1598     Function *F = getAssociatedFunction();
1599     const IRPosition &FnPos = IRPosition::function(*F);
1600     auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos, DepClassTy::REQUIRED);
1601     return clampStateAndIndicateChange(getState(), FnAA.getState());
1602   }
1603 
1604   /// See AbstractAttribute::trackStatistics()
1605   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); }
1606 };
1607 } // namespace
1608 
1609 /// --------------------- Function Return Values -------------------------------
1610 
1611 namespace {
1612 /// "Attribute" that collects all potential returned values and the return
1613 /// instructions that they arise from.
1614 ///
1615 /// If there is a unique returned value R, the manifest method will:
1616 ///   - mark R with the "returned" attribute, if R is an argument.
1617 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState {
1618 
1619   /// Mapping of values potentially returned by the associated function to the
1620   /// return instructions that might return them.
1621   MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues;
1622 
1623   /// State flags
1624   ///
1625   ///{
1626   bool IsFixed = false;
1627   bool IsValidState = true;
1628   ///}
1629 
1630 public:
1631   AAReturnedValuesImpl(const IRPosition &IRP, Attributor &A)
1632       : AAReturnedValues(IRP, A) {}
1633 
1634   /// See AbstractAttribute::initialize(...).
1635   void initialize(Attributor &A) override {
1636     // Reset the state.
1637     IsFixed = false;
1638     IsValidState = true;
1639     ReturnedValues.clear();
1640 
1641     Function *F = getAssociatedFunction();
1642     if (!F || F->isDeclaration()) {
1643       indicatePessimisticFixpoint();
1644       return;
1645     }
1646     assert(!F->getReturnType()->isVoidTy() &&
1647            "Did not expect a void return type!");
1648 
1649     // The map from instruction opcodes to those instructions in the function.
1650     auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F);
1651 
1652     // Look through all arguments, if one is marked as returned we are done.
1653     for (Argument &Arg : F->args()) {
1654       if (Arg.hasReturnedAttr()) {
1655         auto &ReturnInstSet = ReturnedValues[&Arg];
1656         if (auto *Insts = OpcodeInstMap.lookup(Instruction::Ret))
1657           for (Instruction *RI : *Insts)
1658             ReturnInstSet.insert(cast<ReturnInst>(RI));
1659 
1660         indicateOptimisticFixpoint();
1661         return;
1662       }
1663     }
1664 
1665     if (!A.isFunctionIPOAmendable(*F))
1666       indicatePessimisticFixpoint();
1667   }
1668 
1669   /// See AbstractAttribute::manifest(...).
1670   ChangeStatus manifest(Attributor &A) override;
1671 
1672   /// See AbstractAttribute::getState(...).
1673   AbstractState &getState() override { return *this; }
1674 
1675   /// See AbstractAttribute::getState(...).
1676   const AbstractState &getState() const override { return *this; }
1677 
1678   /// See AbstractAttribute::updateImpl(Attributor &A).
1679   ChangeStatus updateImpl(Attributor &A) override;
1680 
1681   llvm::iterator_range<iterator> returned_values() override {
1682     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
1683   }
1684 
1685   llvm::iterator_range<const_iterator> returned_values() const override {
1686     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
1687   }
1688 
1689   /// Return the number of potential return values, -1 if unknown.
1690   size_t getNumReturnValues() const override {
1691     return isValidState() ? ReturnedValues.size() : -1;
1692   }
1693 
1694   /// Return an assumed unique return value if a single candidate is found. If
1695   /// there cannot be one, return a nullptr. If it is not clear yet, return the
1696   /// Optional::NoneType.
1697   Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const;
1698 
1699   /// See AbstractState::checkForAllReturnedValues(...).
1700   bool checkForAllReturnedValuesAndReturnInsts(
1701       function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
1702       const override;
1703 
1704   /// Pretty print the attribute similar to the IR representation.
1705   const std::string getAsStr() const override;
1706 
1707   /// See AbstractState::isAtFixpoint().
1708   bool isAtFixpoint() const override { return IsFixed; }
1709 
1710   /// See AbstractState::isValidState().
1711   bool isValidState() const override { return IsValidState; }
1712 
1713   /// See AbstractState::indicateOptimisticFixpoint(...).
1714   ChangeStatus indicateOptimisticFixpoint() override {
1715     IsFixed = true;
1716     return ChangeStatus::UNCHANGED;
1717   }
1718 
1719   ChangeStatus indicatePessimisticFixpoint() override {
1720     IsFixed = true;
1721     IsValidState = false;
1722     return ChangeStatus::CHANGED;
1723   }
1724 };
1725 
1726 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
1727   ChangeStatus Changed = ChangeStatus::UNCHANGED;
1728 
1729   // Bookkeeping.
1730   assert(isValidState());
1731   STATS_DECLTRACK(KnownReturnValues, FunctionReturn,
1732                   "Number of function with known return values");
1733 
1734   // Check if we have an assumed unique return value that we could manifest.
1735   Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
1736 
1737   if (!UniqueRV || !UniqueRV.value())
1738     return Changed;
1739 
1740   // Bookkeeping.
1741   STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
1742                   "Number of function with unique return");
1743   // If the assumed unique return value is an argument, annotate it.
1744   if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.value())) {
1745     if (UniqueRVArg->getType()->canLosslesslyBitCastTo(
1746             getAssociatedFunction()->getReturnType())) {
1747       getIRPosition() = IRPosition::argument(*UniqueRVArg);
1748       Changed = IRAttribute::manifest(A);
1749     }
1750   }
1751   return Changed;
1752 }
1753 
1754 const std::string AAReturnedValuesImpl::getAsStr() const {
1755   return (isAtFixpoint() ? "returns(#" : "may-return(#") +
1756          (isValidState() ? std::to_string(getNumReturnValues()) : "?") + ")";
1757 }
1758 
1759 Optional<Value *>
1760 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const {
1761   // If checkForAllReturnedValues provides a unique value, ignoring potential
1762   // undef values that can also be present, it is assumed to be the actual
1763   // return value and forwarded to the caller of this method. If there are
1764   // multiple, a nullptr is returned indicating there cannot be a unique
1765   // returned value.
1766   Optional<Value *> UniqueRV;
1767   Type *Ty = getAssociatedFunction()->getReturnType();
1768 
1769   auto Pred = [&](Value &RV) -> bool {
1770     UniqueRV = AA::combineOptionalValuesInAAValueLatice(UniqueRV, &RV, Ty);
1771     return UniqueRV != Optional<Value *>(nullptr);
1772   };
1773 
1774   if (!A.checkForAllReturnedValues(Pred, *this))
1775     UniqueRV = nullptr;
1776 
1777   return UniqueRV;
1778 }
1779 
1780 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
1781     function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
1782     const {
1783   if (!isValidState())
1784     return false;
1785 
1786   // Check all returned values but ignore call sites as long as we have not
1787   // encountered an overdefined one during an update.
1788   for (auto &It : ReturnedValues) {
1789     Value *RV = It.first;
1790     if (!Pred(*RV, It.second))
1791       return false;
1792   }
1793 
1794   return true;
1795 }
1796 
1797 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) {
1798   ChangeStatus Changed = ChangeStatus::UNCHANGED;
1799 
1800   SmallVector<AA::ValueAndContext> Values;
1801   bool UsedAssumedInformation = false;
1802   auto ReturnInstCB = [&](Instruction &I) {
1803     ReturnInst &Ret = cast<ReturnInst>(I);
1804     Values.clear();
1805     if (!A.getAssumedSimplifiedValues(IRPosition::value(*Ret.getReturnValue()),
1806                                       *this, Values, AA::Intraprocedural,
1807                                       UsedAssumedInformation))
1808       Values.push_back({*Ret.getReturnValue(), Ret});
1809 
1810     for (auto &VAC : Values) {
1811       assert(AA::isValidInScope(*VAC.getValue(), Ret.getFunction()) &&
1812              "Assumed returned value should be valid in function scope!");
1813       if (ReturnedValues[VAC.getValue()].insert(&Ret))
1814         Changed = ChangeStatus::CHANGED;
1815     }
1816     return true;
1817   };
1818 
1819   // Discover returned values from all live returned instructions in the
1820   // associated function.
1821   if (!A.checkForAllInstructions(ReturnInstCB, *this, {Instruction::Ret},
1822                                  UsedAssumedInformation))
1823     return indicatePessimisticFixpoint();
1824   return Changed;
1825 }
1826 
1827 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl {
1828   AAReturnedValuesFunction(const IRPosition &IRP, Attributor &A)
1829       : AAReturnedValuesImpl(IRP, A) {}
1830 
1831   /// See AbstractAttribute::trackStatistics()
1832   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) }
1833 };
1834 
1835 /// Returned values information for a call sites.
1836 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl {
1837   AAReturnedValuesCallSite(const IRPosition &IRP, Attributor &A)
1838       : AAReturnedValuesImpl(IRP, A) {}
1839 
1840   /// See AbstractAttribute::initialize(...).
1841   void initialize(Attributor &A) override {
1842     // TODO: Once we have call site specific value information we can provide
1843     //       call site specific liveness information and then it makes
1844     //       sense to specialize attributes for call sites instead of
1845     //       redirecting requests to the callee.
1846     llvm_unreachable("Abstract attributes for returned values are not "
1847                      "supported for call sites yet!");
1848   }
1849 
1850   /// See AbstractAttribute::updateImpl(...).
1851   ChangeStatus updateImpl(Attributor &A) override {
1852     return indicatePessimisticFixpoint();
1853   }
1854 
1855   /// See AbstractAttribute::trackStatistics()
1856   void trackStatistics() const override {}
1857 };
1858 } // namespace
1859 
1860 /// ------------------------ NoSync Function Attribute -------------------------
1861 
1862 bool AANoSync::isNonRelaxedAtomic(const Instruction *I) {
1863   if (!I->isAtomic())
1864     return false;
1865 
1866   if (auto *FI = dyn_cast<FenceInst>(I))
1867     // All legal orderings for fence are stronger than monotonic.
1868     return FI->getSyncScopeID() != SyncScope::SingleThread;
1869   if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) {
1870     // Unordered is not a legal ordering for cmpxchg.
1871     return (AI->getSuccessOrdering() != AtomicOrdering::Monotonic ||
1872             AI->getFailureOrdering() != AtomicOrdering::Monotonic);
1873   }
1874 
1875   AtomicOrdering Ordering;
1876   switch (I->getOpcode()) {
1877   case Instruction::AtomicRMW:
1878     Ordering = cast<AtomicRMWInst>(I)->getOrdering();
1879     break;
1880   case Instruction::Store:
1881     Ordering = cast<StoreInst>(I)->getOrdering();
1882     break;
1883   case Instruction::Load:
1884     Ordering = cast<LoadInst>(I)->getOrdering();
1885     break;
1886   default:
1887     llvm_unreachable(
1888         "New atomic operations need to be known in the attributor.");
1889   }
1890 
1891   return (Ordering != AtomicOrdering::Unordered &&
1892           Ordering != AtomicOrdering::Monotonic);
1893 }
1894 
1895 /// Return true if this intrinsic is nosync.  This is only used for intrinsics
1896 /// which would be nosync except that they have a volatile flag.  All other
1897 /// intrinsics are simply annotated with the nosync attribute in Intrinsics.td.
1898 bool AANoSync::isNoSyncIntrinsic(const Instruction *I) {
1899   if (auto *MI = dyn_cast<MemIntrinsic>(I))
1900     return !MI->isVolatile();
1901   return false;
1902 }
1903 
1904 namespace {
1905 struct AANoSyncImpl : AANoSync {
1906   AANoSyncImpl(const IRPosition &IRP, Attributor &A) : AANoSync(IRP, A) {}
1907 
1908   const std::string getAsStr() const override {
1909     return getAssumed() ? "nosync" : "may-sync";
1910   }
1911 
1912   /// See AbstractAttribute::updateImpl(...).
1913   ChangeStatus updateImpl(Attributor &A) override;
1914 };
1915 
1916 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
1917 
1918   auto CheckRWInstForNoSync = [&](Instruction &I) {
1919     return AA::isNoSyncInst(A, I, *this);
1920   };
1921 
1922   auto CheckForNoSync = [&](Instruction &I) {
1923     // At this point we handled all read/write effects and they are all
1924     // nosync, so they can be skipped.
1925     if (I.mayReadOrWriteMemory())
1926       return true;
1927 
1928     // non-convergent and readnone imply nosync.
1929     return !cast<CallBase>(I).isConvergent();
1930   };
1931 
1932   bool UsedAssumedInformation = false;
1933   if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this,
1934                                           UsedAssumedInformation) ||
1935       !A.checkForAllCallLikeInstructions(CheckForNoSync, *this,
1936                                          UsedAssumedInformation))
1937     return indicatePessimisticFixpoint();
1938 
1939   return ChangeStatus::UNCHANGED;
1940 }
1941 
1942 struct AANoSyncFunction final : public AANoSyncImpl {
1943   AANoSyncFunction(const IRPosition &IRP, Attributor &A)
1944       : AANoSyncImpl(IRP, A) {}
1945 
1946   /// See AbstractAttribute::trackStatistics()
1947   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
1948 };
1949 
1950 /// NoSync attribute deduction for a call sites.
1951 struct AANoSyncCallSite final : AANoSyncImpl {
1952   AANoSyncCallSite(const IRPosition &IRP, Attributor &A)
1953       : AANoSyncImpl(IRP, A) {}
1954 
1955   /// See AbstractAttribute::initialize(...).
1956   void initialize(Attributor &A) override {
1957     AANoSyncImpl::initialize(A);
1958     Function *F = getAssociatedFunction();
1959     if (!F || F->isDeclaration())
1960       indicatePessimisticFixpoint();
1961   }
1962 
1963   /// See AbstractAttribute::updateImpl(...).
1964   ChangeStatus updateImpl(Attributor &A) override {
1965     // TODO: Once we have call site specific value information we can provide
1966     //       call site specific liveness information and then it makes
1967     //       sense to specialize attributes for call sites arguments instead of
1968     //       redirecting requests to the callee argument.
1969     Function *F = getAssociatedFunction();
1970     const IRPosition &FnPos = IRPosition::function(*F);
1971     auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos, DepClassTy::REQUIRED);
1972     return clampStateAndIndicateChange(getState(), FnAA.getState());
1973   }
1974 
1975   /// See AbstractAttribute::trackStatistics()
1976   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); }
1977 };
1978 } // namespace
1979 
1980 /// ------------------------ No-Free Attributes ----------------------------
1981 
1982 namespace {
1983 struct AANoFreeImpl : public AANoFree {
1984   AANoFreeImpl(const IRPosition &IRP, Attributor &A) : AANoFree(IRP, A) {}
1985 
1986   /// See AbstractAttribute::updateImpl(...).
1987   ChangeStatus updateImpl(Attributor &A) override {
1988     auto CheckForNoFree = [&](Instruction &I) {
1989       const auto &CB = cast<CallBase>(I);
1990       if (CB.hasFnAttr(Attribute::NoFree))
1991         return true;
1992 
1993       const auto &NoFreeAA = A.getAAFor<AANoFree>(
1994           *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
1995       return NoFreeAA.isAssumedNoFree();
1996     };
1997 
1998     bool UsedAssumedInformation = false;
1999     if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this,
2000                                            UsedAssumedInformation))
2001       return indicatePessimisticFixpoint();
2002     return ChangeStatus::UNCHANGED;
2003   }
2004 
2005   /// See AbstractAttribute::getAsStr().
2006   const std::string getAsStr() const override {
2007     return getAssumed() ? "nofree" : "may-free";
2008   }
2009 };
2010 
2011 struct AANoFreeFunction final : public AANoFreeImpl {
2012   AANoFreeFunction(const IRPosition &IRP, Attributor &A)
2013       : AANoFreeImpl(IRP, A) {}
2014 
2015   /// See AbstractAttribute::trackStatistics()
2016   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
2017 };
2018 
2019 /// NoFree attribute deduction for a call sites.
2020 struct AANoFreeCallSite final : AANoFreeImpl {
2021   AANoFreeCallSite(const IRPosition &IRP, Attributor &A)
2022       : AANoFreeImpl(IRP, A) {}
2023 
2024   /// See AbstractAttribute::initialize(...).
2025   void initialize(Attributor &A) override {
2026     AANoFreeImpl::initialize(A);
2027     Function *F = getAssociatedFunction();
2028     if (!F || F->isDeclaration())
2029       indicatePessimisticFixpoint();
2030   }
2031 
2032   /// See AbstractAttribute::updateImpl(...).
2033   ChangeStatus updateImpl(Attributor &A) override {
2034     // TODO: Once we have call site specific value information we can provide
2035     //       call site specific liveness information and then it makes
2036     //       sense to specialize attributes for call sites arguments instead of
2037     //       redirecting requests to the callee argument.
2038     Function *F = getAssociatedFunction();
2039     const IRPosition &FnPos = IRPosition::function(*F);
2040     auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos, DepClassTy::REQUIRED);
2041     return clampStateAndIndicateChange(getState(), FnAA.getState());
2042   }
2043 
2044   /// See AbstractAttribute::trackStatistics()
2045   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); }
2046 };
2047 
2048 /// NoFree attribute for floating values.
2049 struct AANoFreeFloating : AANoFreeImpl {
2050   AANoFreeFloating(const IRPosition &IRP, Attributor &A)
2051       : AANoFreeImpl(IRP, A) {}
2052 
2053   /// See AbstractAttribute::trackStatistics()
2054   void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)}
2055 
2056   /// See Abstract Attribute::updateImpl(...).
2057   ChangeStatus updateImpl(Attributor &A) override {
2058     const IRPosition &IRP = getIRPosition();
2059 
2060     const auto &NoFreeAA = A.getAAFor<AANoFree>(
2061         *this, IRPosition::function_scope(IRP), DepClassTy::OPTIONAL);
2062     if (NoFreeAA.isAssumedNoFree())
2063       return ChangeStatus::UNCHANGED;
2064 
2065     Value &AssociatedValue = getIRPosition().getAssociatedValue();
2066     auto Pred = [&](const Use &U, bool &Follow) -> bool {
2067       Instruction *UserI = cast<Instruction>(U.getUser());
2068       if (auto *CB = dyn_cast<CallBase>(UserI)) {
2069         if (CB->isBundleOperand(&U))
2070           return false;
2071         if (!CB->isArgOperand(&U))
2072           return true;
2073         unsigned ArgNo = CB->getArgOperandNo(&U);
2074 
2075         const auto &NoFreeArg = A.getAAFor<AANoFree>(
2076             *this, IRPosition::callsite_argument(*CB, ArgNo),
2077             DepClassTy::REQUIRED);
2078         return NoFreeArg.isAssumedNoFree();
2079       }
2080 
2081       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
2082           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
2083         Follow = true;
2084         return true;
2085       }
2086       if (isa<StoreInst>(UserI) || isa<LoadInst>(UserI) ||
2087           isa<ReturnInst>(UserI))
2088         return true;
2089 
2090       // Unknown user.
2091       return false;
2092     };
2093     if (!A.checkForAllUses(Pred, *this, AssociatedValue))
2094       return indicatePessimisticFixpoint();
2095 
2096     return ChangeStatus::UNCHANGED;
2097   }
2098 };
2099 
2100 /// NoFree attribute for a call site argument.
2101 struct AANoFreeArgument final : AANoFreeFloating {
2102   AANoFreeArgument(const IRPosition &IRP, Attributor &A)
2103       : AANoFreeFloating(IRP, A) {}
2104 
2105   /// See AbstractAttribute::trackStatistics()
2106   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) }
2107 };
2108 
2109 /// NoFree attribute for call site arguments.
2110 struct AANoFreeCallSiteArgument final : AANoFreeFloating {
2111   AANoFreeCallSiteArgument(const IRPosition &IRP, Attributor &A)
2112       : AANoFreeFloating(IRP, A) {}
2113 
2114   /// See AbstractAttribute::updateImpl(...).
2115   ChangeStatus updateImpl(Attributor &A) override {
2116     // TODO: Once we have call site specific value information we can provide
2117     //       call site specific liveness information and then it makes
2118     //       sense to specialize attributes for call sites arguments instead of
2119     //       redirecting requests to the callee argument.
2120     Argument *Arg = getAssociatedArgument();
2121     if (!Arg)
2122       return indicatePessimisticFixpoint();
2123     const IRPosition &ArgPos = IRPosition::argument(*Arg);
2124     auto &ArgAA = A.getAAFor<AANoFree>(*this, ArgPos, DepClassTy::REQUIRED);
2125     return clampStateAndIndicateChange(getState(), ArgAA.getState());
2126   }
2127 
2128   /// See AbstractAttribute::trackStatistics()
2129   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nofree)};
2130 };
2131 
2132 /// NoFree attribute for function return value.
2133 struct AANoFreeReturned final : AANoFreeFloating {
2134   AANoFreeReturned(const IRPosition &IRP, Attributor &A)
2135       : AANoFreeFloating(IRP, A) {
2136     llvm_unreachable("NoFree is not applicable to function returns!");
2137   }
2138 
2139   /// See AbstractAttribute::initialize(...).
2140   void initialize(Attributor &A) override {
2141     llvm_unreachable("NoFree is not applicable to function returns!");
2142   }
2143 
2144   /// See AbstractAttribute::updateImpl(...).
2145   ChangeStatus updateImpl(Attributor &A) override {
2146     llvm_unreachable("NoFree is not applicable to function returns!");
2147   }
2148 
2149   /// See AbstractAttribute::trackStatistics()
2150   void trackStatistics() const override {}
2151 };
2152 
2153 /// NoFree attribute deduction for a call site return value.
2154 struct AANoFreeCallSiteReturned final : AANoFreeFloating {
2155   AANoFreeCallSiteReturned(const IRPosition &IRP, Attributor &A)
2156       : AANoFreeFloating(IRP, A) {}
2157 
2158   ChangeStatus manifest(Attributor &A) override {
2159     return ChangeStatus::UNCHANGED;
2160   }
2161   /// See AbstractAttribute::trackStatistics()
2162   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) }
2163 };
2164 } // namespace
2165 
2166 /// ------------------------ NonNull Argument Attribute ------------------------
2167 namespace {
2168 static int64_t getKnownNonNullAndDerefBytesForUse(
2169     Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue,
2170     const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) {
2171   TrackUse = false;
2172 
2173   const Value *UseV = U->get();
2174   if (!UseV->getType()->isPointerTy())
2175     return 0;
2176 
2177   // We need to follow common pointer manipulation uses to the accesses they
2178   // feed into. We can try to be smart to avoid looking through things we do not
2179   // like for now, e.g., non-inbounds GEPs.
2180   if (isa<CastInst>(I)) {
2181     TrackUse = true;
2182     return 0;
2183   }
2184 
2185   if (isa<GetElementPtrInst>(I)) {
2186     TrackUse = true;
2187     return 0;
2188   }
2189 
2190   Type *PtrTy = UseV->getType();
2191   const Function *F = I->getFunction();
2192   bool NullPointerIsDefined =
2193       F ? llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()) : true;
2194   const DataLayout &DL = A.getInfoCache().getDL();
2195   if (const auto *CB = dyn_cast<CallBase>(I)) {
2196     if (CB->isBundleOperand(U)) {
2197       if (RetainedKnowledge RK = getKnowledgeFromUse(
2198               U, {Attribute::NonNull, Attribute::Dereferenceable})) {
2199         IsNonNull |=
2200             (RK.AttrKind == Attribute::NonNull || !NullPointerIsDefined);
2201         return RK.ArgValue;
2202       }
2203       return 0;
2204     }
2205 
2206     if (CB->isCallee(U)) {
2207       IsNonNull |= !NullPointerIsDefined;
2208       return 0;
2209     }
2210 
2211     unsigned ArgNo = CB->getArgOperandNo(U);
2212     IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
2213     // As long as we only use known information there is no need to track
2214     // dependences here.
2215     auto &DerefAA =
2216         A.getAAFor<AADereferenceable>(QueryingAA, IRP, DepClassTy::NONE);
2217     IsNonNull |= DerefAA.isKnownNonNull();
2218     return DerefAA.getKnownDereferenceableBytes();
2219   }
2220 
2221   Optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
2222   if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() || I->isVolatile())
2223     return 0;
2224 
2225   int64_t Offset;
2226   const Value *Base =
2227       getMinimalBaseOfPointer(A, QueryingAA, Loc->Ptr, Offset, DL);
2228   if (Base && Base == &AssociatedValue) {
2229     int64_t DerefBytes = Loc->Size.getValue() + Offset;
2230     IsNonNull |= !NullPointerIsDefined;
2231     return std::max(int64_t(0), DerefBytes);
2232   }
2233 
2234   /// Corner case when an offset is 0.
2235   Base = GetPointerBaseWithConstantOffset(Loc->Ptr, Offset, DL,
2236                                           /*AllowNonInbounds*/ true);
2237   if (Base && Base == &AssociatedValue && Offset == 0) {
2238     int64_t DerefBytes = Loc->Size.getValue();
2239     IsNonNull |= !NullPointerIsDefined;
2240     return std::max(int64_t(0), DerefBytes);
2241   }
2242 
2243   return 0;
2244 }
2245 
2246 struct AANonNullImpl : AANonNull {
2247   AANonNullImpl(const IRPosition &IRP, Attributor &A)
2248       : AANonNull(IRP, A),
2249         NullIsDefined(NullPointerIsDefined(
2250             getAnchorScope(),
2251             getAssociatedValue().getType()->getPointerAddressSpace())) {}
2252 
2253   /// See AbstractAttribute::initialize(...).
2254   void initialize(Attributor &A) override {
2255     Value &V = *getAssociatedValue().stripPointerCasts();
2256     if (!NullIsDefined &&
2257         hasAttr({Attribute::NonNull, Attribute::Dereferenceable},
2258                 /* IgnoreSubsumingPositions */ false, &A)) {
2259       indicateOptimisticFixpoint();
2260       return;
2261     }
2262 
2263     if (isa<ConstantPointerNull>(V)) {
2264       indicatePessimisticFixpoint();
2265       return;
2266     }
2267 
2268     AANonNull::initialize(A);
2269 
2270     bool CanBeNull, CanBeFreed;
2271     if (V.getPointerDereferenceableBytes(A.getDataLayout(), CanBeNull,
2272                                          CanBeFreed)) {
2273       if (!CanBeNull) {
2274         indicateOptimisticFixpoint();
2275         return;
2276       }
2277     }
2278 
2279     if (isa<GlobalValue>(V)) {
2280       indicatePessimisticFixpoint();
2281       return;
2282     }
2283 
2284     if (Instruction *CtxI = getCtxI())
2285       followUsesInMBEC(*this, A, getState(), *CtxI);
2286   }
2287 
2288   /// See followUsesInMBEC
2289   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
2290                        AANonNull::StateType &State) {
2291     bool IsNonNull = false;
2292     bool TrackUse = false;
2293     getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I,
2294                                        IsNonNull, TrackUse);
2295     State.setKnown(IsNonNull);
2296     return TrackUse;
2297   }
2298 
2299   /// See AbstractAttribute::getAsStr().
2300   const std::string getAsStr() const override {
2301     return getAssumed() ? "nonnull" : "may-null";
2302   }
2303 
2304   /// Flag to determine if the underlying value can be null and still allow
2305   /// valid accesses.
2306   const bool NullIsDefined;
2307 };
2308 
2309 /// NonNull attribute for a floating value.
2310 struct AANonNullFloating : public AANonNullImpl {
2311   AANonNullFloating(const IRPosition &IRP, Attributor &A)
2312       : AANonNullImpl(IRP, A) {}
2313 
2314   /// See AbstractAttribute::updateImpl(...).
2315   ChangeStatus updateImpl(Attributor &A) override {
2316     const DataLayout &DL = A.getDataLayout();
2317 
2318     bool Stripped;
2319     bool UsedAssumedInformation = false;
2320     SmallVector<AA::ValueAndContext> Values;
2321     if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
2322                                       AA::AnyScope, UsedAssumedInformation)) {
2323       Values.push_back({getAssociatedValue(), getCtxI()});
2324       Stripped = false;
2325     } else {
2326       Stripped = Values.size() != 1 ||
2327                  Values.front().getValue() != &getAssociatedValue();
2328     }
2329 
2330     DominatorTree *DT = nullptr;
2331     AssumptionCache *AC = nullptr;
2332     InformationCache &InfoCache = A.getInfoCache();
2333     if (const Function *Fn = getAnchorScope()) {
2334       DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Fn);
2335       AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*Fn);
2336     }
2337 
2338     AANonNull::StateType T;
2339     auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool {
2340       const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V),
2341                                              DepClassTy::REQUIRED);
2342       if (!Stripped && this == &AA) {
2343         if (!isKnownNonZero(&V, DL, 0, AC, CtxI, DT))
2344           T.indicatePessimisticFixpoint();
2345       } else {
2346         // Use abstract attribute information.
2347         const AANonNull::StateType &NS = AA.getState();
2348         T ^= NS;
2349       }
2350       return T.isValidState();
2351     };
2352 
2353     for (const auto &VAC : Values)
2354       if (!VisitValueCB(*VAC.getValue(), VAC.getCtxI()))
2355         return indicatePessimisticFixpoint();
2356 
2357     return clampStateAndIndicateChange(getState(), T);
2358   }
2359 
2360   /// See AbstractAttribute::trackStatistics()
2361   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
2362 };
2363 
2364 /// NonNull attribute for function return value.
2365 struct AANonNullReturned final
2366     : AAReturnedFromReturnedValues<AANonNull, AANonNull> {
2367   AANonNullReturned(const IRPosition &IRP, Attributor &A)
2368       : AAReturnedFromReturnedValues<AANonNull, AANonNull>(IRP, A) {}
2369 
2370   /// See AbstractAttribute::getAsStr().
2371   const std::string getAsStr() const override {
2372     return getAssumed() ? "nonnull" : "may-null";
2373   }
2374 
2375   /// See AbstractAttribute::trackStatistics()
2376   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
2377 };
2378 
2379 /// NonNull attribute for function argument.
2380 struct AANonNullArgument final
2381     : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> {
2382   AANonNullArgument(const IRPosition &IRP, Attributor &A)
2383       : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP, A) {}
2384 
2385   /// See AbstractAttribute::trackStatistics()
2386   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
2387 };
2388 
2389 struct AANonNullCallSiteArgument final : AANonNullFloating {
2390   AANonNullCallSiteArgument(const IRPosition &IRP, Attributor &A)
2391       : AANonNullFloating(IRP, A) {}
2392 
2393   /// See AbstractAttribute::trackStatistics()
2394   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) }
2395 };
2396 
2397 /// NonNull attribute for a call site return position.
2398 struct AANonNullCallSiteReturned final
2399     : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl> {
2400   AANonNullCallSiteReturned(const IRPosition &IRP, Attributor &A)
2401       : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl>(IRP, A) {}
2402 
2403   /// See AbstractAttribute::trackStatistics()
2404   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) }
2405 };
2406 } // namespace
2407 
2408 /// ------------------------ No-Recurse Attributes ----------------------------
2409 
2410 namespace {
2411 struct AANoRecurseImpl : public AANoRecurse {
2412   AANoRecurseImpl(const IRPosition &IRP, Attributor &A) : AANoRecurse(IRP, A) {}
2413 
2414   /// See AbstractAttribute::getAsStr()
2415   const std::string getAsStr() const override {
2416     return getAssumed() ? "norecurse" : "may-recurse";
2417   }
2418 };
2419 
2420 struct AANoRecurseFunction final : AANoRecurseImpl {
2421   AANoRecurseFunction(const IRPosition &IRP, Attributor &A)
2422       : AANoRecurseImpl(IRP, A) {}
2423 
2424   /// See AbstractAttribute::updateImpl(...).
2425   ChangeStatus updateImpl(Attributor &A) override {
2426 
2427     // If all live call sites are known to be no-recurse, we are as well.
2428     auto CallSitePred = [&](AbstractCallSite ACS) {
2429       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
2430           *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
2431           DepClassTy::NONE);
2432       return NoRecurseAA.isKnownNoRecurse();
2433     };
2434     bool UsedAssumedInformation = false;
2435     if (A.checkForAllCallSites(CallSitePred, *this, true,
2436                                UsedAssumedInformation)) {
2437       // If we know all call sites and all are known no-recurse, we are done.
2438       // If all known call sites, which might not be all that exist, are known
2439       // to be no-recurse, we are not done but we can continue to assume
2440       // no-recurse. If one of the call sites we have not visited will become
2441       // live, another update is triggered.
2442       if (!UsedAssumedInformation)
2443         indicateOptimisticFixpoint();
2444       return ChangeStatus::UNCHANGED;
2445     }
2446 
2447     const AAFunctionReachability &EdgeReachability =
2448         A.getAAFor<AAFunctionReachability>(*this, getIRPosition(),
2449                                            DepClassTy::REQUIRED);
2450     if (EdgeReachability.canReach(A, *getAnchorScope()))
2451       return indicatePessimisticFixpoint();
2452     return ChangeStatus::UNCHANGED;
2453   }
2454 
2455   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
2456 };
2457 
2458 /// NoRecurse attribute deduction for a call sites.
2459 struct AANoRecurseCallSite final : AANoRecurseImpl {
2460   AANoRecurseCallSite(const IRPosition &IRP, Attributor &A)
2461       : AANoRecurseImpl(IRP, A) {}
2462 
2463   /// See AbstractAttribute::initialize(...).
2464   void initialize(Attributor &A) override {
2465     AANoRecurseImpl::initialize(A);
2466     Function *F = getAssociatedFunction();
2467     if (!F || F->isDeclaration())
2468       indicatePessimisticFixpoint();
2469   }
2470 
2471   /// See AbstractAttribute::updateImpl(...).
2472   ChangeStatus updateImpl(Attributor &A) override {
2473     // TODO: Once we have call site specific value information we can provide
2474     //       call site specific liveness information and then it makes
2475     //       sense to specialize attributes for call sites arguments instead of
2476     //       redirecting requests to the callee argument.
2477     Function *F = getAssociatedFunction();
2478     const IRPosition &FnPos = IRPosition::function(*F);
2479     auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos, DepClassTy::REQUIRED);
2480     return clampStateAndIndicateChange(getState(), FnAA.getState());
2481   }
2482 
2483   /// See AbstractAttribute::trackStatistics()
2484   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); }
2485 };
2486 } // namespace
2487 
2488 /// -------------------- Undefined-Behavior Attributes ------------------------
2489 
2490 namespace {
2491 struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
2492   AAUndefinedBehaviorImpl(const IRPosition &IRP, Attributor &A)
2493       : AAUndefinedBehavior(IRP, A) {}
2494 
2495   /// See AbstractAttribute::updateImpl(...).
2496   // through a pointer (i.e. also branches etc.)
2497   ChangeStatus updateImpl(Attributor &A) override {
2498     const size_t UBPrevSize = KnownUBInsts.size();
2499     const size_t NoUBPrevSize = AssumedNoUBInsts.size();
2500 
2501     auto InspectMemAccessInstForUB = [&](Instruction &I) {
2502       // Lang ref now states volatile store is not UB, let's skip them.
2503       if (I.isVolatile() && I.mayWriteToMemory())
2504         return true;
2505 
2506       // Skip instructions that are already saved.
2507       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2508         return true;
2509 
2510       // If we reach here, we know we have an instruction
2511       // that accesses memory through a pointer operand,
2512       // for which getPointerOperand() should give it to us.
2513       Value *PtrOp =
2514           const_cast<Value *>(getPointerOperand(&I, /* AllowVolatile */ true));
2515       assert(PtrOp &&
2516              "Expected pointer operand of memory accessing instruction");
2517 
2518       // Either we stopped and the appropriate action was taken,
2519       // or we got back a simplified value to continue.
2520       Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I);
2521       if (!SimplifiedPtrOp || !SimplifiedPtrOp.value())
2522         return true;
2523       const Value *PtrOpVal = SimplifiedPtrOp.value();
2524 
2525       // A memory access through a pointer is considered UB
2526       // only if the pointer has constant null value.
2527       // TODO: Expand it to not only check constant values.
2528       if (!isa<ConstantPointerNull>(PtrOpVal)) {
2529         AssumedNoUBInsts.insert(&I);
2530         return true;
2531       }
2532       const Type *PtrTy = PtrOpVal->getType();
2533 
2534       // Because we only consider instructions inside functions,
2535       // assume that a parent function exists.
2536       const Function *F = I.getFunction();
2537 
2538       // A memory access using constant null pointer is only considered UB
2539       // if null pointer is _not_ defined for the target platform.
2540       if (llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()))
2541         AssumedNoUBInsts.insert(&I);
2542       else
2543         KnownUBInsts.insert(&I);
2544       return true;
2545     };
2546 
2547     auto InspectBrInstForUB = [&](Instruction &I) {
2548       // A conditional branch instruction is considered UB if it has `undef`
2549       // condition.
2550 
2551       // Skip instructions that are already saved.
2552       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2553         return true;
2554 
2555       // We know we have a branch instruction.
2556       auto *BrInst = cast<BranchInst>(&I);
2557 
2558       // Unconditional branches are never considered UB.
2559       if (BrInst->isUnconditional())
2560         return true;
2561 
2562       // Either we stopped and the appropriate action was taken,
2563       // or we got back a simplified value to continue.
2564       Optional<Value *> SimplifiedCond =
2565           stopOnUndefOrAssumed(A, BrInst->getCondition(), BrInst);
2566       if (!SimplifiedCond || !*SimplifiedCond)
2567         return true;
2568       AssumedNoUBInsts.insert(&I);
2569       return true;
2570     };
2571 
2572     auto InspectCallSiteForUB = [&](Instruction &I) {
2573       // Check whether a callsite always cause UB or not
2574 
2575       // Skip instructions that are already saved.
2576       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2577         return true;
2578 
2579       // Check nonnull and noundef argument attribute violation for each
2580       // callsite.
2581       CallBase &CB = cast<CallBase>(I);
2582       Function *Callee = CB.getCalledFunction();
2583       if (!Callee)
2584         return true;
2585       for (unsigned idx = 0; idx < CB.arg_size(); idx++) {
2586         // If current argument is known to be simplified to null pointer and the
2587         // corresponding argument position is known to have nonnull attribute,
2588         // the argument is poison. Furthermore, if the argument is poison and
2589         // the position is known to have noundef attriubte, this callsite is
2590         // considered UB.
2591         if (idx >= Callee->arg_size())
2592           break;
2593         Value *ArgVal = CB.getArgOperand(idx);
2594         if (!ArgVal)
2595           continue;
2596         // Here, we handle three cases.
2597         //   (1) Not having a value means it is dead. (we can replace the value
2598         //       with undef)
2599         //   (2) Simplified to undef. The argument violate noundef attriubte.
2600         //   (3) Simplified to null pointer where known to be nonnull.
2601         //       The argument is a poison value and violate noundef attribute.
2602         IRPosition CalleeArgumentIRP = IRPosition::callsite_argument(CB, idx);
2603         auto &NoUndefAA =
2604             A.getAAFor<AANoUndef>(*this, CalleeArgumentIRP, DepClassTy::NONE);
2605         if (!NoUndefAA.isKnownNoUndef())
2606           continue;
2607         bool UsedAssumedInformation = false;
2608         Optional<Value *> SimplifiedVal =
2609             A.getAssumedSimplified(IRPosition::value(*ArgVal), *this,
2610                                    UsedAssumedInformation, AA::Interprocedural);
2611         if (UsedAssumedInformation)
2612           continue;
2613         if (SimplifiedVal && !SimplifiedVal.value())
2614           return true;
2615         if (!SimplifiedVal || isa<UndefValue>(*SimplifiedVal.value())) {
2616           KnownUBInsts.insert(&I);
2617           continue;
2618         }
2619         if (!ArgVal->getType()->isPointerTy() ||
2620             !isa<ConstantPointerNull>(*SimplifiedVal.value()))
2621           continue;
2622         auto &NonNullAA =
2623             A.getAAFor<AANonNull>(*this, CalleeArgumentIRP, DepClassTy::NONE);
2624         if (NonNullAA.isKnownNonNull())
2625           KnownUBInsts.insert(&I);
2626       }
2627       return true;
2628     };
2629 
2630     auto InspectReturnInstForUB = [&](Instruction &I) {
2631       auto &RI = cast<ReturnInst>(I);
2632       // Either we stopped and the appropriate action was taken,
2633       // or we got back a simplified return value to continue.
2634       Optional<Value *> SimplifiedRetValue =
2635           stopOnUndefOrAssumed(A, RI.getReturnValue(), &I);
2636       if (!SimplifiedRetValue || !*SimplifiedRetValue)
2637         return true;
2638 
2639       // Check if a return instruction always cause UB or not
2640       // Note: It is guaranteed that the returned position of the anchor
2641       //       scope has noundef attribute when this is called.
2642       //       We also ensure the return position is not "assumed dead"
2643       //       because the returned value was then potentially simplified to
2644       //       `undef` in AAReturnedValues without removing the `noundef`
2645       //       attribute yet.
2646 
2647       // When the returned position has noundef attriubte, UB occurs in the
2648       // following cases.
2649       //   (1) Returned value is known to be undef.
2650       //   (2) The value is known to be a null pointer and the returned
2651       //       position has nonnull attribute (because the returned value is
2652       //       poison).
2653       if (isa<ConstantPointerNull>(*SimplifiedRetValue)) {
2654         auto &NonNullAA = A.getAAFor<AANonNull>(
2655             *this, IRPosition::returned(*getAnchorScope()), DepClassTy::NONE);
2656         if (NonNullAA.isKnownNonNull())
2657           KnownUBInsts.insert(&I);
2658       }
2659 
2660       return true;
2661     };
2662 
2663     bool UsedAssumedInformation = false;
2664     A.checkForAllInstructions(InspectMemAccessInstForUB, *this,
2665                               {Instruction::Load, Instruction::Store,
2666                                Instruction::AtomicCmpXchg,
2667                                Instruction::AtomicRMW},
2668                               UsedAssumedInformation,
2669                               /* CheckBBLivenessOnly */ true);
2670     A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::Br},
2671                               UsedAssumedInformation,
2672                               /* CheckBBLivenessOnly */ true);
2673     A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *this,
2674                                       UsedAssumedInformation);
2675 
2676     // If the returned position of the anchor scope has noundef attriubte, check
2677     // all returned instructions.
2678     if (!getAnchorScope()->getReturnType()->isVoidTy()) {
2679       const IRPosition &ReturnIRP = IRPosition::returned(*getAnchorScope());
2680       if (!A.isAssumedDead(ReturnIRP, this, nullptr, UsedAssumedInformation)) {
2681         auto &RetPosNoUndefAA =
2682             A.getAAFor<AANoUndef>(*this, ReturnIRP, DepClassTy::NONE);
2683         if (RetPosNoUndefAA.isKnownNoUndef())
2684           A.checkForAllInstructions(InspectReturnInstForUB, *this,
2685                                     {Instruction::Ret}, UsedAssumedInformation,
2686                                     /* CheckBBLivenessOnly */ true);
2687       }
2688     }
2689 
2690     if (NoUBPrevSize != AssumedNoUBInsts.size() ||
2691         UBPrevSize != KnownUBInsts.size())
2692       return ChangeStatus::CHANGED;
2693     return ChangeStatus::UNCHANGED;
2694   }
2695 
2696   bool isKnownToCauseUB(Instruction *I) const override {
2697     return KnownUBInsts.count(I);
2698   }
2699 
2700   bool isAssumedToCauseUB(Instruction *I) const override {
2701     // In simple words, if an instruction is not in the assumed to _not_
2702     // cause UB, then it is assumed UB (that includes those
2703     // in the KnownUBInsts set). The rest is boilerplate
2704     // is to ensure that it is one of the instructions we test
2705     // for UB.
2706 
2707     switch (I->getOpcode()) {
2708     case Instruction::Load:
2709     case Instruction::Store:
2710     case Instruction::AtomicCmpXchg:
2711     case Instruction::AtomicRMW:
2712       return !AssumedNoUBInsts.count(I);
2713     case Instruction::Br: {
2714       auto *BrInst = cast<BranchInst>(I);
2715       if (BrInst->isUnconditional())
2716         return false;
2717       return !AssumedNoUBInsts.count(I);
2718     } break;
2719     default:
2720       return false;
2721     }
2722     return false;
2723   }
2724 
2725   ChangeStatus manifest(Attributor &A) override {
2726     if (KnownUBInsts.empty())
2727       return ChangeStatus::UNCHANGED;
2728     for (Instruction *I : KnownUBInsts)
2729       A.changeToUnreachableAfterManifest(I);
2730     return ChangeStatus::CHANGED;
2731   }
2732 
2733   /// See AbstractAttribute::getAsStr()
2734   const std::string getAsStr() const override {
2735     return getAssumed() ? "undefined-behavior" : "no-ub";
2736   }
2737 
2738   /// Note: The correctness of this analysis depends on the fact that the
2739   /// following 2 sets will stop changing after some point.
2740   /// "Change" here means that their size changes.
2741   /// The size of each set is monotonically increasing
2742   /// (we only add items to them) and it is upper bounded by the number of
2743   /// instructions in the processed function (we can never save more
2744   /// elements in either set than this number). Hence, at some point,
2745   /// they will stop increasing.
2746   /// Consequently, at some point, both sets will have stopped
2747   /// changing, effectively making the analysis reach a fixpoint.
2748 
2749   /// Note: These 2 sets are disjoint and an instruction can be considered
2750   /// one of 3 things:
2751   /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in
2752   ///    the KnownUBInsts set.
2753   /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior
2754   ///    has a reason to assume it).
2755   /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior
2756   ///    could not find a reason to assume or prove that it can cause UB,
2757   ///    hence it assumes it doesn't. We have a set for these instructions
2758   ///    so that we don't reprocess them in every update.
2759   ///    Note however that instructions in this set may cause UB.
2760 
2761 protected:
2762   /// A set of all live instructions _known_ to cause UB.
2763   SmallPtrSet<Instruction *, 8> KnownUBInsts;
2764 
2765 private:
2766   /// A set of all the (live) instructions that are assumed to _not_ cause UB.
2767   SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
2768 
2769   // Should be called on updates in which if we're processing an instruction
2770   // \p I that depends on a value \p V, one of the following has to happen:
2771   // - If the value is assumed, then stop.
2772   // - If the value is known but undef, then consider it UB.
2773   // - Otherwise, do specific processing with the simplified value.
2774   // We return None in the first 2 cases to signify that an appropriate
2775   // action was taken and the caller should stop.
2776   // Otherwise, we return the simplified value that the caller should
2777   // use for specific processing.
2778   Optional<Value *> stopOnUndefOrAssumed(Attributor &A, Value *V,
2779                                          Instruction *I) {
2780     bool UsedAssumedInformation = false;
2781     Optional<Value *> SimplifiedV =
2782         A.getAssumedSimplified(IRPosition::value(*V), *this,
2783                                UsedAssumedInformation, AA::Interprocedural);
2784     if (!UsedAssumedInformation) {
2785       // Don't depend on assumed values.
2786       if (!SimplifiedV) {
2787         // If it is known (which we tested above) but it doesn't have a value,
2788         // then we can assume `undef` and hence the instruction is UB.
2789         KnownUBInsts.insert(I);
2790         return llvm::None;
2791       }
2792       if (!*SimplifiedV)
2793         return nullptr;
2794       V = *SimplifiedV;
2795     }
2796     if (isa<UndefValue>(V)) {
2797       KnownUBInsts.insert(I);
2798       return llvm::None;
2799     }
2800     return V;
2801   }
2802 };
2803 
2804 struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
2805   AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A)
2806       : AAUndefinedBehaviorImpl(IRP, A) {}
2807 
2808   /// See AbstractAttribute::trackStatistics()
2809   void trackStatistics() const override {
2810     STATS_DECL(UndefinedBehaviorInstruction, Instruction,
2811                "Number of instructions known to have UB");
2812     BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) +=
2813         KnownUBInsts.size();
2814   }
2815 };
2816 } // namespace
2817 
2818 /// ------------------------ Will-Return Attributes ----------------------------
2819 
2820 namespace {
2821 // Helper function that checks whether a function has any cycle which we don't
2822 // know if it is bounded or not.
2823 // Loops with maximum trip count are considered bounded, any other cycle not.
2824 static bool mayContainUnboundedCycle(Function &F, Attributor &A) {
2825   ScalarEvolution *SE =
2826       A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F);
2827   LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F);
2828   // If either SCEV or LoopInfo is not available for the function then we assume
2829   // any cycle to be unbounded cycle.
2830   // We use scc_iterator which uses Tarjan algorithm to find all the maximal
2831   // SCCs.To detect if there's a cycle, we only need to find the maximal ones.
2832   if (!SE || !LI) {
2833     for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI)
2834       if (SCCI.hasCycle())
2835         return true;
2836     return false;
2837   }
2838 
2839   // If there's irreducible control, the function may contain non-loop cycles.
2840   if (mayContainIrreducibleControl(F, LI))
2841     return true;
2842 
2843   // Any loop that does not have a max trip count is considered unbounded cycle.
2844   for (auto *L : LI->getLoopsInPreorder()) {
2845     if (!SE->getSmallConstantMaxTripCount(L))
2846       return true;
2847   }
2848   return false;
2849 }
2850 
2851 struct AAWillReturnImpl : public AAWillReturn {
2852   AAWillReturnImpl(const IRPosition &IRP, Attributor &A)
2853       : AAWillReturn(IRP, A) {}
2854 
2855   /// See AbstractAttribute::initialize(...).
2856   void initialize(Attributor &A) override {
2857     AAWillReturn::initialize(A);
2858 
2859     if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ true)) {
2860       indicateOptimisticFixpoint();
2861       return;
2862     }
2863   }
2864 
2865   /// Check for `mustprogress` and `readonly` as they imply `willreturn`.
2866   bool isImpliedByMustprogressAndReadonly(Attributor &A, bool KnownOnly) {
2867     // Check for `mustprogress` in the scope and the associated function which
2868     // might be different if this is a call site.
2869     if ((!getAnchorScope() || !getAnchorScope()->mustProgress()) &&
2870         (!getAssociatedFunction() || !getAssociatedFunction()->mustProgress()))
2871       return false;
2872 
2873     bool IsKnown;
2874     if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
2875       return IsKnown || !KnownOnly;
2876     return false;
2877   }
2878 
2879   /// See AbstractAttribute::updateImpl(...).
2880   ChangeStatus updateImpl(Attributor &A) override {
2881     if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false))
2882       return ChangeStatus::UNCHANGED;
2883 
2884     auto CheckForWillReturn = [&](Instruction &I) {
2885       IRPosition IPos = IRPosition::callsite_function(cast<CallBase>(I));
2886       const auto &WillReturnAA =
2887           A.getAAFor<AAWillReturn>(*this, IPos, DepClassTy::REQUIRED);
2888       if (WillReturnAA.isKnownWillReturn())
2889         return true;
2890       if (!WillReturnAA.isAssumedWillReturn())
2891         return false;
2892       const auto &NoRecurseAA =
2893           A.getAAFor<AANoRecurse>(*this, IPos, DepClassTy::REQUIRED);
2894       return NoRecurseAA.isAssumedNoRecurse();
2895     };
2896 
2897     bool UsedAssumedInformation = false;
2898     if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this,
2899                                            UsedAssumedInformation))
2900       return indicatePessimisticFixpoint();
2901 
2902     return ChangeStatus::UNCHANGED;
2903   }
2904 
2905   /// See AbstractAttribute::getAsStr()
2906   const std::string getAsStr() const override {
2907     return getAssumed() ? "willreturn" : "may-noreturn";
2908   }
2909 };
2910 
2911 struct AAWillReturnFunction final : AAWillReturnImpl {
2912   AAWillReturnFunction(const IRPosition &IRP, Attributor &A)
2913       : AAWillReturnImpl(IRP, A) {}
2914 
2915   /// See AbstractAttribute::initialize(...).
2916   void initialize(Attributor &A) override {
2917     AAWillReturnImpl::initialize(A);
2918 
2919     Function *F = getAnchorScope();
2920     if (!F || F->isDeclaration() || mayContainUnboundedCycle(*F, A))
2921       indicatePessimisticFixpoint();
2922   }
2923 
2924   /// See AbstractAttribute::trackStatistics()
2925   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
2926 };
2927 
2928 /// WillReturn attribute deduction for a call sites.
2929 struct AAWillReturnCallSite final : AAWillReturnImpl {
2930   AAWillReturnCallSite(const IRPosition &IRP, Attributor &A)
2931       : AAWillReturnImpl(IRP, A) {}
2932 
2933   /// See AbstractAttribute::initialize(...).
2934   void initialize(Attributor &A) override {
2935     AAWillReturnImpl::initialize(A);
2936     Function *F = getAssociatedFunction();
2937     if (!F || !A.isFunctionIPOAmendable(*F))
2938       indicatePessimisticFixpoint();
2939   }
2940 
2941   /// See AbstractAttribute::updateImpl(...).
2942   ChangeStatus updateImpl(Attributor &A) override {
2943     if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false))
2944       return ChangeStatus::UNCHANGED;
2945 
2946     // TODO: Once we have call site specific value information we can provide
2947     //       call site specific liveness information and then it makes
2948     //       sense to specialize attributes for call sites arguments instead of
2949     //       redirecting requests to the callee argument.
2950     Function *F = getAssociatedFunction();
2951     const IRPosition &FnPos = IRPosition::function(*F);
2952     auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos, DepClassTy::REQUIRED);
2953     return clampStateAndIndicateChange(getState(), FnAA.getState());
2954   }
2955 
2956   /// See AbstractAttribute::trackStatistics()
2957   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); }
2958 };
2959 } // namespace
2960 
2961 /// -------------------AAReachability Attribute--------------------------
2962 
2963 namespace {
2964 struct AAReachabilityImpl : AAReachability {
2965   AAReachabilityImpl(const IRPosition &IRP, Attributor &A)
2966       : AAReachability(IRP, A) {}
2967 
2968   const std::string getAsStr() const override {
2969     // TODO: Return the number of reachable queries.
2970     return "reachable";
2971   }
2972 
2973   /// See AbstractAttribute::updateImpl(...).
2974   ChangeStatus updateImpl(Attributor &A) override {
2975     return ChangeStatus::UNCHANGED;
2976   }
2977 };
2978 
2979 struct AAReachabilityFunction final : public AAReachabilityImpl {
2980   AAReachabilityFunction(const IRPosition &IRP, Attributor &A)
2981       : AAReachabilityImpl(IRP, A) {}
2982 
2983   /// See AbstractAttribute::trackStatistics()
2984   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(reachable); }
2985 };
2986 } // namespace
2987 
2988 /// ------------------------ NoAlias Argument Attribute ------------------------
2989 
2990 namespace {
2991 struct AANoAliasImpl : AANoAlias {
2992   AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) {
2993     assert(getAssociatedType()->isPointerTy() &&
2994            "Noalias is a pointer attribute");
2995   }
2996 
2997   const std::string getAsStr() const override {
2998     return getAssumed() ? "noalias" : "may-alias";
2999   }
3000 };
3001 
3002 /// NoAlias attribute for a floating value.
3003 struct AANoAliasFloating final : AANoAliasImpl {
3004   AANoAliasFloating(const IRPosition &IRP, Attributor &A)
3005       : AANoAliasImpl(IRP, A) {}
3006 
3007   /// See AbstractAttribute::initialize(...).
3008   void initialize(Attributor &A) override {
3009     AANoAliasImpl::initialize(A);
3010     Value *Val = &getAssociatedValue();
3011     do {
3012       CastInst *CI = dyn_cast<CastInst>(Val);
3013       if (!CI)
3014         break;
3015       Value *Base = CI->getOperand(0);
3016       if (!Base->hasOneUse())
3017         break;
3018       Val = Base;
3019     } while (true);
3020 
3021     if (!Val->getType()->isPointerTy()) {
3022       indicatePessimisticFixpoint();
3023       return;
3024     }
3025 
3026     if (isa<AllocaInst>(Val))
3027       indicateOptimisticFixpoint();
3028     else if (isa<ConstantPointerNull>(Val) &&
3029              !NullPointerIsDefined(getAnchorScope(),
3030                                    Val->getType()->getPointerAddressSpace()))
3031       indicateOptimisticFixpoint();
3032     else if (Val != &getAssociatedValue()) {
3033       const auto &ValNoAliasAA = A.getAAFor<AANoAlias>(
3034           *this, IRPosition::value(*Val), DepClassTy::OPTIONAL);
3035       if (ValNoAliasAA.isKnownNoAlias())
3036         indicateOptimisticFixpoint();
3037     }
3038   }
3039 
3040   /// See AbstractAttribute::updateImpl(...).
3041   ChangeStatus updateImpl(Attributor &A) override {
3042     // TODO: Implement this.
3043     return indicatePessimisticFixpoint();
3044   }
3045 
3046   /// See AbstractAttribute::trackStatistics()
3047   void trackStatistics() const override {
3048     STATS_DECLTRACK_FLOATING_ATTR(noalias)
3049   }
3050 };
3051 
3052 /// NoAlias attribute for an argument.
3053 struct AANoAliasArgument final
3054     : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
3055   using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
3056   AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
3057 
3058   /// See AbstractAttribute::initialize(...).
3059   void initialize(Attributor &A) override {
3060     Base::initialize(A);
3061     // See callsite argument attribute and callee argument attribute.
3062     if (hasAttr({Attribute::ByVal}))
3063       indicateOptimisticFixpoint();
3064   }
3065 
3066   /// See AbstractAttribute::update(...).
3067   ChangeStatus updateImpl(Attributor &A) override {
3068     // We have to make sure no-alias on the argument does not break
3069     // synchronization when this is a callback argument, see also [1] below.
3070     // If synchronization cannot be affected, we delegate to the base updateImpl
3071     // function, otherwise we give up for now.
3072 
3073     // If the function is no-sync, no-alias cannot break synchronization.
3074     const auto &NoSyncAA =
3075         A.getAAFor<AANoSync>(*this, IRPosition::function_scope(getIRPosition()),
3076                              DepClassTy::OPTIONAL);
3077     if (NoSyncAA.isAssumedNoSync())
3078       return Base::updateImpl(A);
3079 
3080     // If the argument is read-only, no-alias cannot break synchronization.
3081     bool IsKnown;
3082     if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
3083       return Base::updateImpl(A);
3084 
3085     // If the argument is never passed through callbacks, no-alias cannot break
3086     // synchronization.
3087     bool UsedAssumedInformation = false;
3088     if (A.checkForAllCallSites(
3089             [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this,
3090             true, UsedAssumedInformation))
3091       return Base::updateImpl(A);
3092 
3093     // TODO: add no-alias but make sure it doesn't break synchronization by
3094     // introducing fake uses. See:
3095     // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel,
3096     //     International Workshop on OpenMP 2018,
3097     //     http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf
3098 
3099     return indicatePessimisticFixpoint();
3100   }
3101 
3102   /// See AbstractAttribute::trackStatistics()
3103   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
3104 };
3105 
3106 struct AANoAliasCallSiteArgument final : AANoAliasImpl {
3107   AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A)
3108       : AANoAliasImpl(IRP, A) {}
3109 
3110   /// See AbstractAttribute::initialize(...).
3111   void initialize(Attributor &A) override {
3112     // See callsite argument attribute and callee argument attribute.
3113     const auto &CB = cast<CallBase>(getAnchorValue());
3114     if (CB.paramHasAttr(getCallSiteArgNo(), Attribute::NoAlias))
3115       indicateOptimisticFixpoint();
3116     Value &Val = getAssociatedValue();
3117     if (isa<ConstantPointerNull>(Val) &&
3118         !NullPointerIsDefined(getAnchorScope(),
3119                               Val.getType()->getPointerAddressSpace()))
3120       indicateOptimisticFixpoint();
3121   }
3122 
3123   /// Determine if the underlying value may alias with the call site argument
3124   /// \p OtherArgNo of \p ICS (= the underlying call site).
3125   bool mayAliasWithArgument(Attributor &A, AAResults *&AAR,
3126                             const AAMemoryBehavior &MemBehaviorAA,
3127                             const CallBase &CB, unsigned OtherArgNo) {
3128     // We do not need to worry about aliasing with the underlying IRP.
3129     if (this->getCalleeArgNo() == (int)OtherArgNo)
3130       return false;
3131 
3132     // If it is not a pointer or pointer vector we do not alias.
3133     const Value *ArgOp = CB.getArgOperand(OtherArgNo);
3134     if (!ArgOp->getType()->isPtrOrPtrVectorTy())
3135       return false;
3136 
3137     auto &CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
3138         *this, IRPosition::callsite_argument(CB, OtherArgNo), DepClassTy::NONE);
3139 
3140     // If the argument is readnone, there is no read-write aliasing.
3141     if (CBArgMemBehaviorAA.isAssumedReadNone()) {
3142       A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
3143       return false;
3144     }
3145 
3146     // If the argument is readonly and the underlying value is readonly, there
3147     // is no read-write aliasing.
3148     bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly();
3149     if (CBArgMemBehaviorAA.isAssumedReadOnly() && IsReadOnly) {
3150       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
3151       A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
3152       return false;
3153     }
3154 
3155     // We have to utilize actual alias analysis queries so we need the object.
3156     if (!AAR)
3157       AAR = A.getInfoCache().getAAResultsForFunction(*getAnchorScope());
3158 
3159     // Try to rule it out at the call site.
3160     bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp);
3161     LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between "
3162                          "callsite arguments: "
3163                       << getAssociatedValue() << " " << *ArgOp << " => "
3164                       << (IsAliasing ? "" : "no-") << "alias \n");
3165 
3166     return IsAliasing;
3167   }
3168 
3169   bool
3170   isKnownNoAliasDueToNoAliasPreservation(Attributor &A, AAResults *&AAR,
3171                                          const AAMemoryBehavior &MemBehaviorAA,
3172                                          const AANoAlias &NoAliasAA) {
3173     // We can deduce "noalias" if the following conditions hold.
3174     // (i)   Associated value is assumed to be noalias in the definition.
3175     // (ii)  Associated value is assumed to be no-capture in all the uses
3176     //       possibly executed before this callsite.
3177     // (iii) There is no other pointer argument which could alias with the
3178     //       value.
3179 
3180     bool AssociatedValueIsNoAliasAtDef = NoAliasAA.isAssumedNoAlias();
3181     if (!AssociatedValueIsNoAliasAtDef) {
3182       LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue()
3183                         << " is not no-alias at the definition\n");
3184       return false;
3185     }
3186 
3187     auto IsDereferenceableOrNull = [&](Value *O, const DataLayout &DL) {
3188       const auto &DerefAA = A.getAAFor<AADereferenceable>(
3189           *this, IRPosition::value(*O), DepClassTy::OPTIONAL);
3190       return DerefAA.getAssumedDereferenceableBytes();
3191     };
3192 
3193     A.recordDependence(NoAliasAA, *this, DepClassTy::OPTIONAL);
3194 
3195     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
3196     const Function *ScopeFn = VIRP.getAnchorScope();
3197     auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, VIRP, DepClassTy::NONE);
3198     // Check whether the value is captured in the scope using AANoCapture.
3199     // Look at CFG and check only uses possibly executed before this
3200     // callsite.
3201     auto UsePred = [&](const Use &U, bool &Follow) -> bool {
3202       Instruction *UserI = cast<Instruction>(U.getUser());
3203 
3204       // If UserI is the curr instruction and there is a single potential use of
3205       // the value in UserI we allow the use.
3206       // TODO: We should inspect the operands and allow those that cannot alias
3207       //       with the value.
3208       if (UserI == getCtxI() && UserI->getNumOperands() == 1)
3209         return true;
3210 
3211       if (ScopeFn) {
3212         if (auto *CB = dyn_cast<CallBase>(UserI)) {
3213           if (CB->isArgOperand(&U)) {
3214 
3215             unsigned ArgNo = CB->getArgOperandNo(&U);
3216 
3217             const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
3218                 *this, IRPosition::callsite_argument(*CB, ArgNo),
3219                 DepClassTy::OPTIONAL);
3220 
3221             if (NoCaptureAA.isAssumedNoCapture())
3222               return true;
3223           }
3224         }
3225 
3226         if (!AA::isPotentiallyReachable(A, *UserI, *getCtxI(), *this))
3227           return true;
3228       }
3229 
3230       // TODO: We should track the capturing uses in AANoCapture but the problem
3231       //       is CGSCC runs. For those we would need to "allow" AANoCapture for
3232       //       a value in the module slice.
3233       switch (DetermineUseCaptureKind(U, IsDereferenceableOrNull)) {
3234       case UseCaptureKind::NO_CAPTURE:
3235         return true;
3236       case UseCaptureKind::MAY_CAPTURE:
3237         LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *UserI
3238                           << "\n");
3239         return false;
3240       case UseCaptureKind::PASSTHROUGH:
3241         Follow = true;
3242         return true;
3243       }
3244       llvm_unreachable("unknown UseCaptureKind");
3245     };
3246 
3247     if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
3248       if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) {
3249         LLVM_DEBUG(
3250             dbgs() << "[AANoAliasCSArg] " << getAssociatedValue()
3251                    << " cannot be noalias as it is potentially captured\n");
3252         return false;
3253       }
3254     }
3255     A.recordDependence(NoCaptureAA, *this, DepClassTy::OPTIONAL);
3256 
3257     // Check there is no other pointer argument which could alias with the
3258     // value passed at this call site.
3259     // TODO: AbstractCallSite
3260     const auto &CB = cast<CallBase>(getAnchorValue());
3261     for (unsigned OtherArgNo = 0; OtherArgNo < CB.arg_size(); OtherArgNo++)
3262       if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo))
3263         return false;
3264 
3265     return true;
3266   }
3267 
3268   /// See AbstractAttribute::updateImpl(...).
3269   ChangeStatus updateImpl(Attributor &A) override {
3270     // If the argument is readnone we are done as there are no accesses via the
3271     // argument.
3272     auto &MemBehaviorAA =
3273         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE);
3274     if (MemBehaviorAA.isAssumedReadNone()) {
3275       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
3276       return ChangeStatus::UNCHANGED;
3277     }
3278 
3279     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
3280     const auto &NoAliasAA =
3281         A.getAAFor<AANoAlias>(*this, VIRP, DepClassTy::NONE);
3282 
3283     AAResults *AAR = nullptr;
3284     if (isKnownNoAliasDueToNoAliasPreservation(A, AAR, MemBehaviorAA,
3285                                                NoAliasAA)) {
3286       LLVM_DEBUG(
3287           dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n");
3288       return ChangeStatus::UNCHANGED;
3289     }
3290 
3291     return indicatePessimisticFixpoint();
3292   }
3293 
3294   /// See AbstractAttribute::trackStatistics()
3295   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) }
3296 };
3297 
3298 /// NoAlias attribute for function return value.
3299 struct AANoAliasReturned final : AANoAliasImpl {
3300   AANoAliasReturned(const IRPosition &IRP, Attributor &A)
3301       : AANoAliasImpl(IRP, A) {}
3302 
3303   /// See AbstractAttribute::initialize(...).
3304   void initialize(Attributor &A) override {
3305     AANoAliasImpl::initialize(A);
3306     Function *F = getAssociatedFunction();
3307     if (!F || F->isDeclaration())
3308       indicatePessimisticFixpoint();
3309   }
3310 
3311   /// See AbstractAttribute::updateImpl(...).
3312   virtual ChangeStatus updateImpl(Attributor &A) override {
3313 
3314     auto CheckReturnValue = [&](Value &RV) -> bool {
3315       if (Constant *C = dyn_cast<Constant>(&RV))
3316         if (C->isNullValue() || isa<UndefValue>(C))
3317           return true;
3318 
3319       /// For now, we can only deduce noalias if we have call sites.
3320       /// FIXME: add more support.
3321       if (!isa<CallBase>(&RV))
3322         return false;
3323 
3324       const IRPosition &RVPos = IRPosition::value(RV);
3325       const auto &NoAliasAA =
3326           A.getAAFor<AANoAlias>(*this, RVPos, DepClassTy::REQUIRED);
3327       if (!NoAliasAA.isAssumedNoAlias())
3328         return false;
3329 
3330       const auto &NoCaptureAA =
3331           A.getAAFor<AANoCapture>(*this, RVPos, DepClassTy::REQUIRED);
3332       return NoCaptureAA.isAssumedNoCaptureMaybeReturned();
3333     };
3334 
3335     if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
3336       return indicatePessimisticFixpoint();
3337 
3338     return ChangeStatus::UNCHANGED;
3339   }
3340 
3341   /// See AbstractAttribute::trackStatistics()
3342   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
3343 };
3344 
3345 /// NoAlias attribute deduction for a call site return value.
3346 struct AANoAliasCallSiteReturned final : AANoAliasImpl {
3347   AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A)
3348       : AANoAliasImpl(IRP, A) {}
3349 
3350   /// See AbstractAttribute::initialize(...).
3351   void initialize(Attributor &A) override {
3352     AANoAliasImpl::initialize(A);
3353     Function *F = getAssociatedFunction();
3354     if (!F || F->isDeclaration())
3355       indicatePessimisticFixpoint();
3356   }
3357 
3358   /// See AbstractAttribute::updateImpl(...).
3359   ChangeStatus updateImpl(Attributor &A) override {
3360     // TODO: Once we have call site specific value information we can provide
3361     //       call site specific liveness information and then it makes
3362     //       sense to specialize attributes for call sites arguments instead of
3363     //       redirecting requests to the callee argument.
3364     Function *F = getAssociatedFunction();
3365     const IRPosition &FnPos = IRPosition::returned(*F);
3366     auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos, DepClassTy::REQUIRED);
3367     return clampStateAndIndicateChange(getState(), FnAA.getState());
3368   }
3369 
3370   /// See AbstractAttribute::trackStatistics()
3371   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); }
3372 };
3373 } // namespace
3374 
3375 /// -------------------AAIsDead Function Attribute-----------------------
3376 
3377 namespace {
3378 struct AAIsDeadValueImpl : public AAIsDead {
3379   AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
3380 
3381   /// See AbstractAttribute::initialize(...).
3382   void initialize(Attributor &A) override {
3383     if (auto *Scope = getAnchorScope())
3384       if (!A.isRunOn(*Scope))
3385         indicatePessimisticFixpoint();
3386   }
3387 
3388   /// See AAIsDead::isAssumedDead().
3389   bool isAssumedDead() const override { return isAssumed(IS_DEAD); }
3390 
3391   /// See AAIsDead::isKnownDead().
3392   bool isKnownDead() const override { return isKnown(IS_DEAD); }
3393 
3394   /// See AAIsDead::isAssumedDead(BasicBlock *).
3395   bool isAssumedDead(const BasicBlock *BB) const override { return false; }
3396 
3397   /// See AAIsDead::isKnownDead(BasicBlock *).
3398   bool isKnownDead(const BasicBlock *BB) const override { return false; }
3399 
3400   /// See AAIsDead::isAssumedDead(Instruction *I).
3401   bool isAssumedDead(const Instruction *I) const override {
3402     return I == getCtxI() && isAssumedDead();
3403   }
3404 
3405   /// See AAIsDead::isKnownDead(Instruction *I).
3406   bool isKnownDead(const Instruction *I) const override {
3407     return isAssumedDead(I) && isKnownDead();
3408   }
3409 
3410   /// See AbstractAttribute::getAsStr().
3411   virtual const std::string getAsStr() const override {
3412     return isAssumedDead() ? "assumed-dead" : "assumed-live";
3413   }
3414 
3415   /// Check if all uses are assumed dead.
3416   bool areAllUsesAssumedDead(Attributor &A, Value &V) {
3417     // Callers might not check the type, void has no uses.
3418     if (V.getType()->isVoidTy() || V.use_empty())
3419       return true;
3420 
3421     // If we replace a value with a constant there are no uses left afterwards.
3422     if (!isa<Constant>(V)) {
3423       if (auto *I = dyn_cast<Instruction>(&V))
3424         if (!A.isRunOn(*I->getFunction()))
3425           return false;
3426       bool UsedAssumedInformation = false;
3427       Optional<Constant *> C =
3428           A.getAssumedConstant(V, *this, UsedAssumedInformation);
3429       if (!C || *C)
3430         return true;
3431     }
3432 
3433     auto UsePred = [&](const Use &U, bool &Follow) { return false; };
3434     // Explicitly set the dependence class to required because we want a long
3435     // chain of N dependent instructions to be considered live as soon as one is
3436     // without going through N update cycles. This is not required for
3437     // correctness.
3438     return A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ false,
3439                              DepClassTy::REQUIRED,
3440                              /* IgnoreDroppableUses */ false);
3441   }
3442 
3443   /// Determine if \p I is assumed to be side-effect free.
3444   bool isAssumedSideEffectFree(Attributor &A, Instruction *I) {
3445     if (!I || wouldInstructionBeTriviallyDead(I))
3446       return true;
3447 
3448     auto *CB = dyn_cast<CallBase>(I);
3449     if (!CB || isa<IntrinsicInst>(CB))
3450       return false;
3451 
3452     const IRPosition &CallIRP = IRPosition::callsite_function(*CB);
3453     const auto &NoUnwindAA =
3454         A.getAndUpdateAAFor<AANoUnwind>(*this, CallIRP, DepClassTy::NONE);
3455     if (!NoUnwindAA.isAssumedNoUnwind())
3456       return false;
3457     if (!NoUnwindAA.isKnownNoUnwind())
3458       A.recordDependence(NoUnwindAA, *this, DepClassTy::OPTIONAL);
3459 
3460     bool IsKnown;
3461     return AA::isAssumedReadOnly(A, CallIRP, *this, IsKnown);
3462   }
3463 };
3464 
3465 struct AAIsDeadFloating : public AAIsDeadValueImpl {
3466   AAIsDeadFloating(const IRPosition &IRP, Attributor &A)
3467       : AAIsDeadValueImpl(IRP, A) {}
3468 
3469   /// See AbstractAttribute::initialize(...).
3470   void initialize(Attributor &A) override {
3471     AAIsDeadValueImpl::initialize(A);
3472 
3473     if (isa<UndefValue>(getAssociatedValue())) {
3474       indicatePessimisticFixpoint();
3475       return;
3476     }
3477 
3478     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
3479     if (!isAssumedSideEffectFree(A, I)) {
3480       if (!isa_and_nonnull<StoreInst>(I))
3481         indicatePessimisticFixpoint();
3482       else
3483         removeAssumedBits(HAS_NO_EFFECT);
3484     }
3485   }
3486 
3487   bool isDeadStore(Attributor &A, StoreInst &SI) {
3488     // Lang ref now states volatile store is not UB/dead, let's skip them.
3489     if (SI.isVolatile())
3490       return false;
3491 
3492     bool UsedAssumedInformation = false;
3493     SmallSetVector<Value *, 4> PotentialCopies;
3494     if (!AA::getPotentialCopiesOfStoredValue(A, SI, PotentialCopies, *this,
3495                                              UsedAssumedInformation))
3496       return false;
3497     return llvm::all_of(PotentialCopies, [&](Value *V) {
3498       return A.isAssumedDead(IRPosition::value(*V), this, nullptr,
3499                              UsedAssumedInformation);
3500     });
3501   }
3502 
3503   /// See AbstractAttribute::getAsStr().
3504   const std::string getAsStr() const override {
3505     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
3506     if (isa_and_nonnull<StoreInst>(I))
3507       if (isValidState())
3508         return "assumed-dead-store";
3509     return AAIsDeadValueImpl::getAsStr();
3510   }
3511 
3512   /// See AbstractAttribute::updateImpl(...).
3513   ChangeStatus updateImpl(Attributor &A) override {
3514     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
3515     if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
3516       if (!isDeadStore(A, *SI))
3517         return indicatePessimisticFixpoint();
3518     } else {
3519       if (!isAssumedSideEffectFree(A, I))
3520         return indicatePessimisticFixpoint();
3521       if (!areAllUsesAssumedDead(A, getAssociatedValue()))
3522         return indicatePessimisticFixpoint();
3523     }
3524     return ChangeStatus::UNCHANGED;
3525   }
3526 
3527   bool isRemovableStore() const override {
3528     return isAssumed(IS_REMOVABLE) && isa<StoreInst>(&getAssociatedValue());
3529   }
3530 
3531   /// See AbstractAttribute::manifest(...).
3532   ChangeStatus manifest(Attributor &A) override {
3533     Value &V = getAssociatedValue();
3534     if (auto *I = dyn_cast<Instruction>(&V)) {
3535       // If we get here we basically know the users are all dead. We check if
3536       // isAssumedSideEffectFree returns true here again because it might not be
3537       // the case and only the users are dead but the instruction (=call) is
3538       // still needed.
3539       if (isa<StoreInst>(I) ||
3540           (isAssumedSideEffectFree(A, I) && !isa<InvokeInst>(I))) {
3541         A.deleteAfterManifest(*I);
3542         return ChangeStatus::CHANGED;
3543       }
3544     }
3545     return ChangeStatus::UNCHANGED;
3546   }
3547 
3548   /// See AbstractAttribute::trackStatistics()
3549   void trackStatistics() const override {
3550     STATS_DECLTRACK_FLOATING_ATTR(IsDead)
3551   }
3552 };
3553 
3554 struct AAIsDeadArgument : public AAIsDeadFloating {
3555   AAIsDeadArgument(const IRPosition &IRP, Attributor &A)
3556       : AAIsDeadFloating(IRP, A) {}
3557 
3558   /// See AbstractAttribute::initialize(...).
3559   void initialize(Attributor &A) override {
3560     AAIsDeadFloating::initialize(A);
3561     if (!A.isFunctionIPOAmendable(*getAnchorScope()))
3562       indicatePessimisticFixpoint();
3563   }
3564 
3565   /// See AbstractAttribute::manifest(...).
3566   ChangeStatus manifest(Attributor &A) override {
3567     Argument &Arg = *getAssociatedArgument();
3568     if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {}))
3569       if (A.registerFunctionSignatureRewrite(
3570               Arg, /* ReplacementTypes */ {},
3571               Attributor::ArgumentReplacementInfo::CalleeRepairCBTy{},
3572               Attributor::ArgumentReplacementInfo::ACSRepairCBTy{})) {
3573         return ChangeStatus::CHANGED;
3574       }
3575     return ChangeStatus::UNCHANGED;
3576   }
3577 
3578   /// See AbstractAttribute::trackStatistics()
3579   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) }
3580 };
3581 
3582 struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl {
3583   AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A)
3584       : AAIsDeadValueImpl(IRP, A) {}
3585 
3586   /// See AbstractAttribute::initialize(...).
3587   void initialize(Attributor &A) override {
3588     AAIsDeadValueImpl::initialize(A);
3589     if (isa<UndefValue>(getAssociatedValue()))
3590       indicatePessimisticFixpoint();
3591   }
3592 
3593   /// See AbstractAttribute::updateImpl(...).
3594   ChangeStatus updateImpl(Attributor &A) override {
3595     // TODO: Once we have call site specific value information we can provide
3596     //       call site specific liveness information and then it makes
3597     //       sense to specialize attributes for call sites arguments instead of
3598     //       redirecting requests to the callee argument.
3599     Argument *Arg = getAssociatedArgument();
3600     if (!Arg)
3601       return indicatePessimisticFixpoint();
3602     const IRPosition &ArgPos = IRPosition::argument(*Arg);
3603     auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos, DepClassTy::REQUIRED);
3604     return clampStateAndIndicateChange(getState(), ArgAA.getState());
3605   }
3606 
3607   /// See AbstractAttribute::manifest(...).
3608   ChangeStatus manifest(Attributor &A) override {
3609     CallBase &CB = cast<CallBase>(getAnchorValue());
3610     Use &U = CB.getArgOperandUse(getCallSiteArgNo());
3611     assert(!isa<UndefValue>(U.get()) &&
3612            "Expected undef values to be filtered out!");
3613     UndefValue &UV = *UndefValue::get(U->getType());
3614     if (A.changeUseAfterManifest(U, UV))
3615       return ChangeStatus::CHANGED;
3616     return ChangeStatus::UNCHANGED;
3617   }
3618 
3619   /// See AbstractAttribute::trackStatistics()
3620   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) }
3621 };
3622 
3623 struct AAIsDeadCallSiteReturned : public AAIsDeadFloating {
3624   AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A)
3625       : AAIsDeadFloating(IRP, A) {}
3626 
3627   /// See AAIsDead::isAssumedDead().
3628   bool isAssumedDead() const override {
3629     return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
3630   }
3631 
3632   /// See AbstractAttribute::initialize(...).
3633   void initialize(Attributor &A) override {
3634     AAIsDeadFloating::initialize(A);
3635     if (isa<UndefValue>(getAssociatedValue())) {
3636       indicatePessimisticFixpoint();
3637       return;
3638     }
3639 
3640     // We track this separately as a secondary state.
3641     IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI());
3642   }
3643 
3644   /// See AbstractAttribute::updateImpl(...).
3645   ChangeStatus updateImpl(Attributor &A) override {
3646     ChangeStatus Changed = ChangeStatus::UNCHANGED;
3647     if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) {
3648       IsAssumedSideEffectFree = false;
3649       Changed = ChangeStatus::CHANGED;
3650     }
3651     if (!areAllUsesAssumedDead(A, getAssociatedValue()))
3652       return indicatePessimisticFixpoint();
3653     return Changed;
3654   }
3655 
3656   /// See AbstractAttribute::trackStatistics()
3657   void trackStatistics() const override {
3658     if (IsAssumedSideEffectFree)
3659       STATS_DECLTRACK_CSRET_ATTR(IsDead)
3660     else
3661       STATS_DECLTRACK_CSRET_ATTR(UnusedResult)
3662   }
3663 
3664   /// See AbstractAttribute::getAsStr().
3665   const std::string getAsStr() const override {
3666     return isAssumedDead()
3667                ? "assumed-dead"
3668                : (getAssumed() ? "assumed-dead-users" : "assumed-live");
3669   }
3670 
3671 private:
3672   bool IsAssumedSideEffectFree = true;
3673 };
3674 
3675 struct AAIsDeadReturned : public AAIsDeadValueImpl {
3676   AAIsDeadReturned(const IRPosition &IRP, Attributor &A)
3677       : AAIsDeadValueImpl(IRP, A) {}
3678 
3679   /// See AbstractAttribute::updateImpl(...).
3680   ChangeStatus updateImpl(Attributor &A) override {
3681 
3682     bool UsedAssumedInformation = false;
3683     A.checkForAllInstructions([](Instruction &) { return true; }, *this,
3684                               {Instruction::Ret}, UsedAssumedInformation);
3685 
3686     auto PredForCallSite = [&](AbstractCallSite ACS) {
3687       if (ACS.isCallbackCall() || !ACS.getInstruction())
3688         return false;
3689       return areAllUsesAssumedDead(A, *ACS.getInstruction());
3690     };
3691 
3692     if (!A.checkForAllCallSites(PredForCallSite, *this, true,
3693                                 UsedAssumedInformation))
3694       return indicatePessimisticFixpoint();
3695 
3696     return ChangeStatus::UNCHANGED;
3697   }
3698 
3699   /// See AbstractAttribute::manifest(...).
3700   ChangeStatus manifest(Attributor &A) override {
3701     // TODO: Rewrite the signature to return void?
3702     bool AnyChange = false;
3703     UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType());
3704     auto RetInstPred = [&](Instruction &I) {
3705       ReturnInst &RI = cast<ReturnInst>(I);
3706       if (!isa<UndefValue>(RI.getReturnValue()))
3707         AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV);
3708       return true;
3709     };
3710     bool UsedAssumedInformation = false;
3711     A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret},
3712                               UsedAssumedInformation);
3713     return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
3714   }
3715 
3716   /// See AbstractAttribute::trackStatistics()
3717   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) }
3718 };
3719 
3720 struct AAIsDeadFunction : public AAIsDead {
3721   AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
3722 
3723   /// See AbstractAttribute::initialize(...).
3724   void initialize(Attributor &A) override {
3725     Function *F = getAnchorScope();
3726     if (!F || F->isDeclaration() || !A.isRunOn(*F)) {
3727       indicatePessimisticFixpoint();
3728       return;
3729     }
3730     ToBeExploredFrom.insert(&F->getEntryBlock().front());
3731     assumeLive(A, F->getEntryBlock());
3732   }
3733 
3734   /// See AbstractAttribute::getAsStr().
3735   const std::string getAsStr() const override {
3736     return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
3737            std::to_string(getAnchorScope()->size()) + "][#TBEP " +
3738            std::to_string(ToBeExploredFrom.size()) + "][#KDE " +
3739            std::to_string(KnownDeadEnds.size()) + "]";
3740   }
3741 
3742   /// See AbstractAttribute::manifest(...).
3743   ChangeStatus manifest(Attributor &A) override {
3744     assert(getState().isValidState() &&
3745            "Attempted to manifest an invalid state!");
3746 
3747     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
3748     Function &F = *getAnchorScope();
3749 
3750     if (AssumedLiveBlocks.empty()) {
3751       A.deleteAfterManifest(F);
3752       return ChangeStatus::CHANGED;
3753     }
3754 
3755     // Flag to determine if we can change an invoke to a call assuming the
3756     // callee is nounwind. This is not possible if the personality of the
3757     // function allows to catch asynchronous exceptions.
3758     bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
3759 
3760     KnownDeadEnds.set_union(ToBeExploredFrom);
3761     for (const Instruction *DeadEndI : KnownDeadEnds) {
3762       auto *CB = dyn_cast<CallBase>(DeadEndI);
3763       if (!CB)
3764         continue;
3765       const auto &NoReturnAA = A.getAndUpdateAAFor<AANoReturn>(
3766           *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL);
3767       bool MayReturn = !NoReturnAA.isAssumedNoReturn();
3768       if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
3769         continue;
3770 
3771       if (auto *II = dyn_cast<InvokeInst>(DeadEndI))
3772         A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II));
3773       else
3774         A.changeToUnreachableAfterManifest(
3775             const_cast<Instruction *>(DeadEndI->getNextNode()));
3776       HasChanged = ChangeStatus::CHANGED;
3777     }
3778 
3779     STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted.");
3780     for (BasicBlock &BB : F)
3781       if (!AssumedLiveBlocks.count(&BB)) {
3782         A.deleteAfterManifest(BB);
3783         ++BUILD_STAT_NAME(AAIsDead, BasicBlock);
3784         HasChanged = ChangeStatus::CHANGED;
3785       }
3786 
3787     return HasChanged;
3788   }
3789 
3790   /// See AbstractAttribute::updateImpl(...).
3791   ChangeStatus updateImpl(Attributor &A) override;
3792 
3793   bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const override {
3794     assert(From->getParent() == getAnchorScope() &&
3795            To->getParent() == getAnchorScope() &&
3796            "Used AAIsDead of the wrong function");
3797     return isValidState() && !AssumedLiveEdges.count(std::make_pair(From, To));
3798   }
3799 
3800   /// See AbstractAttribute::trackStatistics()
3801   void trackStatistics() const override {}
3802 
3803   /// Returns true if the function is assumed dead.
3804   bool isAssumedDead() const override { return false; }
3805 
3806   /// See AAIsDead::isKnownDead().
3807   bool isKnownDead() const override { return false; }
3808 
3809   /// See AAIsDead::isAssumedDead(BasicBlock *).
3810   bool isAssumedDead(const BasicBlock *BB) const override {
3811     assert(BB->getParent() == getAnchorScope() &&
3812            "BB must be in the same anchor scope function.");
3813 
3814     if (!getAssumed())
3815       return false;
3816     return !AssumedLiveBlocks.count(BB);
3817   }
3818 
3819   /// See AAIsDead::isKnownDead(BasicBlock *).
3820   bool isKnownDead(const BasicBlock *BB) const override {
3821     return getKnown() && isAssumedDead(BB);
3822   }
3823 
3824   /// See AAIsDead::isAssumed(Instruction *I).
3825   bool isAssumedDead(const Instruction *I) const override {
3826     assert(I->getParent()->getParent() == getAnchorScope() &&
3827            "Instruction must be in the same anchor scope function.");
3828 
3829     if (!getAssumed())
3830       return false;
3831 
3832     // If it is not in AssumedLiveBlocks then it for sure dead.
3833     // Otherwise, it can still be after noreturn call in a live block.
3834     if (!AssumedLiveBlocks.count(I->getParent()))
3835       return true;
3836 
3837     // If it is not after a liveness barrier it is live.
3838     const Instruction *PrevI = I->getPrevNode();
3839     while (PrevI) {
3840       if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
3841         return true;
3842       PrevI = PrevI->getPrevNode();
3843     }
3844     return false;
3845   }
3846 
3847   /// See AAIsDead::isKnownDead(Instruction *I).
3848   bool isKnownDead(const Instruction *I) const override {
3849     return getKnown() && isAssumedDead(I);
3850   }
3851 
3852   /// Assume \p BB is (partially) live now and indicate to the Attributor \p A
3853   /// that internal function called from \p BB should now be looked at.
3854   bool assumeLive(Attributor &A, const BasicBlock &BB) {
3855     if (!AssumedLiveBlocks.insert(&BB).second)
3856       return false;
3857 
3858     // We assume that all of BB is (probably) live now and if there are calls to
3859     // internal functions we will assume that those are now live as well. This
3860     // is a performance optimization for blocks with calls to a lot of internal
3861     // functions. It can however cause dead functions to be treated as live.
3862     for (const Instruction &I : BB)
3863       if (const auto *CB = dyn_cast<CallBase>(&I))
3864         if (const Function *F = CB->getCalledFunction())
3865           if (F->hasLocalLinkage())
3866             A.markLiveInternalFunction(*F);
3867     return true;
3868   }
3869 
3870   /// Collection of instructions that need to be explored again, e.g., we
3871   /// did assume they do not transfer control to (one of their) successors.
3872   SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
3873 
3874   /// Collection of instructions that are known to not transfer control.
3875   SmallSetVector<const Instruction *, 8> KnownDeadEnds;
3876 
3877   /// Collection of all assumed live edges
3878   DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges;
3879 
3880   /// Collection of all assumed live BasicBlocks.
3881   DenseSet<const BasicBlock *> AssumedLiveBlocks;
3882 };
3883 
3884 static bool
3885 identifyAliveSuccessors(Attributor &A, const CallBase &CB,
3886                         AbstractAttribute &AA,
3887                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3888   const IRPosition &IPos = IRPosition::callsite_function(CB);
3889 
3890   const auto &NoReturnAA =
3891       A.getAndUpdateAAFor<AANoReturn>(AA, IPos, DepClassTy::OPTIONAL);
3892   if (NoReturnAA.isAssumedNoReturn())
3893     return !NoReturnAA.isKnownNoReturn();
3894   if (CB.isTerminator())
3895     AliveSuccessors.push_back(&CB.getSuccessor(0)->front());
3896   else
3897     AliveSuccessors.push_back(CB.getNextNode());
3898   return false;
3899 }
3900 
3901 static bool
3902 identifyAliveSuccessors(Attributor &A, const InvokeInst &II,
3903                         AbstractAttribute &AA,
3904                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3905   bool UsedAssumedInformation =
3906       identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
3907 
3908   // First, determine if we can change an invoke to a call assuming the
3909   // callee is nounwind. This is not possible if the personality of the
3910   // function allows to catch asynchronous exceptions.
3911   if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) {
3912     AliveSuccessors.push_back(&II.getUnwindDest()->front());
3913   } else {
3914     const IRPosition &IPos = IRPosition::callsite_function(II);
3915     const auto &AANoUnw =
3916         A.getAndUpdateAAFor<AANoUnwind>(AA, IPos, DepClassTy::OPTIONAL);
3917     if (AANoUnw.isAssumedNoUnwind()) {
3918       UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind();
3919     } else {
3920       AliveSuccessors.push_back(&II.getUnwindDest()->front());
3921     }
3922   }
3923   return UsedAssumedInformation;
3924 }
3925 
3926 static bool
3927 identifyAliveSuccessors(Attributor &A, const BranchInst &BI,
3928                         AbstractAttribute &AA,
3929                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3930   bool UsedAssumedInformation = false;
3931   if (BI.getNumSuccessors() == 1) {
3932     AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
3933   } else {
3934     Optional<Constant *> C =
3935         A.getAssumedConstant(*BI.getCondition(), AA, UsedAssumedInformation);
3936     if (!C || isa_and_nonnull<UndefValue>(*C)) {
3937       // No value yet, assume both edges are dead.
3938     } else if (isa_and_nonnull<ConstantInt>(*C)) {
3939       const BasicBlock *SuccBB =
3940           BI.getSuccessor(1 - cast<ConstantInt>(*C)->getValue().getZExtValue());
3941       AliveSuccessors.push_back(&SuccBB->front());
3942     } else {
3943       AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
3944       AliveSuccessors.push_back(&BI.getSuccessor(1)->front());
3945       UsedAssumedInformation = false;
3946     }
3947   }
3948   return UsedAssumedInformation;
3949 }
3950 
3951 static bool
3952 identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
3953                         AbstractAttribute &AA,
3954                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3955   bool UsedAssumedInformation = false;
3956   Optional<Constant *> C =
3957       A.getAssumedConstant(*SI.getCondition(), AA, UsedAssumedInformation);
3958   if (!C || isa_and_nonnull<UndefValue>(C.value())) {
3959     // No value yet, assume all edges are dead.
3960   } else if (isa_and_nonnull<ConstantInt>(C.value())) {
3961     for (auto &CaseIt : SI.cases()) {
3962       if (CaseIt.getCaseValue() == C.value()) {
3963         AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
3964         return UsedAssumedInformation;
3965       }
3966     }
3967     AliveSuccessors.push_back(&SI.getDefaultDest()->front());
3968     return UsedAssumedInformation;
3969   } else {
3970     for (const BasicBlock *SuccBB : successors(SI.getParent()))
3971       AliveSuccessors.push_back(&SuccBB->front());
3972   }
3973   return UsedAssumedInformation;
3974 }
3975 
3976 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
3977   ChangeStatus Change = ChangeStatus::UNCHANGED;
3978 
3979   LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/"
3980                     << getAnchorScope()->size() << "] BBs and "
3981                     << ToBeExploredFrom.size() << " exploration points and "
3982                     << KnownDeadEnds.size() << " known dead ends\n");
3983 
3984   // Copy and clear the list of instructions we need to explore from. It is
3985   // refilled with instructions the next update has to look at.
3986   SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(),
3987                                                ToBeExploredFrom.end());
3988   decltype(ToBeExploredFrom) NewToBeExploredFrom;
3989 
3990   SmallVector<const Instruction *, 8> AliveSuccessors;
3991   while (!Worklist.empty()) {
3992     const Instruction *I = Worklist.pop_back_val();
3993     LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n");
3994 
3995     // Fast forward for uninteresting instructions. We could look for UB here
3996     // though.
3997     while (!I->isTerminator() && !isa<CallBase>(I))
3998       I = I->getNextNode();
3999 
4000     AliveSuccessors.clear();
4001 
4002     bool UsedAssumedInformation = false;
4003     switch (I->getOpcode()) {
4004     // TODO: look for (assumed) UB to backwards propagate "deadness".
4005     default:
4006       assert(I->isTerminator() &&
4007              "Expected non-terminators to be handled already!");
4008       for (const BasicBlock *SuccBB : successors(I->getParent()))
4009         AliveSuccessors.push_back(&SuccBB->front());
4010       break;
4011     case Instruction::Call:
4012       UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
4013                                                        *this, AliveSuccessors);
4014       break;
4015     case Instruction::Invoke:
4016       UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
4017                                                        *this, AliveSuccessors);
4018       break;
4019     case Instruction::Br:
4020       UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I),
4021                                                        *this, AliveSuccessors);
4022       break;
4023     case Instruction::Switch:
4024       UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
4025                                                        *this, AliveSuccessors);
4026       break;
4027     }
4028 
4029     if (UsedAssumedInformation) {
4030       NewToBeExploredFrom.insert(I);
4031     } else if (AliveSuccessors.empty() ||
4032                (I->isTerminator() &&
4033                 AliveSuccessors.size() < I->getNumSuccessors())) {
4034       if (KnownDeadEnds.insert(I))
4035         Change = ChangeStatus::CHANGED;
4036     }
4037 
4038     LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: "
4039                       << AliveSuccessors.size() << " UsedAssumedInformation: "
4040                       << UsedAssumedInformation << "\n");
4041 
4042     for (const Instruction *AliveSuccessor : AliveSuccessors) {
4043       if (!I->isTerminator()) {
4044         assert(AliveSuccessors.size() == 1 &&
4045                "Non-terminator expected to have a single successor!");
4046         Worklist.push_back(AliveSuccessor);
4047       } else {
4048         // record the assumed live edge
4049         auto Edge = std::make_pair(I->getParent(), AliveSuccessor->getParent());
4050         if (AssumedLiveEdges.insert(Edge).second)
4051           Change = ChangeStatus::CHANGED;
4052         if (assumeLive(A, *AliveSuccessor->getParent()))
4053           Worklist.push_back(AliveSuccessor);
4054       }
4055     }
4056   }
4057 
4058   // Check if the content of ToBeExploredFrom changed, ignore the order.
4059   if (NewToBeExploredFrom.size() != ToBeExploredFrom.size() ||
4060       llvm::any_of(NewToBeExploredFrom, [&](const Instruction *I) {
4061         return !ToBeExploredFrom.count(I);
4062       })) {
4063     Change = ChangeStatus::CHANGED;
4064     ToBeExploredFrom = std::move(NewToBeExploredFrom);
4065   }
4066 
4067   // If we know everything is live there is no need to query for liveness.
4068   // Instead, indicating a pessimistic fixpoint will cause the state to be
4069   // "invalid" and all queries to be answered conservatively without lookups.
4070   // To be in this state we have to (1) finished the exploration and (3) not
4071   // discovered any non-trivial dead end and (2) not ruled unreachable code
4072   // dead.
4073   if (ToBeExploredFrom.empty() &&
4074       getAnchorScope()->size() == AssumedLiveBlocks.size() &&
4075       llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) {
4076         return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
4077       }))
4078     return indicatePessimisticFixpoint();
4079   return Change;
4080 }
4081 
4082 /// Liveness information for a call sites.
4083 struct AAIsDeadCallSite final : AAIsDeadFunction {
4084   AAIsDeadCallSite(const IRPosition &IRP, Attributor &A)
4085       : AAIsDeadFunction(IRP, A) {}
4086 
4087   /// See AbstractAttribute::initialize(...).
4088   void initialize(Attributor &A) override {
4089     // TODO: Once we have call site specific value information we can provide
4090     //       call site specific liveness information and then it makes
4091     //       sense to specialize attributes for call sites instead of
4092     //       redirecting requests to the callee.
4093     llvm_unreachable("Abstract attributes for liveness are not "
4094                      "supported for call sites yet!");
4095   }
4096 
4097   /// See AbstractAttribute::updateImpl(...).
4098   ChangeStatus updateImpl(Attributor &A) override {
4099     return indicatePessimisticFixpoint();
4100   }
4101 
4102   /// See AbstractAttribute::trackStatistics()
4103   void trackStatistics() const override {}
4104 };
4105 } // namespace
4106 
4107 /// -------------------- Dereferenceable Argument Attribute --------------------
4108 
4109 namespace {
4110 struct AADereferenceableImpl : AADereferenceable {
4111   AADereferenceableImpl(const IRPosition &IRP, Attributor &A)
4112       : AADereferenceable(IRP, A) {}
4113   using StateType = DerefState;
4114 
4115   /// See AbstractAttribute::initialize(...).
4116   void initialize(Attributor &A) override {
4117     Value &V = *getAssociatedValue().stripPointerCasts();
4118     SmallVector<Attribute, 4> Attrs;
4119     getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
4120              Attrs, /* IgnoreSubsumingPositions */ false, &A);
4121     for (const Attribute &Attr : Attrs)
4122       takeKnownDerefBytesMaximum(Attr.getValueAsInt());
4123 
4124     const IRPosition &IRP = this->getIRPosition();
4125     NonNullAA = &A.getAAFor<AANonNull>(*this, IRP, DepClassTy::NONE);
4126 
4127     bool CanBeNull, CanBeFreed;
4128     takeKnownDerefBytesMaximum(V.getPointerDereferenceableBytes(
4129         A.getDataLayout(), CanBeNull, CanBeFreed));
4130 
4131     bool IsFnInterface = IRP.isFnInterfaceKind();
4132     Function *FnScope = IRP.getAnchorScope();
4133     if (IsFnInterface && (!FnScope || !A.isFunctionIPOAmendable(*FnScope))) {
4134       indicatePessimisticFixpoint();
4135       return;
4136     }
4137 
4138     if (Instruction *CtxI = getCtxI())
4139       followUsesInMBEC(*this, A, getState(), *CtxI);
4140   }
4141 
4142   /// See AbstractAttribute::getState()
4143   /// {
4144   StateType &getState() override { return *this; }
4145   const StateType &getState() const override { return *this; }
4146   /// }
4147 
4148   /// Helper function for collecting accessed bytes in must-be-executed-context
4149   void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I,
4150                               DerefState &State) {
4151     const Value *UseV = U->get();
4152     if (!UseV->getType()->isPointerTy())
4153       return;
4154 
4155     Optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
4156     if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() || I->isVolatile())
4157       return;
4158 
4159     int64_t Offset;
4160     const Value *Base = GetPointerBaseWithConstantOffset(
4161         Loc->Ptr, Offset, A.getDataLayout(), /*AllowNonInbounds*/ true);
4162     if (Base && Base == &getAssociatedValue())
4163       State.addAccessedBytes(Offset, Loc->Size.getValue());
4164   }
4165 
4166   /// See followUsesInMBEC
4167   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
4168                        AADereferenceable::StateType &State) {
4169     bool IsNonNull = false;
4170     bool TrackUse = false;
4171     int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
4172         A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse);
4173     LLVM_DEBUG(dbgs() << "[AADereferenceable] Deref bytes: " << DerefBytes
4174                       << " for instruction " << *I << "\n");
4175 
4176     addAccessedBytesForUse(A, U, I, State);
4177     State.takeKnownDerefBytesMaximum(DerefBytes);
4178     return TrackUse;
4179   }
4180 
4181   /// See AbstractAttribute::manifest(...).
4182   ChangeStatus manifest(Attributor &A) override {
4183     ChangeStatus Change = AADereferenceable::manifest(A);
4184     if (isAssumedNonNull() && hasAttr(Attribute::DereferenceableOrNull)) {
4185       removeAttrs({Attribute::DereferenceableOrNull});
4186       return ChangeStatus::CHANGED;
4187     }
4188     return Change;
4189   }
4190 
4191   void getDeducedAttributes(LLVMContext &Ctx,
4192                             SmallVectorImpl<Attribute> &Attrs) const override {
4193     // TODO: Add *_globally support
4194     if (isAssumedNonNull())
4195       Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
4196           Ctx, getAssumedDereferenceableBytes()));
4197     else
4198       Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
4199           Ctx, getAssumedDereferenceableBytes()));
4200   }
4201 
4202   /// See AbstractAttribute::getAsStr().
4203   const std::string getAsStr() const override {
4204     if (!getAssumedDereferenceableBytes())
4205       return "unknown-dereferenceable";
4206     return std::string("dereferenceable") +
4207            (isAssumedNonNull() ? "" : "_or_null") +
4208            (isAssumedGlobal() ? "_globally" : "") + "<" +
4209            std::to_string(getKnownDereferenceableBytes()) + "-" +
4210            std::to_string(getAssumedDereferenceableBytes()) + ">";
4211   }
4212 };
4213 
4214 /// Dereferenceable attribute for a floating value.
4215 struct AADereferenceableFloating : AADereferenceableImpl {
4216   AADereferenceableFloating(const IRPosition &IRP, Attributor &A)
4217       : AADereferenceableImpl(IRP, A) {}
4218 
4219   /// See AbstractAttribute::updateImpl(...).
4220   ChangeStatus updateImpl(Attributor &A) override {
4221 
4222     bool Stripped;
4223     bool UsedAssumedInformation = false;
4224     SmallVector<AA::ValueAndContext> Values;
4225     if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
4226                                       AA::AnyScope, UsedAssumedInformation)) {
4227       Values.push_back({getAssociatedValue(), getCtxI()});
4228       Stripped = false;
4229     } else {
4230       Stripped = Values.size() != 1 ||
4231                  Values.front().getValue() != &getAssociatedValue();
4232     }
4233 
4234     const DataLayout &DL = A.getDataLayout();
4235     DerefState T;
4236 
4237     auto VisitValueCB = [&](const Value &V) -> bool {
4238       unsigned IdxWidth =
4239           DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
4240       APInt Offset(IdxWidth, 0);
4241       const Value *Base = stripAndAccumulateOffsets(
4242           A, *this, &V, DL, Offset, /* GetMinOffset */ false,
4243           /* AllowNonInbounds */ true);
4244 
4245       const auto &AA = A.getAAFor<AADereferenceable>(
4246           *this, IRPosition::value(*Base), DepClassTy::REQUIRED);
4247       int64_t DerefBytes = 0;
4248       if (!Stripped && this == &AA) {
4249         // Use IR information if we did not strip anything.
4250         // TODO: track globally.
4251         bool CanBeNull, CanBeFreed;
4252         DerefBytes =
4253             Base->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
4254         T.GlobalState.indicatePessimisticFixpoint();
4255       } else {
4256         const DerefState &DS = AA.getState();
4257         DerefBytes = DS.DerefBytesState.getAssumed();
4258         T.GlobalState &= DS.GlobalState;
4259       }
4260 
4261       // For now we do not try to "increase" dereferenceability due to negative
4262       // indices as we first have to come up with code to deal with loops and
4263       // for overflows of the dereferenceable bytes.
4264       int64_t OffsetSExt = Offset.getSExtValue();
4265       if (OffsetSExt < 0)
4266         OffsetSExt = 0;
4267 
4268       T.takeAssumedDerefBytesMinimum(
4269           std::max(int64_t(0), DerefBytes - OffsetSExt));
4270 
4271       if (this == &AA) {
4272         if (!Stripped) {
4273           // If nothing was stripped IR information is all we got.
4274           T.takeKnownDerefBytesMaximum(
4275               std::max(int64_t(0), DerefBytes - OffsetSExt));
4276           T.indicatePessimisticFixpoint();
4277         } else if (OffsetSExt > 0) {
4278           // If something was stripped but there is circular reasoning we look
4279           // for the offset. If it is positive we basically decrease the
4280           // dereferenceable bytes in a circluar loop now, which will simply
4281           // drive them down to the known value in a very slow way which we
4282           // can accelerate.
4283           T.indicatePessimisticFixpoint();
4284         }
4285       }
4286 
4287       return T.isValidState();
4288     };
4289 
4290     for (const auto &VAC : Values)
4291       if (!VisitValueCB(*VAC.getValue()))
4292         return indicatePessimisticFixpoint();
4293 
4294     return clampStateAndIndicateChange(getState(), T);
4295   }
4296 
4297   /// See AbstractAttribute::trackStatistics()
4298   void trackStatistics() const override {
4299     STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
4300   }
4301 };
4302 
4303 /// Dereferenceable attribute for a return value.
4304 struct AADereferenceableReturned final
4305     : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
4306   AADereferenceableReturned(const IRPosition &IRP, Attributor &A)
4307       : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>(
4308             IRP, A) {}
4309 
4310   /// See AbstractAttribute::trackStatistics()
4311   void trackStatistics() const override {
4312     STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
4313   }
4314 };
4315 
4316 /// Dereferenceable attribute for an argument
4317 struct AADereferenceableArgument final
4318     : AAArgumentFromCallSiteArguments<AADereferenceable,
4319                                       AADereferenceableImpl> {
4320   using Base =
4321       AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>;
4322   AADereferenceableArgument(const IRPosition &IRP, Attributor &A)
4323       : Base(IRP, A) {}
4324 
4325   /// See AbstractAttribute::trackStatistics()
4326   void trackStatistics() const override {
4327     STATS_DECLTRACK_ARG_ATTR(dereferenceable)
4328   }
4329 };
4330 
4331 /// Dereferenceable attribute for a call site argument.
4332 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
4333   AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A)
4334       : AADereferenceableFloating(IRP, A) {}
4335 
4336   /// See AbstractAttribute::trackStatistics()
4337   void trackStatistics() const override {
4338     STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
4339   }
4340 };
4341 
4342 /// Dereferenceable attribute deduction for a call site return value.
4343 struct AADereferenceableCallSiteReturned final
4344     : AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl> {
4345   using Base =
4346       AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl>;
4347   AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A)
4348       : Base(IRP, A) {}
4349 
4350   /// See AbstractAttribute::trackStatistics()
4351   void trackStatistics() const override {
4352     STATS_DECLTRACK_CS_ATTR(dereferenceable);
4353   }
4354 };
4355 } // namespace
4356 
4357 // ------------------------ Align Argument Attribute ------------------------
4358 
4359 namespace {
4360 static unsigned getKnownAlignForUse(Attributor &A, AAAlign &QueryingAA,
4361                                     Value &AssociatedValue, const Use *U,
4362                                     const Instruction *I, bool &TrackUse) {
4363   // We need to follow common pointer manipulation uses to the accesses they
4364   // feed into.
4365   if (isa<CastInst>(I)) {
4366     // Follow all but ptr2int casts.
4367     TrackUse = !isa<PtrToIntInst>(I);
4368     return 0;
4369   }
4370   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
4371     if (GEP->hasAllConstantIndices())
4372       TrackUse = true;
4373     return 0;
4374   }
4375 
4376   MaybeAlign MA;
4377   if (const auto *CB = dyn_cast<CallBase>(I)) {
4378     if (CB->isBundleOperand(U) || CB->isCallee(U))
4379       return 0;
4380 
4381     unsigned ArgNo = CB->getArgOperandNo(U);
4382     IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
4383     // As long as we only use known information there is no need to track
4384     // dependences here.
4385     auto &AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP, DepClassTy::NONE);
4386     MA = MaybeAlign(AlignAA.getKnownAlign());
4387   }
4388 
4389   const DataLayout &DL = A.getDataLayout();
4390   const Value *UseV = U->get();
4391   if (auto *SI = dyn_cast<StoreInst>(I)) {
4392     if (SI->getPointerOperand() == UseV)
4393       MA = SI->getAlign();
4394   } else if (auto *LI = dyn_cast<LoadInst>(I)) {
4395     if (LI->getPointerOperand() == UseV)
4396       MA = LI->getAlign();
4397   }
4398 
4399   if (!MA || *MA <= QueryingAA.getKnownAlign())
4400     return 0;
4401 
4402   unsigned Alignment = MA->value();
4403   int64_t Offset;
4404 
4405   if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) {
4406     if (Base == &AssociatedValue) {
4407       // BasePointerAddr + Offset = Alignment * Q for some integer Q.
4408       // So we can say that the maximum power of two which is a divisor of
4409       // gcd(Offset, Alignment) is an alignment.
4410 
4411       uint32_t gcd =
4412           greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), Alignment);
4413       Alignment = llvm::PowerOf2Floor(gcd);
4414     }
4415   }
4416 
4417   return Alignment;
4418 }
4419 
4420 struct AAAlignImpl : AAAlign {
4421   AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {}
4422 
4423   /// See AbstractAttribute::initialize(...).
4424   void initialize(Attributor &A) override {
4425     SmallVector<Attribute, 4> Attrs;
4426     getAttrs({Attribute::Alignment}, Attrs);
4427     for (const Attribute &Attr : Attrs)
4428       takeKnownMaximum(Attr.getValueAsInt());
4429 
4430     Value &V = *getAssociatedValue().stripPointerCasts();
4431     takeKnownMaximum(V.getPointerAlignment(A.getDataLayout()).value());
4432 
4433     if (getIRPosition().isFnInterfaceKind() &&
4434         (!getAnchorScope() ||
4435          !A.isFunctionIPOAmendable(*getAssociatedFunction()))) {
4436       indicatePessimisticFixpoint();
4437       return;
4438     }
4439 
4440     if (Instruction *CtxI = getCtxI())
4441       followUsesInMBEC(*this, A, getState(), *CtxI);
4442   }
4443 
4444   /// See AbstractAttribute::manifest(...).
4445   ChangeStatus manifest(Attributor &A) override {
4446     ChangeStatus LoadStoreChanged = ChangeStatus::UNCHANGED;
4447 
4448     // Check for users that allow alignment annotations.
4449     Value &AssociatedValue = getAssociatedValue();
4450     for (const Use &U : AssociatedValue.uses()) {
4451       if (auto *SI = dyn_cast<StoreInst>(U.getUser())) {
4452         if (SI->getPointerOperand() == &AssociatedValue)
4453           if (SI->getAlign() < getAssumedAlign()) {
4454             STATS_DECLTRACK(AAAlign, Store,
4455                             "Number of times alignment added to a store");
4456             SI->setAlignment(getAssumedAlign());
4457             LoadStoreChanged = ChangeStatus::CHANGED;
4458           }
4459       } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) {
4460         if (LI->getPointerOperand() == &AssociatedValue)
4461           if (LI->getAlign() < getAssumedAlign()) {
4462             LI->setAlignment(getAssumedAlign());
4463             STATS_DECLTRACK(AAAlign, Load,
4464                             "Number of times alignment added to a load");
4465             LoadStoreChanged = ChangeStatus::CHANGED;
4466           }
4467       }
4468     }
4469 
4470     ChangeStatus Changed = AAAlign::manifest(A);
4471 
4472     Align InheritAlign =
4473         getAssociatedValue().getPointerAlignment(A.getDataLayout());
4474     if (InheritAlign >= getAssumedAlign())
4475       return LoadStoreChanged;
4476     return Changed | LoadStoreChanged;
4477   }
4478 
4479   // TODO: Provide a helper to determine the implied ABI alignment and check in
4480   //       the existing manifest method and a new one for AAAlignImpl that value
4481   //       to avoid making the alignment explicit if it did not improve.
4482 
4483   /// See AbstractAttribute::getDeducedAttributes
4484   virtual void
4485   getDeducedAttributes(LLVMContext &Ctx,
4486                        SmallVectorImpl<Attribute> &Attrs) const override {
4487     if (getAssumedAlign() > 1)
4488       Attrs.emplace_back(
4489           Attribute::getWithAlignment(Ctx, Align(getAssumedAlign())));
4490   }
4491 
4492   /// See followUsesInMBEC
4493   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
4494                        AAAlign::StateType &State) {
4495     bool TrackUse = false;
4496 
4497     unsigned int KnownAlign =
4498         getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse);
4499     State.takeKnownMaximum(KnownAlign);
4500 
4501     return TrackUse;
4502   }
4503 
4504   /// See AbstractAttribute::getAsStr().
4505   const std::string getAsStr() const override {
4506     return "align<" + std::to_string(getKnownAlign().value()) + "-" +
4507            std::to_string(getAssumedAlign().value()) + ">";
4508   }
4509 };
4510 
4511 /// Align attribute for a floating value.
4512 struct AAAlignFloating : AAAlignImpl {
4513   AAAlignFloating(const IRPosition &IRP, Attributor &A) : AAAlignImpl(IRP, A) {}
4514 
4515   /// See AbstractAttribute::updateImpl(...).
4516   ChangeStatus updateImpl(Attributor &A) override {
4517     const DataLayout &DL = A.getDataLayout();
4518 
4519     bool Stripped;
4520     bool UsedAssumedInformation = false;
4521     SmallVector<AA::ValueAndContext> Values;
4522     if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
4523                                       AA::AnyScope, UsedAssumedInformation)) {
4524       Values.push_back({getAssociatedValue(), getCtxI()});
4525       Stripped = false;
4526     } else {
4527       Stripped = Values.size() != 1 ||
4528                  Values.front().getValue() != &getAssociatedValue();
4529     }
4530 
4531     StateType T;
4532     auto VisitValueCB = [&](Value &V) -> bool {
4533       if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
4534         return true;
4535       const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V),
4536                                            DepClassTy::REQUIRED);
4537       if (!Stripped && this == &AA) {
4538         int64_t Offset;
4539         unsigned Alignment = 1;
4540         if (const Value *Base =
4541                 GetPointerBaseWithConstantOffset(&V, Offset, DL)) {
4542           // TODO: Use AAAlign for the base too.
4543           Align PA = Base->getPointerAlignment(DL);
4544           // BasePointerAddr + Offset = Alignment * Q for some integer Q.
4545           // So we can say that the maximum power of two which is a divisor of
4546           // gcd(Offset, Alignment) is an alignment.
4547 
4548           uint32_t gcd = greatestCommonDivisor(uint32_t(abs((int32_t)Offset)),
4549                                                uint32_t(PA.value()));
4550           Alignment = llvm::PowerOf2Floor(gcd);
4551         } else {
4552           Alignment = V.getPointerAlignment(DL).value();
4553         }
4554         // Use only IR information if we did not strip anything.
4555         T.takeKnownMaximum(Alignment);
4556         T.indicatePessimisticFixpoint();
4557       } else {
4558         // Use abstract attribute information.
4559         const AAAlign::StateType &DS = AA.getState();
4560         T ^= DS;
4561       }
4562       return T.isValidState();
4563     };
4564 
4565     for (const auto &VAC : Values) {
4566       if (!VisitValueCB(*VAC.getValue()))
4567         return indicatePessimisticFixpoint();
4568     }
4569 
4570     //  TODO: If we know we visited all incoming values, thus no are assumed
4571     //  dead, we can take the known information from the state T.
4572     return clampStateAndIndicateChange(getState(), T);
4573   }
4574 
4575   /// See AbstractAttribute::trackStatistics()
4576   void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
4577 };
4578 
4579 /// Align attribute for function return value.
4580 struct AAAlignReturned final
4581     : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
4582   using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>;
4583   AAAlignReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
4584 
4585   /// See AbstractAttribute::initialize(...).
4586   void initialize(Attributor &A) override {
4587     Base::initialize(A);
4588     Function *F = getAssociatedFunction();
4589     if (!F || F->isDeclaration())
4590       indicatePessimisticFixpoint();
4591   }
4592 
4593   /// See AbstractAttribute::trackStatistics()
4594   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
4595 };
4596 
4597 /// Align attribute for function argument.
4598 struct AAAlignArgument final
4599     : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
4600   using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>;
4601   AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
4602 
4603   /// See AbstractAttribute::manifest(...).
4604   ChangeStatus manifest(Attributor &A) override {
4605     // If the associated argument is involved in a must-tail call we give up
4606     // because we would need to keep the argument alignments of caller and
4607     // callee in-sync. Just does not seem worth the trouble right now.
4608     if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
4609       return ChangeStatus::UNCHANGED;
4610     return Base::manifest(A);
4611   }
4612 
4613   /// See AbstractAttribute::trackStatistics()
4614   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
4615 };
4616 
4617 struct AAAlignCallSiteArgument final : AAAlignFloating {
4618   AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A)
4619       : AAAlignFloating(IRP, A) {}
4620 
4621   /// See AbstractAttribute::manifest(...).
4622   ChangeStatus manifest(Attributor &A) override {
4623     // If the associated argument is involved in a must-tail call we give up
4624     // because we would need to keep the argument alignments of caller and
4625     // callee in-sync. Just does not seem worth the trouble right now.
4626     if (Argument *Arg = getAssociatedArgument())
4627       if (A.getInfoCache().isInvolvedInMustTailCall(*Arg))
4628         return ChangeStatus::UNCHANGED;
4629     ChangeStatus Changed = AAAlignImpl::manifest(A);
4630     Align InheritAlign =
4631         getAssociatedValue().getPointerAlignment(A.getDataLayout());
4632     if (InheritAlign >= getAssumedAlign())
4633       Changed = ChangeStatus::UNCHANGED;
4634     return Changed;
4635   }
4636 
4637   /// See AbstractAttribute::updateImpl(Attributor &A).
4638   ChangeStatus updateImpl(Attributor &A) override {
4639     ChangeStatus Changed = AAAlignFloating::updateImpl(A);
4640     if (Argument *Arg = getAssociatedArgument()) {
4641       // We only take known information from the argument
4642       // so we do not need to track a dependence.
4643       const auto &ArgAlignAA = A.getAAFor<AAAlign>(
4644           *this, IRPosition::argument(*Arg), DepClassTy::NONE);
4645       takeKnownMaximum(ArgAlignAA.getKnownAlign().value());
4646     }
4647     return Changed;
4648   }
4649 
4650   /// See AbstractAttribute::trackStatistics()
4651   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
4652 };
4653 
4654 /// Align attribute deduction for a call site return value.
4655 struct AAAlignCallSiteReturned final
4656     : AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl> {
4657   using Base = AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl>;
4658   AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A)
4659       : Base(IRP, A) {}
4660 
4661   /// See AbstractAttribute::initialize(...).
4662   void initialize(Attributor &A) override {
4663     Base::initialize(A);
4664     Function *F = getAssociatedFunction();
4665     if (!F || F->isDeclaration())
4666       indicatePessimisticFixpoint();
4667   }
4668 
4669   /// See AbstractAttribute::trackStatistics()
4670   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); }
4671 };
4672 } // namespace
4673 
4674 /// ------------------ Function No-Return Attribute ----------------------------
4675 namespace {
4676 struct AANoReturnImpl : public AANoReturn {
4677   AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {}
4678 
4679   /// See AbstractAttribute::initialize(...).
4680   void initialize(Attributor &A) override {
4681     AANoReturn::initialize(A);
4682     Function *F = getAssociatedFunction();
4683     if (!F || F->isDeclaration())
4684       indicatePessimisticFixpoint();
4685   }
4686 
4687   /// See AbstractAttribute::getAsStr().
4688   const std::string getAsStr() const override {
4689     return getAssumed() ? "noreturn" : "may-return";
4690   }
4691 
4692   /// See AbstractAttribute::updateImpl(Attributor &A).
4693   virtual ChangeStatus updateImpl(Attributor &A) override {
4694     auto CheckForNoReturn = [](Instruction &) { return false; };
4695     bool UsedAssumedInformation = false;
4696     if (!A.checkForAllInstructions(CheckForNoReturn, *this,
4697                                    {(unsigned)Instruction::Ret},
4698                                    UsedAssumedInformation))
4699       return indicatePessimisticFixpoint();
4700     return ChangeStatus::UNCHANGED;
4701   }
4702 };
4703 
4704 struct AANoReturnFunction final : AANoReturnImpl {
4705   AANoReturnFunction(const IRPosition &IRP, Attributor &A)
4706       : AANoReturnImpl(IRP, A) {}
4707 
4708   /// See AbstractAttribute::trackStatistics()
4709   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
4710 };
4711 
4712 /// NoReturn attribute deduction for a call sites.
4713 struct AANoReturnCallSite final : AANoReturnImpl {
4714   AANoReturnCallSite(const IRPosition &IRP, Attributor &A)
4715       : AANoReturnImpl(IRP, A) {}
4716 
4717   /// See AbstractAttribute::initialize(...).
4718   void initialize(Attributor &A) override {
4719     AANoReturnImpl::initialize(A);
4720     if (Function *F = getAssociatedFunction()) {
4721       const IRPosition &FnPos = IRPosition::function(*F);
4722       auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos, DepClassTy::REQUIRED);
4723       if (!FnAA.isAssumedNoReturn())
4724         indicatePessimisticFixpoint();
4725     }
4726   }
4727 
4728   /// See AbstractAttribute::updateImpl(...).
4729   ChangeStatus updateImpl(Attributor &A) override {
4730     // TODO: Once we have call site specific value information we can provide
4731     //       call site specific liveness information and then it makes
4732     //       sense to specialize attributes for call sites arguments instead of
4733     //       redirecting requests to the callee argument.
4734     Function *F = getAssociatedFunction();
4735     const IRPosition &FnPos = IRPosition::function(*F);
4736     auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos, DepClassTy::REQUIRED);
4737     return clampStateAndIndicateChange(getState(), FnAA.getState());
4738   }
4739 
4740   /// See AbstractAttribute::trackStatistics()
4741   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); }
4742 };
4743 } // namespace
4744 
4745 /// ----------------------- Instance Info ---------------------------------
4746 
4747 namespace {
4748 /// A class to hold the state of for no-capture attributes.
4749 struct AAInstanceInfoImpl : public AAInstanceInfo {
4750   AAInstanceInfoImpl(const IRPosition &IRP, Attributor &A)
4751       : AAInstanceInfo(IRP, A) {}
4752 
4753   /// See AbstractAttribute::initialize(...).
4754   void initialize(Attributor &A) override {
4755     Value &V = getAssociatedValue();
4756     if (auto *C = dyn_cast<Constant>(&V)) {
4757       if (C->isThreadDependent())
4758         indicatePessimisticFixpoint();
4759       else
4760         indicateOptimisticFixpoint();
4761       return;
4762     }
4763     if (auto *CB = dyn_cast<CallBase>(&V))
4764       if (CB->arg_size() == 0 && !CB->mayHaveSideEffects() &&
4765           !CB->mayReadFromMemory()) {
4766         indicateOptimisticFixpoint();
4767         return;
4768       }
4769   }
4770 
4771   /// See AbstractAttribute::updateImpl(...).
4772   ChangeStatus updateImpl(Attributor &A) override {
4773     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4774 
4775     Value &V = getAssociatedValue();
4776     const Function *Scope = nullptr;
4777     if (auto *I = dyn_cast<Instruction>(&V))
4778       Scope = I->getFunction();
4779     if (auto *A = dyn_cast<Argument>(&V)) {
4780       Scope = A->getParent();
4781       if (!Scope->hasLocalLinkage())
4782         return Changed;
4783     }
4784     if (!Scope)
4785       return indicateOptimisticFixpoint();
4786 
4787     auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
4788         *this, IRPosition::function(*Scope), DepClassTy::OPTIONAL);
4789     if (NoRecurseAA.isAssumedNoRecurse())
4790       return Changed;
4791 
4792     auto UsePred = [&](const Use &U, bool &Follow) {
4793       const Instruction *UserI = dyn_cast<Instruction>(U.getUser());
4794       if (!UserI || isa<GetElementPtrInst>(UserI) || isa<CastInst>(UserI) ||
4795           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
4796         Follow = true;
4797         return true;
4798       }
4799       if (isa<LoadInst>(UserI) || isa<CmpInst>(UserI) ||
4800           (isa<StoreInst>(UserI) &&
4801            cast<StoreInst>(UserI)->getValueOperand() != U.get()))
4802         return true;
4803       if (auto *CB = dyn_cast<CallBase>(UserI)) {
4804         // This check is not guaranteeing uniqueness but for now that we cannot
4805         // end up with two versions of \p U thinking it was one.
4806         if (!CB->getCalledFunction() ||
4807             !CB->getCalledFunction()->hasLocalLinkage())
4808           return true;
4809         if (!CB->isArgOperand(&U))
4810           return false;
4811         const auto &ArgInstanceInfoAA = A.getAAFor<AAInstanceInfo>(
4812             *this, IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)),
4813             DepClassTy::OPTIONAL);
4814         if (!ArgInstanceInfoAA.isAssumedUniqueForAnalysis())
4815           return false;
4816         // If this call base might reach the scope again we might forward the
4817         // argument back here. This is very conservative.
4818         if (AA::isPotentiallyReachable(A, *CB, *Scope, *this, nullptr))
4819           return false;
4820         return true;
4821       }
4822       return false;
4823     };
4824 
4825     auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
4826       if (auto *SI = dyn_cast<StoreInst>(OldU.getUser())) {
4827         auto *Ptr = SI->getPointerOperand()->stripPointerCasts();
4828         if (isa<AllocaInst>(Ptr) && AA::isDynamicallyUnique(A, *this, *Ptr))
4829           return true;
4830         auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(
4831             *SI->getFunction());
4832         if (isAllocationFn(Ptr, TLI) && AA::isDynamicallyUnique(A, *this, *Ptr))
4833           return true;
4834       }
4835       return false;
4836     };
4837 
4838     if (!A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ true,
4839                            DepClassTy::OPTIONAL,
4840                            /* IgnoreDroppableUses */ true, EquivalentUseCB))
4841       return indicatePessimisticFixpoint();
4842 
4843     return Changed;
4844   }
4845 
4846   /// See AbstractState::getAsStr().
4847   const std::string getAsStr() const override {
4848     return isAssumedUniqueForAnalysis() ? "<unique [fAa]>" : "<unknown>";
4849   }
4850 
4851   /// See AbstractAttribute::trackStatistics()
4852   void trackStatistics() const override {}
4853 };
4854 
4855 /// InstanceInfo attribute for floating values.
4856 struct AAInstanceInfoFloating : AAInstanceInfoImpl {
4857   AAInstanceInfoFloating(const IRPosition &IRP, Attributor &A)
4858       : AAInstanceInfoImpl(IRP, A) {}
4859 };
4860 
4861 /// NoCapture attribute for function arguments.
4862 struct AAInstanceInfoArgument final : AAInstanceInfoFloating {
4863   AAInstanceInfoArgument(const IRPosition &IRP, Attributor &A)
4864       : AAInstanceInfoFloating(IRP, A) {}
4865 };
4866 
4867 /// InstanceInfo attribute for call site arguments.
4868 struct AAInstanceInfoCallSiteArgument final : AAInstanceInfoImpl {
4869   AAInstanceInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
4870       : AAInstanceInfoImpl(IRP, A) {}
4871 
4872   /// See AbstractAttribute::updateImpl(...).
4873   ChangeStatus updateImpl(Attributor &A) override {
4874     // TODO: Once we have call site specific value information we can provide
4875     //       call site specific liveness information and then it makes
4876     //       sense to specialize attributes for call sites arguments instead of
4877     //       redirecting requests to the callee argument.
4878     Argument *Arg = getAssociatedArgument();
4879     if (!Arg)
4880       return indicatePessimisticFixpoint();
4881     const IRPosition &ArgPos = IRPosition::argument(*Arg);
4882     auto &ArgAA =
4883         A.getAAFor<AAInstanceInfo>(*this, ArgPos, DepClassTy::REQUIRED);
4884     return clampStateAndIndicateChange(getState(), ArgAA.getState());
4885   }
4886 };
4887 
4888 /// InstanceInfo attribute for function return value.
4889 struct AAInstanceInfoReturned final : AAInstanceInfoImpl {
4890   AAInstanceInfoReturned(const IRPosition &IRP, Attributor &A)
4891       : AAInstanceInfoImpl(IRP, A) {
4892     llvm_unreachable("InstanceInfo is not applicable to function returns!");
4893   }
4894 
4895   /// See AbstractAttribute::initialize(...).
4896   void initialize(Attributor &A) override {
4897     llvm_unreachable("InstanceInfo is not applicable to function returns!");
4898   }
4899 
4900   /// See AbstractAttribute::updateImpl(...).
4901   ChangeStatus updateImpl(Attributor &A) override {
4902     llvm_unreachable("InstanceInfo is not applicable to function returns!");
4903   }
4904 };
4905 
4906 /// InstanceInfo attribute deduction for a call site return value.
4907 struct AAInstanceInfoCallSiteReturned final : AAInstanceInfoFloating {
4908   AAInstanceInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
4909       : AAInstanceInfoFloating(IRP, A) {}
4910 };
4911 } // namespace
4912 
4913 /// ----------------------- Variable Capturing ---------------------------------
4914 
4915 namespace {
4916 /// A class to hold the state of for no-capture attributes.
4917 struct AANoCaptureImpl : public AANoCapture {
4918   AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {}
4919 
4920   /// See AbstractAttribute::initialize(...).
4921   void initialize(Attributor &A) override {
4922     if (hasAttr(getAttrKind(), /* IgnoreSubsumingPositions */ true)) {
4923       indicateOptimisticFixpoint();
4924       return;
4925     }
4926     Function *AnchorScope = getAnchorScope();
4927     if (isFnInterfaceKind() &&
4928         (!AnchorScope || !A.isFunctionIPOAmendable(*AnchorScope))) {
4929       indicatePessimisticFixpoint();
4930       return;
4931     }
4932 
4933     // You cannot "capture" null in the default address space.
4934     if (isa<ConstantPointerNull>(getAssociatedValue()) &&
4935         getAssociatedValue().getType()->getPointerAddressSpace() == 0) {
4936       indicateOptimisticFixpoint();
4937       return;
4938     }
4939 
4940     const Function *F =
4941         isArgumentPosition() ? getAssociatedFunction() : AnchorScope;
4942 
4943     // Check what state the associated function can actually capture.
4944     if (F)
4945       determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
4946     else
4947       indicatePessimisticFixpoint();
4948   }
4949 
4950   /// See AbstractAttribute::updateImpl(...).
4951   ChangeStatus updateImpl(Attributor &A) override;
4952 
4953   /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...).
4954   virtual void
4955   getDeducedAttributes(LLVMContext &Ctx,
4956                        SmallVectorImpl<Attribute> &Attrs) const override {
4957     if (!isAssumedNoCaptureMaybeReturned())
4958       return;
4959 
4960     if (isArgumentPosition()) {
4961       if (isAssumedNoCapture())
4962         Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture));
4963       else if (ManifestInternal)
4964         Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned"));
4965     }
4966   }
4967 
4968   /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known
4969   /// depending on the ability of the function associated with \p IRP to capture
4970   /// state in memory and through "returning/throwing", respectively.
4971   static void determineFunctionCaptureCapabilities(const IRPosition &IRP,
4972                                                    const Function &F,
4973                                                    BitIntegerState &State) {
4974     // TODO: Once we have memory behavior attributes we should use them here.
4975 
4976     // If we know we cannot communicate or write to memory, we do not care about
4977     // ptr2int anymore.
4978     if (F.onlyReadsMemory() && F.doesNotThrow() &&
4979         F.getReturnType()->isVoidTy()) {
4980       State.addKnownBits(NO_CAPTURE);
4981       return;
4982     }
4983 
4984     // A function cannot capture state in memory if it only reads memory, it can
4985     // however return/throw state and the state might be influenced by the
4986     // pointer value, e.g., loading from a returned pointer might reveal a bit.
4987     if (F.onlyReadsMemory())
4988       State.addKnownBits(NOT_CAPTURED_IN_MEM);
4989 
4990     // A function cannot communicate state back if it does not through
4991     // exceptions and doesn not return values.
4992     if (F.doesNotThrow() && F.getReturnType()->isVoidTy())
4993       State.addKnownBits(NOT_CAPTURED_IN_RET);
4994 
4995     // Check existing "returned" attributes.
4996     int ArgNo = IRP.getCalleeArgNo();
4997     if (F.doesNotThrow() && ArgNo >= 0) {
4998       for (unsigned u = 0, e = F.arg_size(); u < e; ++u)
4999         if (F.hasParamAttribute(u, Attribute::Returned)) {
5000           if (u == unsigned(ArgNo))
5001             State.removeAssumedBits(NOT_CAPTURED_IN_RET);
5002           else if (F.onlyReadsMemory())
5003             State.addKnownBits(NO_CAPTURE);
5004           else
5005             State.addKnownBits(NOT_CAPTURED_IN_RET);
5006           break;
5007         }
5008     }
5009   }
5010 
5011   /// See AbstractState::getAsStr().
5012   const std::string getAsStr() const override {
5013     if (isKnownNoCapture())
5014       return "known not-captured";
5015     if (isAssumedNoCapture())
5016       return "assumed not-captured";
5017     if (isKnownNoCaptureMaybeReturned())
5018       return "known not-captured-maybe-returned";
5019     if (isAssumedNoCaptureMaybeReturned())
5020       return "assumed not-captured-maybe-returned";
5021     return "assumed-captured";
5022   }
5023 
5024   /// Check the use \p U and update \p State accordingly. Return true if we
5025   /// should continue to update the state.
5026   bool checkUse(Attributor &A, AANoCapture::StateType &State, const Use &U,
5027                 bool &Follow) {
5028     Instruction *UInst = cast<Instruction>(U.getUser());
5029     LLVM_DEBUG(dbgs() << "[AANoCapture] Check use: " << *U.get() << " in "
5030                       << *UInst << "\n");
5031 
5032     // Deal with ptr2int by following uses.
5033     if (isa<PtrToIntInst>(UInst)) {
5034       LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n");
5035       return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5036                           /* Return */ true);
5037     }
5038 
5039     // For stores we already checked if we can follow them, if they make it
5040     // here we give up.
5041     if (isa<StoreInst>(UInst))
5042       return isCapturedIn(State, /* Memory */ true, /* Integer */ false,
5043                           /* Return */ false);
5044 
5045     // Explicitly catch return instructions.
5046     if (isa<ReturnInst>(UInst)) {
5047       if (UInst->getFunction() == getAnchorScope())
5048         return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5049                             /* Return */ true);
5050       return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5051                           /* Return */ true);
5052     }
5053 
5054     // For now we only use special logic for call sites. However, the tracker
5055     // itself knows about a lot of other non-capturing cases already.
5056     auto *CB = dyn_cast<CallBase>(UInst);
5057     if (!CB || !CB->isArgOperand(&U))
5058       return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5059                           /* Return */ true);
5060 
5061     unsigned ArgNo = CB->getArgOperandNo(&U);
5062     const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo);
5063     // If we have a abstract no-capture attribute for the argument we can use
5064     // it to justify a non-capture attribute here. This allows recursion!
5065     auto &ArgNoCaptureAA =
5066         A.getAAFor<AANoCapture>(*this, CSArgPos, DepClassTy::REQUIRED);
5067     if (ArgNoCaptureAA.isAssumedNoCapture())
5068       return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5069                           /* Return */ false);
5070     if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
5071       Follow = true;
5072       return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5073                           /* Return */ false);
5074     }
5075 
5076     // Lastly, we could not find a reason no-capture can be assumed so we don't.
5077     return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5078                         /* Return */ true);
5079   }
5080 
5081   /// Update \p State according to \p CapturedInMem, \p CapturedInInt, and
5082   /// \p CapturedInRet, then return true if we should continue updating the
5083   /// state.
5084   static bool isCapturedIn(AANoCapture::StateType &State, bool CapturedInMem,
5085                            bool CapturedInInt, bool CapturedInRet) {
5086     LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int "
5087                       << CapturedInInt << "|Ret " << CapturedInRet << "]\n");
5088     if (CapturedInMem)
5089       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM);
5090     if (CapturedInInt)
5091       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT);
5092     if (CapturedInRet)
5093       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET);
5094     return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
5095   }
5096 };
5097 
5098 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) {
5099   const IRPosition &IRP = getIRPosition();
5100   Value *V = isArgumentPosition() ? IRP.getAssociatedArgument()
5101                                   : &IRP.getAssociatedValue();
5102   if (!V)
5103     return indicatePessimisticFixpoint();
5104 
5105   const Function *F =
5106       isArgumentPosition() ? IRP.getAssociatedFunction() : IRP.getAnchorScope();
5107   assert(F && "Expected a function!");
5108   const IRPosition &FnPos = IRPosition::function(*F);
5109 
5110   AANoCapture::StateType T;
5111 
5112   // Readonly means we cannot capture through memory.
5113   bool IsKnown;
5114   if (AA::isAssumedReadOnly(A, FnPos, *this, IsKnown)) {
5115     T.addKnownBits(NOT_CAPTURED_IN_MEM);
5116     if (IsKnown)
5117       addKnownBits(NOT_CAPTURED_IN_MEM);
5118   }
5119 
5120   // Make sure all returned values are different than the underlying value.
5121   // TODO: we could do this in a more sophisticated way inside
5122   //       AAReturnedValues, e.g., track all values that escape through returns
5123   //       directly somehow.
5124   auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) {
5125     if (!RVAA.getState().isValidState())
5126       return false;
5127     bool SeenConstant = false;
5128     for (auto &It : RVAA.returned_values()) {
5129       if (isa<Constant>(It.first)) {
5130         if (SeenConstant)
5131           return false;
5132         SeenConstant = true;
5133       } else if (!isa<Argument>(It.first) ||
5134                  It.first == getAssociatedArgument())
5135         return false;
5136     }
5137     return true;
5138   };
5139 
5140   const auto &NoUnwindAA =
5141       A.getAAFor<AANoUnwind>(*this, FnPos, DepClassTy::OPTIONAL);
5142   if (NoUnwindAA.isAssumedNoUnwind()) {
5143     bool IsVoidTy = F->getReturnType()->isVoidTy();
5144     const AAReturnedValues *RVAA =
5145         IsVoidTy ? nullptr
5146                  : &A.getAAFor<AAReturnedValues>(*this, FnPos,
5147 
5148                                                  DepClassTy::OPTIONAL);
5149     if (IsVoidTy || CheckReturnedArgs(*RVAA)) {
5150       T.addKnownBits(NOT_CAPTURED_IN_RET);
5151       if (T.isKnown(NOT_CAPTURED_IN_MEM))
5152         return ChangeStatus::UNCHANGED;
5153       if (NoUnwindAA.isKnownNoUnwind() &&
5154           (IsVoidTy || RVAA->getState().isAtFixpoint())) {
5155         addKnownBits(NOT_CAPTURED_IN_RET);
5156         if (isKnown(NOT_CAPTURED_IN_MEM))
5157           return indicateOptimisticFixpoint();
5158       }
5159     }
5160   }
5161 
5162   auto IsDereferenceableOrNull = [&](Value *O, const DataLayout &DL) {
5163     const auto &DerefAA = A.getAAFor<AADereferenceable>(
5164         *this, IRPosition::value(*O), DepClassTy::OPTIONAL);
5165     return DerefAA.getAssumedDereferenceableBytes();
5166   };
5167 
5168   auto UseCheck = [&](const Use &U, bool &Follow) -> bool {
5169     switch (DetermineUseCaptureKind(U, IsDereferenceableOrNull)) {
5170     case UseCaptureKind::NO_CAPTURE:
5171       return true;
5172     case UseCaptureKind::MAY_CAPTURE:
5173       return checkUse(A, T, U, Follow);
5174     case UseCaptureKind::PASSTHROUGH:
5175       Follow = true;
5176       return true;
5177     }
5178     llvm_unreachable("Unexpected use capture kind!");
5179   };
5180 
5181   if (!A.checkForAllUses(UseCheck, *this, *V))
5182     return indicatePessimisticFixpoint();
5183 
5184   AANoCapture::StateType &S = getState();
5185   auto Assumed = S.getAssumed();
5186   S.intersectAssumedBits(T.getAssumed());
5187   if (!isAssumedNoCaptureMaybeReturned())
5188     return indicatePessimisticFixpoint();
5189   return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
5190                                    : ChangeStatus::CHANGED;
5191 }
5192 
5193 /// NoCapture attribute for function arguments.
5194 struct AANoCaptureArgument final : AANoCaptureImpl {
5195   AANoCaptureArgument(const IRPosition &IRP, Attributor &A)
5196       : AANoCaptureImpl(IRP, A) {}
5197 
5198   /// See AbstractAttribute::trackStatistics()
5199   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) }
5200 };
5201 
5202 /// NoCapture attribute for call site arguments.
5203 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
5204   AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A)
5205       : AANoCaptureImpl(IRP, A) {}
5206 
5207   /// See AbstractAttribute::initialize(...).
5208   void initialize(Attributor &A) override {
5209     if (Argument *Arg = getAssociatedArgument())
5210       if (Arg->hasByValAttr())
5211         indicateOptimisticFixpoint();
5212     AANoCaptureImpl::initialize(A);
5213   }
5214 
5215   /// See AbstractAttribute::updateImpl(...).
5216   ChangeStatus updateImpl(Attributor &A) override {
5217     // TODO: Once we have call site specific value information we can provide
5218     //       call site specific liveness information and then it makes
5219     //       sense to specialize attributes for call sites arguments instead of
5220     //       redirecting requests to the callee argument.
5221     Argument *Arg = getAssociatedArgument();
5222     if (!Arg)
5223       return indicatePessimisticFixpoint();
5224     const IRPosition &ArgPos = IRPosition::argument(*Arg);
5225     auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos, DepClassTy::REQUIRED);
5226     return clampStateAndIndicateChange(getState(), ArgAA.getState());
5227   }
5228 
5229   /// See AbstractAttribute::trackStatistics()
5230   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)};
5231 };
5232 
5233 /// NoCapture attribute for floating values.
5234 struct AANoCaptureFloating final : AANoCaptureImpl {
5235   AANoCaptureFloating(const IRPosition &IRP, Attributor &A)
5236       : AANoCaptureImpl(IRP, A) {}
5237 
5238   /// See AbstractAttribute::trackStatistics()
5239   void trackStatistics() const override {
5240     STATS_DECLTRACK_FLOATING_ATTR(nocapture)
5241   }
5242 };
5243 
5244 /// NoCapture attribute for function return value.
5245 struct AANoCaptureReturned final : AANoCaptureImpl {
5246   AANoCaptureReturned(const IRPosition &IRP, Attributor &A)
5247       : AANoCaptureImpl(IRP, A) {
5248     llvm_unreachable("NoCapture is not applicable to function returns!");
5249   }
5250 
5251   /// See AbstractAttribute::initialize(...).
5252   void initialize(Attributor &A) override {
5253     llvm_unreachable("NoCapture is not applicable to function returns!");
5254   }
5255 
5256   /// See AbstractAttribute::updateImpl(...).
5257   ChangeStatus updateImpl(Attributor &A) override {
5258     llvm_unreachable("NoCapture is not applicable to function returns!");
5259   }
5260 
5261   /// See AbstractAttribute::trackStatistics()
5262   void trackStatistics() const override {}
5263 };
5264 
5265 /// NoCapture attribute deduction for a call site return value.
5266 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
5267   AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A)
5268       : AANoCaptureImpl(IRP, A) {}
5269 
5270   /// See AbstractAttribute::initialize(...).
5271   void initialize(Attributor &A) override {
5272     const Function *F = getAnchorScope();
5273     // Check what state the associated function can actually capture.
5274     determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
5275   }
5276 
5277   /// See AbstractAttribute::trackStatistics()
5278   void trackStatistics() const override {
5279     STATS_DECLTRACK_CSRET_ATTR(nocapture)
5280   }
5281 };
5282 } // namespace
5283 
5284 /// ------------------ Value Simplify Attribute ----------------------------
5285 
5286 bool ValueSimplifyStateType::unionAssumed(Optional<Value *> Other) {
5287   // FIXME: Add a typecast support.
5288   SimplifiedAssociatedValue = AA::combineOptionalValuesInAAValueLatice(
5289       SimplifiedAssociatedValue, Other, Ty);
5290   if (SimplifiedAssociatedValue == Optional<Value *>(nullptr))
5291     return false;
5292 
5293   LLVM_DEBUG({
5294     if (SimplifiedAssociatedValue)
5295       dbgs() << "[ValueSimplify] is assumed to be "
5296              << **SimplifiedAssociatedValue << "\n";
5297     else
5298       dbgs() << "[ValueSimplify] is assumed to be <none>\n";
5299   });
5300   return true;
5301 }
5302 
5303 namespace {
5304 struct AAValueSimplifyImpl : AAValueSimplify {
5305   AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A)
5306       : AAValueSimplify(IRP, A) {}
5307 
5308   /// See AbstractAttribute::initialize(...).
5309   void initialize(Attributor &A) override {
5310     if (getAssociatedValue().getType()->isVoidTy())
5311       indicatePessimisticFixpoint();
5312     if (A.hasSimplificationCallback(getIRPosition()))
5313       indicatePessimisticFixpoint();
5314   }
5315 
5316   /// See AbstractAttribute::getAsStr().
5317   const std::string getAsStr() const override {
5318     LLVM_DEBUG({
5319       dbgs() << "SAV: " << (bool)SimplifiedAssociatedValue << " ";
5320       if (SimplifiedAssociatedValue && *SimplifiedAssociatedValue)
5321         dbgs() << "SAV: " << **SimplifiedAssociatedValue << " ";
5322     });
5323     return isValidState() ? (isAtFixpoint() ? "simplified" : "maybe-simple")
5324                           : "not-simple";
5325   }
5326 
5327   /// See AbstractAttribute::trackStatistics()
5328   void trackStatistics() const override {}
5329 
5330   /// See AAValueSimplify::getAssumedSimplifiedValue()
5331   Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override {
5332     return SimplifiedAssociatedValue;
5333   }
5334 
5335   /// Ensure the return value is \p V with type \p Ty, if not possible return
5336   /// nullptr. If \p Check is true we will only verify such an operation would
5337   /// suceed and return a non-nullptr value if that is the case. No IR is
5338   /// generated or modified.
5339   static Value *ensureType(Attributor &A, Value &V, Type &Ty, Instruction *CtxI,
5340                            bool Check) {
5341     if (auto *TypedV = AA::getWithType(V, Ty))
5342       return TypedV;
5343     if (CtxI && V.getType()->canLosslesslyBitCastTo(&Ty))
5344       return Check ? &V
5345                    : BitCastInst::CreatePointerBitCastOrAddrSpaceCast(&V, &Ty,
5346                                                                       "", CtxI);
5347     return nullptr;
5348   }
5349 
5350   /// Reproduce \p I with type \p Ty or return nullptr if that is not posisble.
5351   /// If \p Check is true we will only verify such an operation would suceed and
5352   /// return a non-nullptr value if that is the case. No IR is generated or
5353   /// modified.
5354   static Value *reproduceInst(Attributor &A,
5355                               const AbstractAttribute &QueryingAA,
5356                               Instruction &I, Type &Ty, Instruction *CtxI,
5357                               bool Check, ValueToValueMapTy &VMap) {
5358     assert(CtxI && "Cannot reproduce an instruction without context!");
5359     if (Check && (I.mayReadFromMemory() ||
5360                   !isSafeToSpeculativelyExecute(&I, CtxI, /* DT */ nullptr,
5361                                                 /* TLI */ nullptr)))
5362       return nullptr;
5363     for (Value *Op : I.operands()) {
5364       Value *NewOp = reproduceValue(A, QueryingAA, *Op, Ty, CtxI, Check, VMap);
5365       if (!NewOp) {
5366         assert(Check && "Manifest of new value unexpectedly failed!");
5367         return nullptr;
5368       }
5369       if (!Check)
5370         VMap[Op] = NewOp;
5371     }
5372     if (Check)
5373       return &I;
5374 
5375     Instruction *CloneI = I.clone();
5376     // TODO: Try to salvage debug information here.
5377     CloneI->setDebugLoc(DebugLoc());
5378     VMap[&I] = CloneI;
5379     CloneI->insertBefore(CtxI);
5380     RemapInstruction(CloneI, VMap);
5381     return CloneI;
5382   }
5383 
5384   /// Reproduce \p V with type \p Ty or return nullptr if that is not posisble.
5385   /// If \p Check is true we will only verify such an operation would suceed and
5386   /// return a non-nullptr value if that is the case. No IR is generated or
5387   /// modified.
5388   static Value *reproduceValue(Attributor &A,
5389                                const AbstractAttribute &QueryingAA, Value &V,
5390                                Type &Ty, Instruction *CtxI, bool Check,
5391                                ValueToValueMapTy &VMap) {
5392     if (const auto &NewV = VMap.lookup(&V))
5393       return NewV;
5394     bool UsedAssumedInformation = false;
5395     Optional<Value *> SimpleV = A.getAssumedSimplified(
5396         V, QueryingAA, UsedAssumedInformation, AA::Interprocedural);
5397     if (!SimpleV.has_value())
5398       return PoisonValue::get(&Ty);
5399     Value *EffectiveV = &V;
5400     if (SimpleV.value())
5401       EffectiveV = SimpleV.value();
5402     if (auto *C = dyn_cast<Constant>(EffectiveV))
5403       return C;
5404     if (CtxI && AA::isValidAtPosition(AA::ValueAndContext(*EffectiveV, *CtxI),
5405                                       A.getInfoCache()))
5406       return ensureType(A, *EffectiveV, Ty, CtxI, Check);
5407     if (auto *I = dyn_cast<Instruction>(EffectiveV))
5408       if (Value *NewV = reproduceInst(A, QueryingAA, *I, Ty, CtxI, Check, VMap))
5409         return ensureType(A, *NewV, Ty, CtxI, Check);
5410     return nullptr;
5411   }
5412 
5413   /// Return a value we can use as replacement for the associated one, or
5414   /// nullptr if we don't have one that makes sense.
5415   Value *manifestReplacementValue(Attributor &A, Instruction *CtxI) const {
5416     Value *NewV = SimplifiedAssociatedValue
5417                       ? SimplifiedAssociatedValue.value()
5418                       : UndefValue::get(getAssociatedType());
5419     if (NewV && NewV != &getAssociatedValue()) {
5420       ValueToValueMapTy VMap;
5421       // First verify we can reprduce the value with the required type at the
5422       // context location before we actually start modifying the IR.
5423       if (reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI,
5424                          /* CheckOnly */ true, VMap))
5425         return reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI,
5426                               /* CheckOnly */ false, VMap);
5427     }
5428     return nullptr;
5429   }
5430 
5431   /// Helper function for querying AAValueSimplify and updating candicate.
5432   /// \param IRP The value position we are trying to unify with SimplifiedValue
5433   bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA,
5434                       const IRPosition &IRP, bool Simplify = true) {
5435     bool UsedAssumedInformation = false;
5436     Optional<Value *> QueryingValueSimplified = &IRP.getAssociatedValue();
5437     if (Simplify)
5438       QueryingValueSimplified = A.getAssumedSimplified(
5439           IRP, QueryingAA, UsedAssumedInformation, AA::Interprocedural);
5440     return unionAssumed(QueryingValueSimplified);
5441   }
5442 
5443   /// Returns a candidate is found or not
5444   template <typename AAType> bool askSimplifiedValueFor(Attributor &A) {
5445     if (!getAssociatedValue().getType()->isIntegerTy())
5446       return false;
5447 
5448     // This will also pass the call base context.
5449     const auto &AA =
5450         A.getAAFor<AAType>(*this, getIRPosition(), DepClassTy::NONE);
5451 
5452     Optional<Constant *> COpt = AA.getAssumedConstant(A);
5453 
5454     if (!COpt) {
5455       SimplifiedAssociatedValue = llvm::None;
5456       A.recordDependence(AA, *this, DepClassTy::OPTIONAL);
5457       return true;
5458     }
5459     if (auto *C = *COpt) {
5460       SimplifiedAssociatedValue = C;
5461       A.recordDependence(AA, *this, DepClassTy::OPTIONAL);
5462       return true;
5463     }
5464     return false;
5465   }
5466 
5467   bool askSimplifiedValueForOtherAAs(Attributor &A) {
5468     if (askSimplifiedValueFor<AAValueConstantRange>(A))
5469       return true;
5470     if (askSimplifiedValueFor<AAPotentialConstantValues>(A))
5471       return true;
5472     return false;
5473   }
5474 
5475   /// See AbstractAttribute::manifest(...).
5476   ChangeStatus manifest(Attributor &A) override {
5477     ChangeStatus Changed = ChangeStatus::UNCHANGED;
5478     for (auto &U : getAssociatedValue().uses()) {
5479       // Check if we need to adjust the insertion point to make sure the IR is
5480       // valid.
5481       Instruction *IP = dyn_cast<Instruction>(U.getUser());
5482       if (auto *PHI = dyn_cast_or_null<PHINode>(IP))
5483         IP = PHI->getIncomingBlock(U)->getTerminator();
5484       if (auto *NewV = manifestReplacementValue(A, IP)) {
5485         LLVM_DEBUG(dbgs() << "[ValueSimplify] " << getAssociatedValue()
5486                           << " -> " << *NewV << " :: " << *this << "\n");
5487         if (A.changeUseAfterManifest(U, *NewV))
5488           Changed = ChangeStatus::CHANGED;
5489       }
5490     }
5491 
5492     return Changed | AAValueSimplify::manifest(A);
5493   }
5494 
5495   /// See AbstractState::indicatePessimisticFixpoint(...).
5496   ChangeStatus indicatePessimisticFixpoint() override {
5497     SimplifiedAssociatedValue = &getAssociatedValue();
5498     return AAValueSimplify::indicatePessimisticFixpoint();
5499   }
5500 };
5501 
5502 struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
5503   AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A)
5504       : AAValueSimplifyImpl(IRP, A) {}
5505 
5506   void initialize(Attributor &A) override {
5507     AAValueSimplifyImpl::initialize(A);
5508     if (!getAnchorScope() || getAnchorScope()->isDeclaration())
5509       indicatePessimisticFixpoint();
5510     if (hasAttr({Attribute::InAlloca, Attribute::Preallocated,
5511                  Attribute::StructRet, Attribute::Nest, Attribute::ByVal},
5512                 /* IgnoreSubsumingPositions */ true))
5513       indicatePessimisticFixpoint();
5514   }
5515 
5516   /// See AbstractAttribute::updateImpl(...).
5517   ChangeStatus updateImpl(Attributor &A) override {
5518     // Byval is only replacable if it is readonly otherwise we would write into
5519     // the replaced value and not the copy that byval creates implicitly.
5520     Argument *Arg = getAssociatedArgument();
5521     if (Arg->hasByValAttr()) {
5522       // TODO: We probably need to verify synchronization is not an issue, e.g.,
5523       //       there is no race by not copying a constant byval.
5524       bool IsKnown;
5525       if (!AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
5526         return indicatePessimisticFixpoint();
5527     }
5528 
5529     auto Before = SimplifiedAssociatedValue;
5530 
5531     auto PredForCallSite = [&](AbstractCallSite ACS) {
5532       const IRPosition &ACSArgPos =
5533           IRPosition::callsite_argument(ACS, getCallSiteArgNo());
5534       // Check if a coresponding argument was found or if it is on not
5535       // associated (which can happen for callback calls).
5536       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
5537         return false;
5538 
5539       // Simplify the argument operand explicitly and check if the result is
5540       // valid in the current scope. This avoids refering to simplified values
5541       // in other functions, e.g., we don't want to say a an argument in a
5542       // static function is actually an argument in a different function.
5543       bool UsedAssumedInformation = false;
5544       Optional<Constant *> SimpleArgOp =
5545           A.getAssumedConstant(ACSArgPos, *this, UsedAssumedInformation);
5546       if (!SimpleArgOp)
5547         return true;
5548       if (!SimpleArgOp.value())
5549         return false;
5550       if (!AA::isDynamicallyUnique(A, *this, **SimpleArgOp))
5551         return false;
5552       return unionAssumed(*SimpleArgOp);
5553     };
5554 
5555     // Generate a answer specific to a call site context.
5556     bool Success;
5557     bool UsedAssumedInformation = false;
5558     if (hasCallBaseContext() &&
5559         getCallBaseContext()->getCalledFunction() == Arg->getParent())
5560       Success = PredForCallSite(
5561           AbstractCallSite(&getCallBaseContext()->getCalledOperandUse()));
5562     else
5563       Success = A.checkForAllCallSites(PredForCallSite, *this, true,
5564                                        UsedAssumedInformation);
5565 
5566     if (!Success)
5567       if (!askSimplifiedValueForOtherAAs(A))
5568         return indicatePessimisticFixpoint();
5569 
5570     // If a candicate was found in this update, return CHANGED.
5571     return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
5572                                                : ChangeStatus ::CHANGED;
5573   }
5574 
5575   /// See AbstractAttribute::trackStatistics()
5576   void trackStatistics() const override {
5577     STATS_DECLTRACK_ARG_ATTR(value_simplify)
5578   }
5579 };
5580 
5581 struct AAValueSimplifyReturned : AAValueSimplifyImpl {
5582   AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A)
5583       : AAValueSimplifyImpl(IRP, A) {}
5584 
5585   /// See AAValueSimplify::getAssumedSimplifiedValue()
5586   Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override {
5587     if (!isValidState())
5588       return nullptr;
5589     return SimplifiedAssociatedValue;
5590   }
5591 
5592   /// See AbstractAttribute::updateImpl(...).
5593   ChangeStatus updateImpl(Attributor &A) override {
5594     auto Before = SimplifiedAssociatedValue;
5595 
5596     auto ReturnInstCB = [&](Instruction &I) {
5597       auto &RI = cast<ReturnInst>(I);
5598       return checkAndUpdate(
5599           A, *this,
5600           IRPosition::value(*RI.getReturnValue(), getCallBaseContext()));
5601     };
5602 
5603     bool UsedAssumedInformation = false;
5604     if (!A.checkForAllInstructions(ReturnInstCB, *this, {Instruction::Ret},
5605                                    UsedAssumedInformation))
5606       if (!askSimplifiedValueForOtherAAs(A))
5607         return indicatePessimisticFixpoint();
5608 
5609     // If a candicate was found in this update, return CHANGED.
5610     return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
5611                                                : ChangeStatus ::CHANGED;
5612   }
5613 
5614   ChangeStatus manifest(Attributor &A) override {
5615     // We queried AAValueSimplify for the returned values so they will be
5616     // replaced if a simplified form was found. Nothing to do here.
5617     return ChangeStatus::UNCHANGED;
5618   }
5619 
5620   /// See AbstractAttribute::trackStatistics()
5621   void trackStatistics() const override {
5622     STATS_DECLTRACK_FNRET_ATTR(value_simplify)
5623   }
5624 };
5625 
5626 struct AAValueSimplifyFloating : AAValueSimplifyImpl {
5627   AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A)
5628       : AAValueSimplifyImpl(IRP, A) {}
5629 
5630   /// See AbstractAttribute::initialize(...).
5631   void initialize(Attributor &A) override {
5632     AAValueSimplifyImpl::initialize(A);
5633     Value &V = getAnchorValue();
5634 
5635     // TODO: add other stuffs
5636     if (isa<Constant>(V))
5637       indicatePessimisticFixpoint();
5638   }
5639 
5640   /// See AbstractAttribute::updateImpl(...).
5641   ChangeStatus updateImpl(Attributor &A) override {
5642     auto Before = SimplifiedAssociatedValue;
5643     if (!askSimplifiedValueForOtherAAs(A))
5644       return indicatePessimisticFixpoint();
5645 
5646     // If a candicate was found in this update, return CHANGED.
5647     return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
5648                                                : ChangeStatus ::CHANGED;
5649   }
5650 
5651   /// See AbstractAttribute::trackStatistics()
5652   void trackStatistics() const override {
5653     STATS_DECLTRACK_FLOATING_ATTR(value_simplify)
5654   }
5655 };
5656 
5657 struct AAValueSimplifyFunction : AAValueSimplifyImpl {
5658   AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A)
5659       : AAValueSimplifyImpl(IRP, A) {}
5660 
5661   /// See AbstractAttribute::initialize(...).
5662   void initialize(Attributor &A) override {
5663     SimplifiedAssociatedValue = nullptr;
5664     indicateOptimisticFixpoint();
5665   }
5666   /// See AbstractAttribute::initialize(...).
5667   ChangeStatus updateImpl(Attributor &A) override {
5668     llvm_unreachable(
5669         "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
5670   }
5671   /// See AbstractAttribute::trackStatistics()
5672   void trackStatistics() const override {
5673     STATS_DECLTRACK_FN_ATTR(value_simplify)
5674   }
5675 };
5676 
5677 struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
5678   AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A)
5679       : AAValueSimplifyFunction(IRP, A) {}
5680   /// See AbstractAttribute::trackStatistics()
5681   void trackStatistics() const override {
5682     STATS_DECLTRACK_CS_ATTR(value_simplify)
5683   }
5684 };
5685 
5686 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyImpl {
5687   AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A)
5688       : AAValueSimplifyImpl(IRP, A) {}
5689 
5690   void initialize(Attributor &A) override {
5691     AAValueSimplifyImpl::initialize(A);
5692     Function *Fn = getAssociatedFunction();
5693     if (!Fn) {
5694       indicatePessimisticFixpoint();
5695       return;
5696     }
5697     for (Argument &Arg : Fn->args()) {
5698       if (Arg.hasReturnedAttr()) {
5699         auto IRP = IRPosition::callsite_argument(*cast<CallBase>(getCtxI()),
5700                                                  Arg.getArgNo());
5701         if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE_ARGUMENT &&
5702             checkAndUpdate(A, *this, IRP))
5703           indicateOptimisticFixpoint();
5704         else
5705           indicatePessimisticFixpoint();
5706         return;
5707       }
5708     }
5709   }
5710 
5711   /// See AbstractAttribute::updateImpl(...).
5712   ChangeStatus updateImpl(Attributor &A) override {
5713     auto Before = SimplifiedAssociatedValue;
5714     auto &RetAA = A.getAAFor<AAReturnedValues>(
5715         *this, IRPosition::function(*getAssociatedFunction()),
5716         DepClassTy::REQUIRED);
5717     auto PredForReturned =
5718         [&](Value &RetVal, const SmallSetVector<ReturnInst *, 4> &RetInsts) {
5719           bool UsedAssumedInformation = false;
5720           Optional<Value *> CSRetVal = A.translateArgumentToCallSiteContent(
5721               &RetVal, *cast<CallBase>(getCtxI()), *this,
5722               UsedAssumedInformation);
5723           SimplifiedAssociatedValue = AA::combineOptionalValuesInAAValueLatice(
5724               SimplifiedAssociatedValue, CSRetVal, getAssociatedType());
5725           return SimplifiedAssociatedValue != Optional<Value *>(nullptr);
5726         };
5727     if (!RetAA.checkForAllReturnedValuesAndReturnInsts(PredForReturned))
5728       if (!askSimplifiedValueForOtherAAs(A))
5729         return indicatePessimisticFixpoint();
5730     return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
5731                                                : ChangeStatus ::CHANGED;
5732   }
5733 
5734   void trackStatistics() const override {
5735     STATS_DECLTRACK_CSRET_ATTR(value_simplify)
5736   }
5737 };
5738 
5739 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
5740   AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A)
5741       : AAValueSimplifyFloating(IRP, A) {}
5742 
5743   /// See AbstractAttribute::manifest(...).
5744   ChangeStatus manifest(Attributor &A) override {
5745     ChangeStatus Changed = ChangeStatus::UNCHANGED;
5746     // TODO: We should avoid simplification duplication to begin with.
5747     auto *FloatAA = A.lookupAAFor<AAValueSimplify>(
5748         IRPosition::value(getAssociatedValue()), this, DepClassTy::NONE);
5749     if (FloatAA && FloatAA->getState().isValidState())
5750       return Changed;
5751 
5752     if (auto *NewV = manifestReplacementValue(A, getCtxI())) {
5753       Use &U = cast<CallBase>(&getAnchorValue())
5754                    ->getArgOperandUse(getCallSiteArgNo());
5755       if (A.changeUseAfterManifest(U, *NewV))
5756         Changed = ChangeStatus::CHANGED;
5757     }
5758 
5759     return Changed | AAValueSimplify::manifest(A);
5760   }
5761 
5762   void trackStatistics() const override {
5763     STATS_DECLTRACK_CSARG_ATTR(value_simplify)
5764   }
5765 };
5766 } // namespace
5767 
5768 /// ----------------------- Heap-To-Stack Conversion ---------------------------
5769 namespace {
5770 struct AAHeapToStackFunction final : public AAHeapToStack {
5771 
5772   struct AllocationInfo {
5773     /// The call that allocates the memory.
5774     CallBase *const CB;
5775 
5776     /// The library function id for the allocation.
5777     LibFunc LibraryFunctionId = NotLibFunc;
5778 
5779     /// The status wrt. a rewrite.
5780     enum {
5781       STACK_DUE_TO_USE,
5782       STACK_DUE_TO_FREE,
5783       INVALID,
5784     } Status = STACK_DUE_TO_USE;
5785 
5786     /// Flag to indicate if we encountered a use that might free this allocation
5787     /// but which is not in the deallocation infos.
5788     bool HasPotentiallyFreeingUnknownUses = false;
5789 
5790     /// Flag to indicate that we should place the new alloca in the function
5791     /// entry block rather than where the call site (CB) is.
5792     bool MoveAllocaIntoEntry = true;
5793 
5794     /// The set of free calls that use this allocation.
5795     SmallSetVector<CallBase *, 1> PotentialFreeCalls{};
5796   };
5797 
5798   struct DeallocationInfo {
5799     /// The call that deallocates the memory.
5800     CallBase *const CB;
5801 
5802     /// Flag to indicate if we don't know all objects this deallocation might
5803     /// free.
5804     bool MightFreeUnknownObjects = false;
5805 
5806     /// The set of allocation calls that are potentially freed.
5807     SmallSetVector<CallBase *, 1> PotentialAllocationCalls{};
5808   };
5809 
5810   AAHeapToStackFunction(const IRPosition &IRP, Attributor &A)
5811       : AAHeapToStack(IRP, A) {}
5812 
5813   ~AAHeapToStackFunction() {
5814     // Ensure we call the destructor so we release any memory allocated in the
5815     // sets.
5816     for (auto &It : AllocationInfos)
5817       It.second->~AllocationInfo();
5818     for (auto &It : DeallocationInfos)
5819       It.second->~DeallocationInfo();
5820   }
5821 
5822   void initialize(Attributor &A) override {
5823     AAHeapToStack::initialize(A);
5824 
5825     const Function *F = getAnchorScope();
5826     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
5827 
5828     auto AllocationIdentifierCB = [&](Instruction &I) {
5829       CallBase *CB = dyn_cast<CallBase>(&I);
5830       if (!CB)
5831         return true;
5832       if (isFreeCall(CB, TLI)) {
5833         DeallocationInfos[CB] = new (A.Allocator) DeallocationInfo{CB};
5834         return true;
5835       }
5836       // To do heap to stack, we need to know that the allocation itself is
5837       // removable once uses are rewritten, and that we can initialize the
5838       // alloca to the same pattern as the original allocation result.
5839       if (isAllocationFn(CB, TLI) && isAllocRemovable(CB, TLI)) {
5840         auto *I8Ty = Type::getInt8Ty(CB->getParent()->getContext());
5841         if (nullptr != getInitialValueOfAllocation(CB, TLI, I8Ty)) {
5842           AllocationInfo *AI = new (A.Allocator) AllocationInfo{CB};
5843           AllocationInfos[CB] = AI;
5844           if (TLI)
5845             TLI->getLibFunc(*CB, AI->LibraryFunctionId);
5846         }
5847       }
5848       return true;
5849     };
5850 
5851     bool UsedAssumedInformation = false;
5852     bool Success = A.checkForAllCallLikeInstructions(
5853         AllocationIdentifierCB, *this, UsedAssumedInformation,
5854         /* CheckBBLivenessOnly */ false,
5855         /* CheckPotentiallyDead */ true);
5856     (void)Success;
5857     assert(Success && "Did not expect the call base visit callback to fail!");
5858 
5859     Attributor::SimplifictionCallbackTy SCB =
5860         [](const IRPosition &, const AbstractAttribute *,
5861            bool &) -> Optional<Value *> { return nullptr; };
5862     for (const auto &It : AllocationInfos)
5863       A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first),
5864                                        SCB);
5865     for (const auto &It : DeallocationInfos)
5866       A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first),
5867                                        SCB);
5868   }
5869 
5870   const std::string getAsStr() const override {
5871     unsigned NumH2SMallocs = 0, NumInvalidMallocs = 0;
5872     for (const auto &It : AllocationInfos) {
5873       if (It.second->Status == AllocationInfo::INVALID)
5874         ++NumInvalidMallocs;
5875       else
5876         ++NumH2SMallocs;
5877     }
5878     return "[H2S] Mallocs Good/Bad: " + std::to_string(NumH2SMallocs) + "/" +
5879            std::to_string(NumInvalidMallocs);
5880   }
5881 
5882   /// See AbstractAttribute::trackStatistics().
5883   void trackStatistics() const override {
5884     STATS_DECL(
5885         MallocCalls, Function,
5886         "Number of malloc/calloc/aligned_alloc calls converted to allocas");
5887     for (auto &It : AllocationInfos)
5888       if (It.second->Status != AllocationInfo::INVALID)
5889         ++BUILD_STAT_NAME(MallocCalls, Function);
5890   }
5891 
5892   bool isAssumedHeapToStack(const CallBase &CB) const override {
5893     if (isValidState())
5894       if (AllocationInfo *AI =
5895               AllocationInfos.lookup(const_cast<CallBase *>(&CB)))
5896         return AI->Status != AllocationInfo::INVALID;
5897     return false;
5898   }
5899 
5900   bool isAssumedHeapToStackRemovedFree(CallBase &CB) const override {
5901     if (!isValidState())
5902       return false;
5903 
5904     for (auto &It : AllocationInfos) {
5905       AllocationInfo &AI = *It.second;
5906       if (AI.Status == AllocationInfo::INVALID)
5907         continue;
5908 
5909       if (AI.PotentialFreeCalls.count(&CB))
5910         return true;
5911     }
5912 
5913     return false;
5914   }
5915 
5916   ChangeStatus manifest(Attributor &A) override {
5917     assert(getState().isValidState() &&
5918            "Attempted to manifest an invalid state!");
5919 
5920     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
5921     Function *F = getAnchorScope();
5922     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
5923 
5924     for (auto &It : AllocationInfos) {
5925       AllocationInfo &AI = *It.second;
5926       if (AI.Status == AllocationInfo::INVALID)
5927         continue;
5928 
5929       for (CallBase *FreeCall : AI.PotentialFreeCalls) {
5930         LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n");
5931         A.deleteAfterManifest(*FreeCall);
5932         HasChanged = ChangeStatus::CHANGED;
5933       }
5934 
5935       LLVM_DEBUG(dbgs() << "H2S: Removing malloc-like call: " << *AI.CB
5936                         << "\n");
5937 
5938       auto Remark = [&](OptimizationRemark OR) {
5939         LibFunc IsAllocShared;
5940         if (TLI->getLibFunc(*AI.CB, IsAllocShared))
5941           if (IsAllocShared == LibFunc___kmpc_alloc_shared)
5942             return OR << "Moving globalized variable to the stack.";
5943         return OR << "Moving memory allocation from the heap to the stack.";
5944       };
5945       if (AI.LibraryFunctionId == LibFunc___kmpc_alloc_shared)
5946         A.emitRemark<OptimizationRemark>(AI.CB, "OMP110", Remark);
5947       else
5948         A.emitRemark<OptimizationRemark>(AI.CB, "HeapToStack", Remark);
5949 
5950       const DataLayout &DL = A.getInfoCache().getDL();
5951       Value *Size;
5952       Optional<APInt> SizeAPI = getSize(A, *this, AI);
5953       if (SizeAPI) {
5954         Size = ConstantInt::get(AI.CB->getContext(), *SizeAPI);
5955       } else {
5956         LLVMContext &Ctx = AI.CB->getContext();
5957         ObjectSizeOpts Opts;
5958         ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, Opts);
5959         SizeOffsetEvalType SizeOffsetPair = Eval.compute(AI.CB);
5960         assert(SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown() &&
5961                cast<ConstantInt>(SizeOffsetPair.second)->isZero());
5962         Size = SizeOffsetPair.first;
5963       }
5964 
5965       Instruction *IP =
5966           AI.MoveAllocaIntoEntry ? &F->getEntryBlock().front() : AI.CB;
5967 
5968       Align Alignment(1);
5969       if (MaybeAlign RetAlign = AI.CB->getRetAlign())
5970         Alignment = std::max(Alignment, *RetAlign);
5971       if (Value *Align = getAllocAlignment(AI.CB, TLI)) {
5972         Optional<APInt> AlignmentAPI = getAPInt(A, *this, *Align);
5973         assert(AlignmentAPI && AlignmentAPI.value().getZExtValue() > 0 &&
5974                "Expected an alignment during manifest!");
5975         Alignment = std::max(
5976             Alignment, assumeAligned(AlignmentAPI.value().getZExtValue()));
5977       }
5978 
5979       // TODO: Hoist the alloca towards the function entry.
5980       unsigned AS = DL.getAllocaAddrSpace();
5981       Instruction *Alloca =
5982           new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment,
5983                          AI.CB->getName() + ".h2s", IP);
5984 
5985       if (Alloca->getType() != AI.CB->getType())
5986         Alloca = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
5987             Alloca, AI.CB->getType(), "malloc_cast", AI.CB);
5988 
5989       auto *I8Ty = Type::getInt8Ty(F->getContext());
5990       auto *InitVal = getInitialValueOfAllocation(AI.CB, TLI, I8Ty);
5991       assert(InitVal &&
5992              "Must be able to materialize initial memory state of allocation");
5993 
5994       A.changeAfterManifest(IRPosition::inst(*AI.CB), *Alloca);
5995 
5996       if (auto *II = dyn_cast<InvokeInst>(AI.CB)) {
5997         auto *NBB = II->getNormalDest();
5998         BranchInst::Create(NBB, AI.CB->getParent());
5999         A.deleteAfterManifest(*AI.CB);
6000       } else {
6001         A.deleteAfterManifest(*AI.CB);
6002       }
6003 
6004       // Initialize the alloca with the same value as used by the allocation
6005       // function.  We can skip undef as the initial value of an alloc is
6006       // undef, and the memset would simply end up being DSEd.
6007       if (!isa<UndefValue>(InitVal)) {
6008         IRBuilder<> Builder(Alloca->getNextNode());
6009         // TODO: Use alignment above if align!=1
6010         Builder.CreateMemSet(Alloca, InitVal, Size, None);
6011       }
6012       HasChanged = ChangeStatus::CHANGED;
6013     }
6014 
6015     return HasChanged;
6016   }
6017 
6018   Optional<APInt> getAPInt(Attributor &A, const AbstractAttribute &AA,
6019                            Value &V) {
6020     bool UsedAssumedInformation = false;
6021     Optional<Constant *> SimpleV =
6022         A.getAssumedConstant(V, AA, UsedAssumedInformation);
6023     if (!SimpleV)
6024       return APInt(64, 0);
6025     if (auto *CI = dyn_cast_or_null<ConstantInt>(SimpleV.value()))
6026       return CI->getValue();
6027     return llvm::None;
6028   }
6029 
6030   Optional<APInt> getSize(Attributor &A, const AbstractAttribute &AA,
6031                           AllocationInfo &AI) {
6032     auto Mapper = [&](const Value *V) -> const Value * {
6033       bool UsedAssumedInformation = false;
6034       if (Optional<Constant *> SimpleV =
6035               A.getAssumedConstant(*V, AA, UsedAssumedInformation))
6036         if (*SimpleV)
6037           return *SimpleV;
6038       return V;
6039     };
6040 
6041     const Function *F = getAnchorScope();
6042     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6043     return getAllocSize(AI.CB, TLI, Mapper);
6044   }
6045 
6046   /// Collection of all malloc-like calls in a function with associated
6047   /// information.
6048   MapVector<CallBase *, AllocationInfo *> AllocationInfos;
6049 
6050   /// Collection of all free-like calls in a function with associated
6051   /// information.
6052   MapVector<CallBase *, DeallocationInfo *> DeallocationInfos;
6053 
6054   ChangeStatus updateImpl(Attributor &A) override;
6055 };
6056 
6057 ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &A) {
6058   ChangeStatus Changed = ChangeStatus::UNCHANGED;
6059   const Function *F = getAnchorScope();
6060   const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6061 
6062   const auto &LivenessAA =
6063       A.getAAFor<AAIsDead>(*this, IRPosition::function(*F), DepClassTy::NONE);
6064 
6065   MustBeExecutedContextExplorer &Explorer =
6066       A.getInfoCache().getMustBeExecutedContextExplorer();
6067 
6068   bool StackIsAccessibleByOtherThreads =
6069       A.getInfoCache().stackIsAccessibleByOtherThreads();
6070 
6071   LoopInfo *LI =
6072       A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(*F);
6073   Optional<bool> MayContainIrreducibleControl;
6074   auto IsInLoop = [&](BasicBlock &BB) {
6075     if (&F->getEntryBlock() == &BB)
6076       return false;
6077     if (!MayContainIrreducibleControl.has_value())
6078       MayContainIrreducibleControl = mayContainIrreducibleControl(*F, LI);
6079     if (MayContainIrreducibleControl.value())
6080       return true;
6081     if (!LI)
6082       return true;
6083     return LI->getLoopFor(&BB) != nullptr;
6084   };
6085 
6086   // Flag to ensure we update our deallocation information at most once per
6087   // updateImpl call and only if we use the free check reasoning.
6088   bool HasUpdatedFrees = false;
6089 
6090   auto UpdateFrees = [&]() {
6091     HasUpdatedFrees = true;
6092 
6093     for (auto &It : DeallocationInfos) {
6094       DeallocationInfo &DI = *It.second;
6095       // For now we cannot use deallocations that have unknown inputs, skip
6096       // them.
6097       if (DI.MightFreeUnknownObjects)
6098         continue;
6099 
6100       // No need to analyze dead calls, ignore them instead.
6101       bool UsedAssumedInformation = false;
6102       if (A.isAssumedDead(*DI.CB, this, &LivenessAA, UsedAssumedInformation,
6103                           /* CheckBBLivenessOnly */ true))
6104         continue;
6105 
6106       // Use the non-optimistic version to get the freed object.
6107       Value *Obj = getUnderlyingObject(DI.CB->getArgOperand(0));
6108       if (!Obj) {
6109         LLVM_DEBUG(dbgs() << "[H2S] Unknown underlying object for free!\n");
6110         DI.MightFreeUnknownObjects = true;
6111         continue;
6112       }
6113 
6114       // Free of null and undef can be ignored as no-ops (or UB in the latter
6115       // case).
6116       if (isa<ConstantPointerNull>(Obj) || isa<UndefValue>(Obj))
6117         continue;
6118 
6119       CallBase *ObjCB = dyn_cast<CallBase>(Obj);
6120       if (!ObjCB) {
6121         LLVM_DEBUG(dbgs() << "[H2S] Free of a non-call object: " << *Obj
6122                           << "\n");
6123         DI.MightFreeUnknownObjects = true;
6124         continue;
6125       }
6126 
6127       AllocationInfo *AI = AllocationInfos.lookup(ObjCB);
6128       if (!AI) {
6129         LLVM_DEBUG(dbgs() << "[H2S] Free of a non-allocation object: " << *Obj
6130                           << "\n");
6131         DI.MightFreeUnknownObjects = true;
6132         continue;
6133       }
6134 
6135       DI.PotentialAllocationCalls.insert(ObjCB);
6136     }
6137   };
6138 
6139   auto FreeCheck = [&](AllocationInfo &AI) {
6140     // If the stack is not accessible by other threads, the "must-free" logic
6141     // doesn't apply as the pointer could be shared and needs to be places in
6142     // "shareable" memory.
6143     if (!StackIsAccessibleByOtherThreads) {
6144       auto &NoSyncAA =
6145           A.getAAFor<AANoSync>(*this, getIRPosition(), DepClassTy::OPTIONAL);
6146       if (!NoSyncAA.isAssumedNoSync()) {
6147         LLVM_DEBUG(
6148             dbgs() << "[H2S] found an escaping use, stack is not accessible by "
6149                       "other threads and function is not nosync:\n");
6150         return false;
6151       }
6152     }
6153     if (!HasUpdatedFrees)
6154       UpdateFrees();
6155 
6156     // TODO: Allow multi exit functions that have different free calls.
6157     if (AI.PotentialFreeCalls.size() != 1) {
6158       LLVM_DEBUG(dbgs() << "[H2S] did not find one free call but "
6159                         << AI.PotentialFreeCalls.size() << "\n");
6160       return false;
6161     }
6162     CallBase *UniqueFree = *AI.PotentialFreeCalls.begin();
6163     DeallocationInfo *DI = DeallocationInfos.lookup(UniqueFree);
6164     if (!DI) {
6165       LLVM_DEBUG(
6166           dbgs() << "[H2S] unique free call was not known as deallocation call "
6167                  << *UniqueFree << "\n");
6168       return false;
6169     }
6170     if (DI->MightFreeUnknownObjects) {
6171       LLVM_DEBUG(
6172           dbgs() << "[H2S] unique free call might free unknown allocations\n");
6173       return false;
6174     }
6175     if (DI->PotentialAllocationCalls.empty())
6176       return true;
6177     if (DI->PotentialAllocationCalls.size() > 1) {
6178       LLVM_DEBUG(dbgs() << "[H2S] unique free call might free "
6179                         << DI->PotentialAllocationCalls.size()
6180                         << " different allocations\n");
6181       return false;
6182     }
6183     if (*DI->PotentialAllocationCalls.begin() != AI.CB) {
6184       LLVM_DEBUG(
6185           dbgs()
6186           << "[H2S] unique free call not known to free this allocation but "
6187           << **DI->PotentialAllocationCalls.begin() << "\n");
6188       return false;
6189     }
6190     Instruction *CtxI = isa<InvokeInst>(AI.CB) ? AI.CB : AI.CB->getNextNode();
6191     if (!Explorer.findInContextOf(UniqueFree, CtxI)) {
6192       LLVM_DEBUG(
6193           dbgs()
6194           << "[H2S] unique free call might not be executed with the allocation "
6195           << *UniqueFree << "\n");
6196       return false;
6197     }
6198     return true;
6199   };
6200 
6201   auto UsesCheck = [&](AllocationInfo &AI) {
6202     bool ValidUsesOnly = true;
6203 
6204     auto Pred = [&](const Use &U, bool &Follow) -> bool {
6205       Instruction *UserI = cast<Instruction>(U.getUser());
6206       if (isa<LoadInst>(UserI))
6207         return true;
6208       if (auto *SI = dyn_cast<StoreInst>(UserI)) {
6209         if (SI->getValueOperand() == U.get()) {
6210           LLVM_DEBUG(dbgs()
6211                      << "[H2S] escaping store to memory: " << *UserI << "\n");
6212           ValidUsesOnly = false;
6213         } else {
6214           // A store into the malloc'ed memory is fine.
6215         }
6216         return true;
6217       }
6218       if (auto *CB = dyn_cast<CallBase>(UserI)) {
6219         if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd())
6220           return true;
6221         if (DeallocationInfos.count(CB)) {
6222           AI.PotentialFreeCalls.insert(CB);
6223           return true;
6224         }
6225 
6226         unsigned ArgNo = CB->getArgOperandNo(&U);
6227 
6228         const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
6229             *this, IRPosition::callsite_argument(*CB, ArgNo),
6230             DepClassTy::OPTIONAL);
6231 
6232         // If a call site argument use is nofree, we are fine.
6233         const auto &ArgNoFreeAA = A.getAAFor<AANoFree>(
6234             *this, IRPosition::callsite_argument(*CB, ArgNo),
6235             DepClassTy::OPTIONAL);
6236 
6237         bool MaybeCaptured = !NoCaptureAA.isAssumedNoCapture();
6238         bool MaybeFreed = !ArgNoFreeAA.isAssumedNoFree();
6239         if (MaybeCaptured ||
6240             (AI.LibraryFunctionId != LibFunc___kmpc_alloc_shared &&
6241              MaybeFreed)) {
6242           AI.HasPotentiallyFreeingUnknownUses |= MaybeFreed;
6243 
6244           // Emit a missed remark if this is missed OpenMP globalization.
6245           auto Remark = [&](OptimizationRemarkMissed ORM) {
6246             return ORM
6247                    << "Could not move globalized variable to the stack. "
6248                       "Variable is potentially captured in call. Mark "
6249                       "parameter as `__attribute__((noescape))` to override.";
6250           };
6251 
6252           if (ValidUsesOnly &&
6253               AI.LibraryFunctionId == LibFunc___kmpc_alloc_shared)
6254             A.emitRemark<OptimizationRemarkMissed>(CB, "OMP113", Remark);
6255 
6256           LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n");
6257           ValidUsesOnly = false;
6258         }
6259         return true;
6260       }
6261 
6262       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
6263           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
6264         Follow = true;
6265         return true;
6266       }
6267       // Unknown user for which we can not track uses further (in a way that
6268       // makes sense).
6269       LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n");
6270       ValidUsesOnly = false;
6271       return true;
6272     };
6273     if (!A.checkForAllUses(Pred, *this, *AI.CB))
6274       return false;
6275     return ValidUsesOnly;
6276   };
6277 
6278   // The actual update starts here. We look at all allocations and depending on
6279   // their status perform the appropriate check(s).
6280   for (auto &It : AllocationInfos) {
6281     AllocationInfo &AI = *It.second;
6282     if (AI.Status == AllocationInfo::INVALID)
6283       continue;
6284 
6285     if (Value *Align = getAllocAlignment(AI.CB, TLI)) {
6286       Optional<APInt> APAlign = getAPInt(A, *this, *Align);
6287       if (!APAlign) {
6288         // Can't generate an alloca which respects the required alignment
6289         // on the allocation.
6290         LLVM_DEBUG(dbgs() << "[H2S] Unknown allocation alignment: " << *AI.CB
6291                           << "\n");
6292         AI.Status = AllocationInfo::INVALID;
6293         Changed = ChangeStatus::CHANGED;
6294         continue;
6295       }
6296       if (APAlign->ugt(llvm::Value::MaximumAlignment) ||
6297           !APAlign->isPowerOf2()) {
6298         LLVM_DEBUG(dbgs() << "[H2S] Invalid allocation alignment: " << APAlign
6299                           << "\n");
6300         AI.Status = AllocationInfo::INVALID;
6301         Changed = ChangeStatus::CHANGED;
6302         continue;
6303       }
6304     }
6305 
6306     Optional<APInt> Size = getSize(A, *this, AI);
6307     if (MaxHeapToStackSize != -1) {
6308       if (!Size || Size.value().ugt(MaxHeapToStackSize)) {
6309         LLVM_DEBUG({
6310           if (!Size)
6311             dbgs() << "[H2S] Unknown allocation size: " << *AI.CB << "\n";
6312           else
6313             dbgs() << "[H2S] Allocation size too large: " << *AI.CB << " vs. "
6314                    << MaxHeapToStackSize << "\n";
6315         });
6316 
6317         AI.Status = AllocationInfo::INVALID;
6318         Changed = ChangeStatus::CHANGED;
6319         continue;
6320       }
6321     }
6322 
6323     switch (AI.Status) {
6324     case AllocationInfo::STACK_DUE_TO_USE:
6325       if (UsesCheck(AI))
6326         break;
6327       AI.Status = AllocationInfo::STACK_DUE_TO_FREE;
6328       LLVM_FALLTHROUGH;
6329     case AllocationInfo::STACK_DUE_TO_FREE:
6330       if (FreeCheck(AI))
6331         break;
6332       AI.Status = AllocationInfo::INVALID;
6333       Changed = ChangeStatus::CHANGED;
6334       break;
6335     case AllocationInfo::INVALID:
6336       llvm_unreachable("Invalid allocations should never reach this point!");
6337     };
6338 
6339     // Check if we still think we can move it into the entry block.
6340     if (AI.MoveAllocaIntoEntry &&
6341         (!Size.has_value() || IsInLoop(*AI.CB->getParent())))
6342       AI.MoveAllocaIntoEntry = false;
6343   }
6344 
6345   return Changed;
6346 }
6347 } // namespace
6348 
6349 /// ----------------------- Privatizable Pointers ------------------------------
6350 namespace {
6351 struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
6352   AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A)
6353       : AAPrivatizablePtr(IRP, A), PrivatizableType(llvm::None) {}
6354 
6355   ChangeStatus indicatePessimisticFixpoint() override {
6356     AAPrivatizablePtr::indicatePessimisticFixpoint();
6357     PrivatizableType = nullptr;
6358     return ChangeStatus::CHANGED;
6359   }
6360 
6361   /// Identify the type we can chose for a private copy of the underlying
6362   /// argument. None means it is not clear yet, nullptr means there is none.
6363   virtual Optional<Type *> identifyPrivatizableType(Attributor &A) = 0;
6364 
6365   /// Return a privatizable type that encloses both T0 and T1.
6366   /// TODO: This is merely a stub for now as we should manage a mapping as well.
6367   Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) {
6368     if (!T0)
6369       return T1;
6370     if (!T1)
6371       return T0;
6372     if (T0 == T1)
6373       return T0;
6374     return nullptr;
6375   }
6376 
6377   Optional<Type *> getPrivatizableType() const override {
6378     return PrivatizableType;
6379   }
6380 
6381   const std::string getAsStr() const override {
6382     return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]";
6383   }
6384 
6385 protected:
6386   Optional<Type *> PrivatizableType;
6387 };
6388 
6389 // TODO: Do this for call site arguments (probably also other values) as well.
6390 
6391 struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
6392   AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A)
6393       : AAPrivatizablePtrImpl(IRP, A) {}
6394 
6395   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
6396   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
6397     // If this is a byval argument and we know all the call sites (so we can
6398     // rewrite them), there is no need to check them explicitly.
6399     bool UsedAssumedInformation = false;
6400     SmallVector<Attribute, 1> Attrs;
6401     getAttrs({Attribute::ByVal}, Attrs, /* IgnoreSubsumingPositions */ true);
6402     if (!Attrs.empty() &&
6403         A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this,
6404                                true, UsedAssumedInformation))
6405       return Attrs[0].getValueAsType();
6406 
6407     Optional<Type *> Ty;
6408     unsigned ArgNo = getIRPosition().getCallSiteArgNo();
6409 
6410     // Make sure the associated call site argument has the same type at all call
6411     // sites and it is an allocation we know is safe to privatize, for now that
6412     // means we only allow alloca instructions.
6413     // TODO: We can additionally analyze the accesses in the callee to  create
6414     //       the type from that information instead. That is a little more
6415     //       involved and will be done in a follow up patch.
6416     auto CallSiteCheck = [&](AbstractCallSite ACS) {
6417       IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
6418       // Check if a coresponding argument was found or if it is one not
6419       // associated (which can happen for callback calls).
6420       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
6421         return false;
6422 
6423       // Check that all call sites agree on a type.
6424       auto &PrivCSArgAA =
6425           A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos, DepClassTy::REQUIRED);
6426       Optional<Type *> CSTy = PrivCSArgAA.getPrivatizableType();
6427 
6428       LLVM_DEBUG({
6429         dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
6430         if (CSTy && CSTy.value())
6431           CSTy.value()->print(dbgs());
6432         else if (CSTy)
6433           dbgs() << "<nullptr>";
6434         else
6435           dbgs() << "<none>";
6436       });
6437 
6438       Ty = combineTypes(Ty, CSTy);
6439 
6440       LLVM_DEBUG({
6441         dbgs() << " : New Type: ";
6442         if (Ty && Ty.value())
6443           Ty.value()->print(dbgs());
6444         else if (Ty)
6445           dbgs() << "<nullptr>";
6446         else
6447           dbgs() << "<none>";
6448         dbgs() << "\n";
6449       });
6450 
6451       return !Ty || Ty.value();
6452     };
6453 
6454     if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
6455                                 UsedAssumedInformation))
6456       return nullptr;
6457     return Ty;
6458   }
6459 
6460   /// See AbstractAttribute::updateImpl(...).
6461   ChangeStatus updateImpl(Attributor &A) override {
6462     PrivatizableType = identifyPrivatizableType(A);
6463     if (!PrivatizableType)
6464       return ChangeStatus::UNCHANGED;
6465     if (!PrivatizableType.value())
6466       return indicatePessimisticFixpoint();
6467 
6468     // The dependence is optional so we don't give up once we give up on the
6469     // alignment.
6470     A.getAAFor<AAAlign>(*this, IRPosition::value(getAssociatedValue()),
6471                         DepClassTy::OPTIONAL);
6472 
6473     // Avoid arguments with padding for now.
6474     if (!getIRPosition().hasAttr(Attribute::ByVal) &&
6475         !isDenselyPacked(*PrivatizableType, A.getInfoCache().getDL())) {
6476       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n");
6477       return indicatePessimisticFixpoint();
6478     }
6479 
6480     // Collect the types that will replace the privatizable type in the function
6481     // signature.
6482     SmallVector<Type *, 16> ReplacementTypes;
6483     identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
6484 
6485     // Verify callee and caller agree on how the promoted argument would be
6486     // passed.
6487     Function &Fn = *getIRPosition().getAnchorScope();
6488     const auto *TTI =
6489         A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
6490     if (!TTI) {
6491       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Missing TTI for function "
6492                         << Fn.getName() << "\n");
6493       return indicatePessimisticFixpoint();
6494     }
6495 
6496     auto CallSiteCheck = [&](AbstractCallSite ACS) {
6497       CallBase *CB = ACS.getInstruction();
6498       return TTI->areTypesABICompatible(
6499           CB->getCaller(), CB->getCalledFunction(), ReplacementTypes);
6500     };
6501     bool UsedAssumedInformation = false;
6502     if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
6503                                 UsedAssumedInformation)) {
6504       LLVM_DEBUG(
6505           dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for "
6506                  << Fn.getName() << "\n");
6507       return indicatePessimisticFixpoint();
6508     }
6509 
6510     // Register a rewrite of the argument.
6511     Argument *Arg = getAssociatedArgument();
6512     if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
6513       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n");
6514       return indicatePessimisticFixpoint();
6515     }
6516 
6517     unsigned ArgNo = Arg->getArgNo();
6518 
6519     // Helper to check if for the given call site the associated argument is
6520     // passed to a callback where the privatization would be different.
6521     auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
6522       SmallVector<const Use *, 4> CallbackUses;
6523       AbstractCallSite::getCallbackUses(CB, CallbackUses);
6524       for (const Use *U : CallbackUses) {
6525         AbstractCallSite CBACS(U);
6526         assert(CBACS && CBACS.isCallbackCall());
6527         for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
6528           int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
6529 
6530           LLVM_DEBUG({
6531             dbgs()
6532                 << "[AAPrivatizablePtr] Argument " << *Arg
6533                 << "check if can be privatized in the context of its parent ("
6534                 << Arg->getParent()->getName()
6535                 << ")\n[AAPrivatizablePtr] because it is an argument in a "
6536                    "callback ("
6537                 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
6538                 << ")\n[AAPrivatizablePtr] " << CBArg << " : "
6539                 << CBACS.getCallArgOperand(CBArg) << " vs "
6540                 << CB.getArgOperand(ArgNo) << "\n"
6541                 << "[AAPrivatizablePtr] " << CBArg << " : "
6542                 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n";
6543           });
6544 
6545           if (CBArgNo != int(ArgNo))
6546             continue;
6547           const auto &CBArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
6548               *this, IRPosition::argument(CBArg), DepClassTy::REQUIRED);
6549           if (CBArgPrivAA.isValidState()) {
6550             auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType();
6551             if (!CBArgPrivTy)
6552               continue;
6553             if (CBArgPrivTy.value() == PrivatizableType)
6554               continue;
6555           }
6556 
6557           LLVM_DEBUG({
6558             dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
6559                    << " cannot be privatized in the context of its parent ("
6560                    << Arg->getParent()->getName()
6561                    << ")\n[AAPrivatizablePtr] because it is an argument in a "
6562                       "callback ("
6563                    << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
6564                    << ").\n[AAPrivatizablePtr] for which the argument "
6565                       "privatization is not compatible.\n";
6566           });
6567           return false;
6568         }
6569       }
6570       return true;
6571     };
6572 
6573     // Helper to check if for the given call site the associated argument is
6574     // passed to a direct call where the privatization would be different.
6575     auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
6576       CallBase *DC = cast<CallBase>(ACS.getInstruction());
6577       int DCArgNo = ACS.getCallArgOperandNo(ArgNo);
6578       assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->arg_size() &&
6579              "Expected a direct call operand for callback call operand");
6580 
6581       LLVM_DEBUG({
6582         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
6583                << " check if be privatized in the context of its parent ("
6584                << Arg->getParent()->getName()
6585                << ")\n[AAPrivatizablePtr] because it is an argument in a "
6586                   "direct call of ("
6587                << DCArgNo << "@" << DC->getCalledFunction()->getName()
6588                << ").\n";
6589       });
6590 
6591       Function *DCCallee = DC->getCalledFunction();
6592       if (unsigned(DCArgNo) < DCCallee->arg_size()) {
6593         const auto &DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
6594             *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)),
6595             DepClassTy::REQUIRED);
6596         if (DCArgPrivAA.isValidState()) {
6597           auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType();
6598           if (!DCArgPrivTy)
6599             return true;
6600           if (DCArgPrivTy.value() == PrivatizableType)
6601             return true;
6602         }
6603       }
6604 
6605       LLVM_DEBUG({
6606         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
6607                << " cannot be privatized in the context of its parent ("
6608                << Arg->getParent()->getName()
6609                << ")\n[AAPrivatizablePtr] because it is an argument in a "
6610                   "direct call of ("
6611                << ACS.getInstruction()->getCalledFunction()->getName()
6612                << ").\n[AAPrivatizablePtr] for which the argument "
6613                   "privatization is not compatible.\n";
6614       });
6615       return false;
6616     };
6617 
6618     // Helper to check if the associated argument is used at the given abstract
6619     // call site in a way that is incompatible with the privatization assumed
6620     // here.
6621     auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
6622       if (ACS.isDirectCall())
6623         return IsCompatiblePrivArgOfCallback(*ACS.getInstruction());
6624       if (ACS.isCallbackCall())
6625         return IsCompatiblePrivArgOfDirectCS(ACS);
6626       return false;
6627     };
6628 
6629     if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true,
6630                                 UsedAssumedInformation))
6631       return indicatePessimisticFixpoint();
6632 
6633     return ChangeStatus::UNCHANGED;
6634   }
6635 
6636   /// Given a type to private \p PrivType, collect the constituates (which are
6637   /// used) in \p ReplacementTypes.
6638   static void
6639   identifyReplacementTypes(Type *PrivType,
6640                            SmallVectorImpl<Type *> &ReplacementTypes) {
6641     // TODO: For now we expand the privatization type to the fullest which can
6642     //       lead to dead arguments that need to be removed later.
6643     assert(PrivType && "Expected privatizable type!");
6644 
6645     // Traverse the type, extract constituate types on the outermost level.
6646     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
6647       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
6648         ReplacementTypes.push_back(PrivStructType->getElementType(u));
6649     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
6650       ReplacementTypes.append(PrivArrayType->getNumElements(),
6651                               PrivArrayType->getElementType());
6652     } else {
6653       ReplacementTypes.push_back(PrivType);
6654     }
6655   }
6656 
6657   /// Initialize \p Base according to the type \p PrivType at position \p IP.
6658   /// The values needed are taken from the arguments of \p F starting at
6659   /// position \p ArgNo.
6660   static void createInitialization(Type *PrivType, Value &Base, Function &F,
6661                                    unsigned ArgNo, Instruction &IP) {
6662     assert(PrivType && "Expected privatizable type!");
6663 
6664     IRBuilder<NoFolder> IRB(&IP);
6665     const DataLayout &DL = F.getParent()->getDataLayout();
6666 
6667     // Traverse the type, build GEPs and stores.
6668     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
6669       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
6670       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
6671         Type *PointeeTy = PrivStructType->getElementType(u)->getPointerTo();
6672         Value *Ptr =
6673             constructPointer(PointeeTy, PrivType, &Base,
6674                              PrivStructLayout->getElementOffset(u), IRB, DL);
6675         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
6676       }
6677     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
6678       Type *PointeeTy = PrivArrayType->getElementType();
6679       Type *PointeePtrTy = PointeeTy->getPointerTo();
6680       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
6681       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
6682         Value *Ptr = constructPointer(PointeePtrTy, PrivType, &Base,
6683                                       u * PointeeTySize, IRB, DL);
6684         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
6685       }
6686     } else {
6687       new StoreInst(F.getArg(ArgNo), &Base, &IP);
6688     }
6689   }
6690 
6691   /// Extract values from \p Base according to the type \p PrivType at the
6692   /// call position \p ACS. The values are appended to \p ReplacementValues.
6693   void createReplacementValues(Align Alignment, Type *PrivType,
6694                                AbstractCallSite ACS, Value *Base,
6695                                SmallVectorImpl<Value *> &ReplacementValues) {
6696     assert(Base && "Expected base value!");
6697     assert(PrivType && "Expected privatizable type!");
6698     Instruction *IP = ACS.getInstruction();
6699 
6700     IRBuilder<NoFolder> IRB(IP);
6701     const DataLayout &DL = IP->getModule()->getDataLayout();
6702 
6703     Type *PrivPtrType = PrivType->getPointerTo();
6704     if (Base->getType() != PrivPtrType)
6705       Base = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6706           Base, PrivPtrType, "", ACS.getInstruction());
6707 
6708     // Traverse the type, build GEPs and loads.
6709     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
6710       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
6711       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
6712         Type *PointeeTy = PrivStructType->getElementType(u);
6713         Value *Ptr =
6714             constructPointer(PointeeTy->getPointerTo(), PrivType, Base,
6715                              PrivStructLayout->getElementOffset(u), IRB, DL);
6716         LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
6717         L->setAlignment(Alignment);
6718         ReplacementValues.push_back(L);
6719       }
6720     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
6721       Type *PointeeTy = PrivArrayType->getElementType();
6722       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
6723       Type *PointeePtrTy = PointeeTy->getPointerTo();
6724       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
6725         Value *Ptr = constructPointer(PointeePtrTy, PrivType, Base,
6726                                       u * PointeeTySize, IRB, DL);
6727         LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
6728         L->setAlignment(Alignment);
6729         ReplacementValues.push_back(L);
6730       }
6731     } else {
6732       LoadInst *L = new LoadInst(PrivType, Base, "", IP);
6733       L->setAlignment(Alignment);
6734       ReplacementValues.push_back(L);
6735     }
6736   }
6737 
6738   /// See AbstractAttribute::manifest(...)
6739   ChangeStatus manifest(Attributor &A) override {
6740     if (!PrivatizableType)
6741       return ChangeStatus::UNCHANGED;
6742     assert(PrivatizableType.value() && "Expected privatizable type!");
6743 
6744     // Collect all tail calls in the function as we cannot allow new allocas to
6745     // escape into tail recursion.
6746     // TODO: Be smarter about new allocas escaping into tail calls.
6747     SmallVector<CallInst *, 16> TailCalls;
6748     bool UsedAssumedInformation = false;
6749     if (!A.checkForAllInstructions(
6750             [&](Instruction &I) {
6751               CallInst &CI = cast<CallInst>(I);
6752               if (CI.isTailCall())
6753                 TailCalls.push_back(&CI);
6754               return true;
6755             },
6756             *this, {Instruction::Call}, UsedAssumedInformation))
6757       return ChangeStatus::UNCHANGED;
6758 
6759     Argument *Arg = getAssociatedArgument();
6760     // Query AAAlign attribute for alignment of associated argument to
6761     // determine the best alignment of loads.
6762     const auto &AlignAA =
6763         A.getAAFor<AAAlign>(*this, IRPosition::value(*Arg), DepClassTy::NONE);
6764 
6765     // Callback to repair the associated function. A new alloca is placed at the
6766     // beginning and initialized with the values passed through arguments. The
6767     // new alloca replaces the use of the old pointer argument.
6768     Attributor::ArgumentReplacementInfo::CalleeRepairCBTy FnRepairCB =
6769         [=](const Attributor::ArgumentReplacementInfo &ARI,
6770             Function &ReplacementFn, Function::arg_iterator ArgIt) {
6771           BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
6772           Instruction *IP = &*EntryBB.getFirstInsertionPt();
6773           const DataLayout &DL = IP->getModule()->getDataLayout();
6774           unsigned AS = DL.getAllocaAddrSpace();
6775           Instruction *AI = new AllocaInst(PrivatizableType.value(), AS,
6776                                            Arg->getName() + ".priv", IP);
6777           createInitialization(PrivatizableType.value(), *AI, ReplacementFn,
6778                                ArgIt->getArgNo(), *IP);
6779 
6780           if (AI->getType() != Arg->getType())
6781             AI = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6782                 AI, Arg->getType(), "", IP);
6783           Arg->replaceAllUsesWith(AI);
6784 
6785           for (CallInst *CI : TailCalls)
6786             CI->setTailCall(false);
6787         };
6788 
6789     // Callback to repair a call site of the associated function. The elements
6790     // of the privatizable type are loaded prior to the call and passed to the
6791     // new function version.
6792     Attributor::ArgumentReplacementInfo::ACSRepairCBTy ACSRepairCB =
6793         [=, &AlignAA](const Attributor::ArgumentReplacementInfo &ARI,
6794                       AbstractCallSite ACS,
6795                       SmallVectorImpl<Value *> &NewArgOperands) {
6796           // When no alignment is specified for the load instruction,
6797           // natural alignment is assumed.
6798           createReplacementValues(
6799               AlignAA.getAssumedAlign(), *PrivatizableType, ACS,
6800               ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()),
6801               NewArgOperands);
6802         };
6803 
6804     // Collect the types that will replace the privatizable type in the function
6805     // signature.
6806     SmallVector<Type *, 16> ReplacementTypes;
6807     identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
6808 
6809     // Register a rewrite of the argument.
6810     if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
6811                                            std::move(FnRepairCB),
6812                                            std::move(ACSRepairCB)))
6813       return ChangeStatus::CHANGED;
6814     return ChangeStatus::UNCHANGED;
6815   }
6816 
6817   /// See AbstractAttribute::trackStatistics()
6818   void trackStatistics() const override {
6819     STATS_DECLTRACK_ARG_ATTR(privatizable_ptr);
6820   }
6821 };
6822 
6823 struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl {
6824   AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A)
6825       : AAPrivatizablePtrImpl(IRP, A) {}
6826 
6827   /// See AbstractAttribute::initialize(...).
6828   virtual void initialize(Attributor &A) override {
6829     // TODO: We can privatize more than arguments.
6830     indicatePessimisticFixpoint();
6831   }
6832 
6833   ChangeStatus updateImpl(Attributor &A) override {
6834     llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::"
6835                      "updateImpl will not be called");
6836   }
6837 
6838   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
6839   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
6840     Value *Obj = getUnderlyingObject(&getAssociatedValue());
6841     if (!Obj) {
6842       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n");
6843       return nullptr;
6844     }
6845 
6846     if (auto *AI = dyn_cast<AllocaInst>(Obj))
6847       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
6848         if (CI->isOne())
6849           return AI->getAllocatedType();
6850     if (auto *Arg = dyn_cast<Argument>(Obj)) {
6851       auto &PrivArgAA = A.getAAFor<AAPrivatizablePtr>(
6852           *this, IRPosition::argument(*Arg), DepClassTy::REQUIRED);
6853       if (PrivArgAA.isAssumedPrivatizablePtr())
6854         return PrivArgAA.getPrivatizableType();
6855     }
6856 
6857     LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid "
6858                          "alloca nor privatizable argument: "
6859                       << *Obj << "!\n");
6860     return nullptr;
6861   }
6862 
6863   /// See AbstractAttribute::trackStatistics()
6864   void trackStatistics() const override {
6865     STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr);
6866   }
6867 };
6868 
6869 struct AAPrivatizablePtrCallSiteArgument final
6870     : public AAPrivatizablePtrFloating {
6871   AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A)
6872       : AAPrivatizablePtrFloating(IRP, A) {}
6873 
6874   /// See AbstractAttribute::initialize(...).
6875   void initialize(Attributor &A) override {
6876     if (getIRPosition().hasAttr(Attribute::ByVal))
6877       indicateOptimisticFixpoint();
6878   }
6879 
6880   /// See AbstractAttribute::updateImpl(...).
6881   ChangeStatus updateImpl(Attributor &A) override {
6882     PrivatizableType = identifyPrivatizableType(A);
6883     if (!PrivatizableType)
6884       return ChangeStatus::UNCHANGED;
6885     if (!PrivatizableType.value())
6886       return indicatePessimisticFixpoint();
6887 
6888     const IRPosition &IRP = getIRPosition();
6889     auto &NoCaptureAA =
6890         A.getAAFor<AANoCapture>(*this, IRP, DepClassTy::REQUIRED);
6891     if (!NoCaptureAA.isAssumedNoCapture()) {
6892       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n");
6893       return indicatePessimisticFixpoint();
6894     }
6895 
6896     auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP, DepClassTy::REQUIRED);
6897     if (!NoAliasAA.isAssumedNoAlias()) {
6898       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n");
6899       return indicatePessimisticFixpoint();
6900     }
6901 
6902     bool IsKnown;
6903     if (!AA::isAssumedReadOnly(A, IRP, *this, IsKnown)) {
6904       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n");
6905       return indicatePessimisticFixpoint();
6906     }
6907 
6908     return ChangeStatus::UNCHANGED;
6909   }
6910 
6911   /// See AbstractAttribute::trackStatistics()
6912   void trackStatistics() const override {
6913     STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr);
6914   }
6915 };
6916 
6917 struct AAPrivatizablePtrCallSiteReturned final
6918     : public AAPrivatizablePtrFloating {
6919   AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A)
6920       : AAPrivatizablePtrFloating(IRP, A) {}
6921 
6922   /// See AbstractAttribute::initialize(...).
6923   void initialize(Attributor &A) override {
6924     // TODO: We can privatize more than arguments.
6925     indicatePessimisticFixpoint();
6926   }
6927 
6928   /// See AbstractAttribute::trackStatistics()
6929   void trackStatistics() const override {
6930     STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr);
6931   }
6932 };
6933 
6934 struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating {
6935   AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A)
6936       : AAPrivatizablePtrFloating(IRP, A) {}
6937 
6938   /// See AbstractAttribute::initialize(...).
6939   void initialize(Attributor &A) override {
6940     // TODO: We can privatize more than arguments.
6941     indicatePessimisticFixpoint();
6942   }
6943 
6944   /// See AbstractAttribute::trackStatistics()
6945   void trackStatistics() const override {
6946     STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr);
6947   }
6948 };
6949 } // namespace
6950 
6951 /// -------------------- Memory Behavior Attributes ----------------------------
6952 /// Includes read-none, read-only, and write-only.
6953 /// ----------------------------------------------------------------------------
6954 namespace {
6955 struct AAMemoryBehaviorImpl : public AAMemoryBehavior {
6956   AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A)
6957       : AAMemoryBehavior(IRP, A) {}
6958 
6959   /// See AbstractAttribute::initialize(...).
6960   void initialize(Attributor &A) override {
6961     intersectAssumedBits(BEST_STATE);
6962     getKnownStateFromValue(getIRPosition(), getState());
6963     AAMemoryBehavior::initialize(A);
6964   }
6965 
6966   /// Return the memory behavior information encoded in the IR for \p IRP.
6967   static void getKnownStateFromValue(const IRPosition &IRP,
6968                                      BitIntegerState &State,
6969                                      bool IgnoreSubsumingPositions = false) {
6970     SmallVector<Attribute, 2> Attrs;
6971     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
6972     for (const Attribute &Attr : Attrs) {
6973       switch (Attr.getKindAsEnum()) {
6974       case Attribute::ReadNone:
6975         State.addKnownBits(NO_ACCESSES);
6976         break;
6977       case Attribute::ReadOnly:
6978         State.addKnownBits(NO_WRITES);
6979         break;
6980       case Attribute::WriteOnly:
6981         State.addKnownBits(NO_READS);
6982         break;
6983       default:
6984         llvm_unreachable("Unexpected attribute!");
6985       }
6986     }
6987 
6988     if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) {
6989       if (!I->mayReadFromMemory())
6990         State.addKnownBits(NO_READS);
6991       if (!I->mayWriteToMemory())
6992         State.addKnownBits(NO_WRITES);
6993     }
6994   }
6995 
6996   /// See AbstractAttribute::getDeducedAttributes(...).
6997   void getDeducedAttributes(LLVMContext &Ctx,
6998                             SmallVectorImpl<Attribute> &Attrs) const override {
6999     assert(Attrs.size() == 0);
7000     if (isAssumedReadNone())
7001       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
7002     else if (isAssumedReadOnly())
7003       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
7004     else if (isAssumedWriteOnly())
7005       Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
7006     assert(Attrs.size() <= 1);
7007   }
7008 
7009   /// See AbstractAttribute::manifest(...).
7010   ChangeStatus manifest(Attributor &A) override {
7011     if (hasAttr(Attribute::ReadNone, /* IgnoreSubsumingPositions */ true))
7012       return ChangeStatus::UNCHANGED;
7013 
7014     const IRPosition &IRP = getIRPosition();
7015 
7016     // Check if we would improve the existing attributes first.
7017     SmallVector<Attribute, 4> DeducedAttrs;
7018     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
7019     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
7020           return IRP.hasAttr(Attr.getKindAsEnum(),
7021                              /* IgnoreSubsumingPositions */ true);
7022         }))
7023       return ChangeStatus::UNCHANGED;
7024 
7025     // Clear existing attributes.
7026     IRP.removeAttrs(AttrKinds);
7027 
7028     // Use the generic manifest method.
7029     return IRAttribute::manifest(A);
7030   }
7031 
7032   /// See AbstractState::getAsStr().
7033   const std::string getAsStr() const override {
7034     if (isAssumedReadNone())
7035       return "readnone";
7036     if (isAssumedReadOnly())
7037       return "readonly";
7038     if (isAssumedWriteOnly())
7039       return "writeonly";
7040     return "may-read/write";
7041   }
7042 
7043   /// The set of IR attributes AAMemoryBehavior deals with.
7044   static const Attribute::AttrKind AttrKinds[3];
7045 };
7046 
7047 const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = {
7048     Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
7049 
7050 /// Memory behavior attribute for a floating value.
7051 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
7052   AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A)
7053       : AAMemoryBehaviorImpl(IRP, A) {}
7054 
7055   /// See AbstractAttribute::updateImpl(...).
7056   ChangeStatus updateImpl(Attributor &A) override;
7057 
7058   /// See AbstractAttribute::trackStatistics()
7059   void trackStatistics() const override {
7060     if (isAssumedReadNone())
7061       STATS_DECLTRACK_FLOATING_ATTR(readnone)
7062     else if (isAssumedReadOnly())
7063       STATS_DECLTRACK_FLOATING_ATTR(readonly)
7064     else if (isAssumedWriteOnly())
7065       STATS_DECLTRACK_FLOATING_ATTR(writeonly)
7066   }
7067 
7068 private:
7069   /// Return true if users of \p UserI might access the underlying
7070   /// variable/location described by \p U and should therefore be analyzed.
7071   bool followUsersOfUseIn(Attributor &A, const Use &U,
7072                           const Instruction *UserI);
7073 
7074   /// Update the state according to the effect of use \p U in \p UserI.
7075   void analyzeUseIn(Attributor &A, const Use &U, const Instruction *UserI);
7076 };
7077 
7078 /// Memory behavior attribute for function argument.
7079 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
7080   AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A)
7081       : AAMemoryBehaviorFloating(IRP, A) {}
7082 
7083   /// See AbstractAttribute::initialize(...).
7084   void initialize(Attributor &A) override {
7085     intersectAssumedBits(BEST_STATE);
7086     const IRPosition &IRP = getIRPosition();
7087     // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we
7088     // can query it when we use has/getAttr. That would allow us to reuse the
7089     // initialize of the base class here.
7090     bool HasByVal =
7091         IRP.hasAttr({Attribute::ByVal}, /* IgnoreSubsumingPositions */ true);
7092     getKnownStateFromValue(IRP, getState(),
7093                            /* IgnoreSubsumingPositions */ HasByVal);
7094 
7095     // Initialize the use vector with all direct uses of the associated value.
7096     Argument *Arg = getAssociatedArgument();
7097     if (!Arg || !A.isFunctionIPOAmendable(*(Arg->getParent())))
7098       indicatePessimisticFixpoint();
7099   }
7100 
7101   ChangeStatus manifest(Attributor &A) override {
7102     // TODO: Pointer arguments are not supported on vectors of pointers yet.
7103     if (!getAssociatedValue().getType()->isPointerTy())
7104       return ChangeStatus::UNCHANGED;
7105 
7106     // TODO: From readattrs.ll: "inalloca parameters are always
7107     //                           considered written"
7108     if (hasAttr({Attribute::InAlloca, Attribute::Preallocated})) {
7109       removeKnownBits(NO_WRITES);
7110       removeAssumedBits(NO_WRITES);
7111     }
7112     return AAMemoryBehaviorFloating::manifest(A);
7113   }
7114 
7115   /// See AbstractAttribute::trackStatistics()
7116   void trackStatistics() const override {
7117     if (isAssumedReadNone())
7118       STATS_DECLTRACK_ARG_ATTR(readnone)
7119     else if (isAssumedReadOnly())
7120       STATS_DECLTRACK_ARG_ATTR(readonly)
7121     else if (isAssumedWriteOnly())
7122       STATS_DECLTRACK_ARG_ATTR(writeonly)
7123   }
7124 };
7125 
7126 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
7127   AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A)
7128       : AAMemoryBehaviorArgument(IRP, A) {}
7129 
7130   /// See AbstractAttribute::initialize(...).
7131   void initialize(Attributor &A) override {
7132     // If we don't have an associated attribute this is either a variadic call
7133     // or an indirect call, either way, nothing to do here.
7134     Argument *Arg = getAssociatedArgument();
7135     if (!Arg) {
7136       indicatePessimisticFixpoint();
7137       return;
7138     }
7139     if (Arg->hasByValAttr()) {
7140       addKnownBits(NO_WRITES);
7141       removeKnownBits(NO_READS);
7142       removeAssumedBits(NO_READS);
7143     }
7144     AAMemoryBehaviorArgument::initialize(A);
7145     if (getAssociatedFunction()->isDeclaration())
7146       indicatePessimisticFixpoint();
7147   }
7148 
7149   /// See AbstractAttribute::updateImpl(...).
7150   ChangeStatus updateImpl(Attributor &A) override {
7151     // TODO: Once we have call site specific value information we can provide
7152     //       call site specific liveness liveness information and then it makes
7153     //       sense to specialize attributes for call sites arguments instead of
7154     //       redirecting requests to the callee argument.
7155     Argument *Arg = getAssociatedArgument();
7156     const IRPosition &ArgPos = IRPosition::argument(*Arg);
7157     auto &ArgAA =
7158         A.getAAFor<AAMemoryBehavior>(*this, ArgPos, DepClassTy::REQUIRED);
7159     return clampStateAndIndicateChange(getState(), ArgAA.getState());
7160   }
7161 
7162   /// See AbstractAttribute::trackStatistics()
7163   void trackStatistics() const override {
7164     if (isAssumedReadNone())
7165       STATS_DECLTRACK_CSARG_ATTR(readnone)
7166     else if (isAssumedReadOnly())
7167       STATS_DECLTRACK_CSARG_ATTR(readonly)
7168     else if (isAssumedWriteOnly())
7169       STATS_DECLTRACK_CSARG_ATTR(writeonly)
7170   }
7171 };
7172 
7173 /// Memory behavior attribute for a call site return position.
7174 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
7175   AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A)
7176       : AAMemoryBehaviorFloating(IRP, A) {}
7177 
7178   /// See AbstractAttribute::initialize(...).
7179   void initialize(Attributor &A) override {
7180     AAMemoryBehaviorImpl::initialize(A);
7181     Function *F = getAssociatedFunction();
7182     if (!F || F->isDeclaration())
7183       indicatePessimisticFixpoint();
7184   }
7185 
7186   /// See AbstractAttribute::manifest(...).
7187   ChangeStatus manifest(Attributor &A) override {
7188     // We do not annotate returned values.
7189     return ChangeStatus::UNCHANGED;
7190   }
7191 
7192   /// See AbstractAttribute::trackStatistics()
7193   void trackStatistics() const override {}
7194 };
7195 
7196 /// An AA to represent the memory behavior function attributes.
7197 struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl {
7198   AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A)
7199       : AAMemoryBehaviorImpl(IRP, A) {}
7200 
7201   /// See AbstractAttribute::updateImpl(Attributor &A).
7202   virtual ChangeStatus updateImpl(Attributor &A) override;
7203 
7204   /// See AbstractAttribute::manifest(...).
7205   ChangeStatus manifest(Attributor &A) override {
7206     Function &F = cast<Function>(getAnchorValue());
7207     if (isAssumedReadNone()) {
7208       F.removeFnAttr(Attribute::ArgMemOnly);
7209       F.removeFnAttr(Attribute::InaccessibleMemOnly);
7210       F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
7211     }
7212     return AAMemoryBehaviorImpl::manifest(A);
7213   }
7214 
7215   /// See AbstractAttribute::trackStatistics()
7216   void trackStatistics() const override {
7217     if (isAssumedReadNone())
7218       STATS_DECLTRACK_FN_ATTR(readnone)
7219     else if (isAssumedReadOnly())
7220       STATS_DECLTRACK_FN_ATTR(readonly)
7221     else if (isAssumedWriteOnly())
7222       STATS_DECLTRACK_FN_ATTR(writeonly)
7223   }
7224 };
7225 
7226 /// AAMemoryBehavior attribute for call sites.
7227 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl {
7228   AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A)
7229       : AAMemoryBehaviorImpl(IRP, A) {}
7230 
7231   /// See AbstractAttribute::initialize(...).
7232   void initialize(Attributor &A) override {
7233     AAMemoryBehaviorImpl::initialize(A);
7234     Function *F = getAssociatedFunction();
7235     if (!F || F->isDeclaration())
7236       indicatePessimisticFixpoint();
7237   }
7238 
7239   /// See AbstractAttribute::updateImpl(...).
7240   ChangeStatus updateImpl(Attributor &A) override {
7241     // TODO: Once we have call site specific value information we can provide
7242     //       call site specific liveness liveness information and then it makes
7243     //       sense to specialize attributes for call sites arguments instead of
7244     //       redirecting requests to the callee argument.
7245     Function *F = getAssociatedFunction();
7246     const IRPosition &FnPos = IRPosition::function(*F);
7247     auto &FnAA =
7248         A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::REQUIRED);
7249     return clampStateAndIndicateChange(getState(), FnAA.getState());
7250   }
7251 
7252   /// See AbstractAttribute::trackStatistics()
7253   void trackStatistics() const override {
7254     if (isAssumedReadNone())
7255       STATS_DECLTRACK_CS_ATTR(readnone)
7256     else if (isAssumedReadOnly())
7257       STATS_DECLTRACK_CS_ATTR(readonly)
7258     else if (isAssumedWriteOnly())
7259       STATS_DECLTRACK_CS_ATTR(writeonly)
7260   }
7261 };
7262 
7263 ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) {
7264 
7265   // The current assumed state used to determine a change.
7266   auto AssumedState = getAssumed();
7267 
7268   auto CheckRWInst = [&](Instruction &I) {
7269     // If the instruction has an own memory behavior state, use it to restrict
7270     // the local state. No further analysis is required as the other memory
7271     // state is as optimistic as it gets.
7272     if (const auto *CB = dyn_cast<CallBase>(&I)) {
7273       const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
7274           *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED);
7275       intersectAssumedBits(MemBehaviorAA.getAssumed());
7276       return !isAtFixpoint();
7277     }
7278 
7279     // Remove access kind modifiers if necessary.
7280     if (I.mayReadFromMemory())
7281       removeAssumedBits(NO_READS);
7282     if (I.mayWriteToMemory())
7283       removeAssumedBits(NO_WRITES);
7284     return !isAtFixpoint();
7285   };
7286 
7287   bool UsedAssumedInformation = false;
7288   if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this,
7289                                           UsedAssumedInformation))
7290     return indicatePessimisticFixpoint();
7291 
7292   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
7293                                         : ChangeStatus::UNCHANGED;
7294 }
7295 
7296 ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) {
7297 
7298   const IRPosition &IRP = getIRPosition();
7299   const IRPosition &FnPos = IRPosition::function_scope(IRP);
7300   AAMemoryBehavior::StateType &S = getState();
7301 
7302   // First, check the function scope. We take the known information and we avoid
7303   // work if the assumed information implies the current assumed information for
7304   // this attribute. This is a valid for all but byval arguments.
7305   Argument *Arg = IRP.getAssociatedArgument();
7306   AAMemoryBehavior::base_t FnMemAssumedState =
7307       AAMemoryBehavior::StateType::getWorstState();
7308   if (!Arg || !Arg->hasByValAttr()) {
7309     const auto &FnMemAA =
7310         A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::OPTIONAL);
7311     FnMemAssumedState = FnMemAA.getAssumed();
7312     S.addKnownBits(FnMemAA.getKnown());
7313     if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed())
7314       return ChangeStatus::UNCHANGED;
7315   }
7316 
7317   // The current assumed state used to determine a change.
7318   auto AssumedState = S.getAssumed();
7319 
7320   // Make sure the value is not captured (except through "return"), if
7321   // it is, any information derived would be irrelevant anyway as we cannot
7322   // check the potential aliases introduced by the capture. However, no need
7323   // to fall back to anythign less optimistic than the function state.
7324   const auto &ArgNoCaptureAA =
7325       A.getAAFor<AANoCapture>(*this, IRP, DepClassTy::OPTIONAL);
7326   if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
7327     S.intersectAssumedBits(FnMemAssumedState);
7328     return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
7329                                           : ChangeStatus::UNCHANGED;
7330   }
7331 
7332   // Visit and expand uses until all are analyzed or a fixpoint is reached.
7333   auto UsePred = [&](const Use &U, bool &Follow) -> bool {
7334     Instruction *UserI = cast<Instruction>(U.getUser());
7335     LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << *U << " in " << *UserI
7336                       << " \n");
7337 
7338     // Droppable users, e.g., llvm::assume does not actually perform any action.
7339     if (UserI->isDroppable())
7340       return true;
7341 
7342     // Check if the users of UserI should also be visited.
7343     Follow = followUsersOfUseIn(A, U, UserI);
7344 
7345     // If UserI might touch memory we analyze the use in detail.
7346     if (UserI->mayReadOrWriteMemory())
7347       analyzeUseIn(A, U, UserI);
7348 
7349     return !isAtFixpoint();
7350   };
7351 
7352   if (!A.checkForAllUses(UsePred, *this, getAssociatedValue()))
7353     return indicatePessimisticFixpoint();
7354 
7355   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
7356                                         : ChangeStatus::UNCHANGED;
7357 }
7358 
7359 bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use &U,
7360                                                   const Instruction *UserI) {
7361   // The loaded value is unrelated to the pointer argument, no need to
7362   // follow the users of the load.
7363   if (isa<LoadInst>(UserI) || isa<ReturnInst>(UserI))
7364     return false;
7365 
7366   // By default we follow all uses assuming UserI might leak information on U,
7367   // we have special handling for call sites operands though.
7368   const auto *CB = dyn_cast<CallBase>(UserI);
7369   if (!CB || !CB->isArgOperand(&U))
7370     return true;
7371 
7372   // If the use is a call argument known not to be captured, the users of
7373   // the call do not need to be visited because they have to be unrelated to
7374   // the input. Note that this check is not trivial even though we disallow
7375   // general capturing of the underlying argument. The reason is that the
7376   // call might the argument "through return", which we allow and for which we
7377   // need to check call users.
7378   if (U.get()->getType()->isPointerTy()) {
7379     unsigned ArgNo = CB->getArgOperandNo(&U);
7380     const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
7381         *this, IRPosition::callsite_argument(*CB, ArgNo), DepClassTy::OPTIONAL);
7382     return !ArgNoCaptureAA.isAssumedNoCapture();
7383   }
7384 
7385   return true;
7386 }
7387 
7388 void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use &U,
7389                                             const Instruction *UserI) {
7390   assert(UserI->mayReadOrWriteMemory());
7391 
7392   switch (UserI->getOpcode()) {
7393   default:
7394     // TODO: Handle all atomics and other side-effect operations we know of.
7395     break;
7396   case Instruction::Load:
7397     // Loads cause the NO_READS property to disappear.
7398     removeAssumedBits(NO_READS);
7399     return;
7400 
7401   case Instruction::Store:
7402     // Stores cause the NO_WRITES property to disappear if the use is the
7403     // pointer operand. Note that while capturing was taken care of somewhere
7404     // else we need to deal with stores of the value that is not looked through.
7405     if (cast<StoreInst>(UserI)->getPointerOperand() == U.get())
7406       removeAssumedBits(NO_WRITES);
7407     else
7408       indicatePessimisticFixpoint();
7409     return;
7410 
7411   case Instruction::Call:
7412   case Instruction::CallBr:
7413   case Instruction::Invoke: {
7414     // For call sites we look at the argument memory behavior attribute (this
7415     // could be recursive!) in order to restrict our own state.
7416     const auto *CB = cast<CallBase>(UserI);
7417 
7418     // Give up on operand bundles.
7419     if (CB->isBundleOperand(&U)) {
7420       indicatePessimisticFixpoint();
7421       return;
7422     }
7423 
7424     // Calling a function does read the function pointer, maybe write it if the
7425     // function is self-modifying.
7426     if (CB->isCallee(&U)) {
7427       removeAssumedBits(NO_READS);
7428       break;
7429     }
7430 
7431     // Adjust the possible access behavior based on the information on the
7432     // argument.
7433     IRPosition Pos;
7434     if (U.get()->getType()->isPointerTy())
7435       Pos = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
7436     else
7437       Pos = IRPosition::callsite_function(*CB);
7438     const auto &MemBehaviorAA =
7439         A.getAAFor<AAMemoryBehavior>(*this, Pos, DepClassTy::OPTIONAL);
7440     // "assumed" has at most the same bits as the MemBehaviorAA assumed
7441     // and at least "known".
7442     intersectAssumedBits(MemBehaviorAA.getAssumed());
7443     return;
7444   }
7445   };
7446 
7447   // Generally, look at the "may-properties" and adjust the assumed state if we
7448   // did not trigger special handling before.
7449   if (UserI->mayReadFromMemory())
7450     removeAssumedBits(NO_READS);
7451   if (UserI->mayWriteToMemory())
7452     removeAssumedBits(NO_WRITES);
7453 }
7454 } // namespace
7455 
7456 /// -------------------- Memory Locations Attributes ---------------------------
7457 /// Includes read-none, argmemonly, inaccessiblememonly,
7458 /// inaccessiblememorargmemonly
7459 /// ----------------------------------------------------------------------------
7460 
7461 std::string AAMemoryLocation::getMemoryLocationsAsStr(
7462     AAMemoryLocation::MemoryLocationsKind MLK) {
7463   if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS))
7464     return "all memory";
7465   if (MLK == AAMemoryLocation::NO_LOCATIONS)
7466     return "no memory";
7467   std::string S = "memory:";
7468   if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM))
7469     S += "stack,";
7470   if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM))
7471     S += "constant,";
7472   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_INTERNAL_MEM))
7473     S += "internal global,";
7474   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_EXTERNAL_MEM))
7475     S += "external global,";
7476   if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM))
7477     S += "argument,";
7478   if (0 == (MLK & AAMemoryLocation::NO_INACCESSIBLE_MEM))
7479     S += "inaccessible,";
7480   if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM))
7481     S += "malloced,";
7482   if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM))
7483     S += "unknown,";
7484   S.pop_back();
7485   return S;
7486 }
7487 
7488 namespace {
7489 struct AAMemoryLocationImpl : public AAMemoryLocation {
7490 
7491   AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A)
7492       : AAMemoryLocation(IRP, A), Allocator(A.Allocator) {
7493     for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u)
7494       AccessKind2Accesses[u] = nullptr;
7495   }
7496 
7497   ~AAMemoryLocationImpl() {
7498     // The AccessSets are allocated via a BumpPtrAllocator, we call
7499     // the destructor manually.
7500     for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u)
7501       if (AccessKind2Accesses[u])
7502         AccessKind2Accesses[u]->~AccessSet();
7503   }
7504 
7505   /// See AbstractAttribute::initialize(...).
7506   void initialize(Attributor &A) override {
7507     intersectAssumedBits(BEST_STATE);
7508     getKnownStateFromValue(A, getIRPosition(), getState());
7509     AAMemoryLocation::initialize(A);
7510   }
7511 
7512   /// Return the memory behavior information encoded in the IR for \p IRP.
7513   static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP,
7514                                      BitIntegerState &State,
7515                                      bool IgnoreSubsumingPositions = false) {
7516     // For internal functions we ignore `argmemonly` and
7517     // `inaccessiblememorargmemonly` as we might break it via interprocedural
7518     // constant propagation. It is unclear if this is the best way but it is
7519     // unlikely this will cause real performance problems. If we are deriving
7520     // attributes for the anchor function we even remove the attribute in
7521     // addition to ignoring it.
7522     bool UseArgMemOnly = true;
7523     Function *AnchorFn = IRP.getAnchorScope();
7524     if (AnchorFn && A.isRunOn(*AnchorFn))
7525       UseArgMemOnly = !AnchorFn->hasLocalLinkage();
7526 
7527     SmallVector<Attribute, 2> Attrs;
7528     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
7529     for (const Attribute &Attr : Attrs) {
7530       switch (Attr.getKindAsEnum()) {
7531       case Attribute::ReadNone:
7532         State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM);
7533         break;
7534       case Attribute::InaccessibleMemOnly:
7535         State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
7536         break;
7537       case Attribute::ArgMemOnly:
7538         if (UseArgMemOnly)
7539           State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true));
7540         else
7541           IRP.removeAttrs({Attribute::ArgMemOnly});
7542         break;
7543       case Attribute::InaccessibleMemOrArgMemOnly:
7544         if (UseArgMemOnly)
7545           State.addKnownBits(inverseLocation(
7546               NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true));
7547         else
7548           IRP.removeAttrs({Attribute::InaccessibleMemOrArgMemOnly});
7549         break;
7550       default:
7551         llvm_unreachable("Unexpected attribute!");
7552       }
7553     }
7554   }
7555 
7556   /// See AbstractAttribute::getDeducedAttributes(...).
7557   void getDeducedAttributes(LLVMContext &Ctx,
7558                             SmallVectorImpl<Attribute> &Attrs) const override {
7559     assert(Attrs.size() == 0);
7560     if (isAssumedReadNone()) {
7561       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
7562     } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) {
7563       if (isAssumedInaccessibleMemOnly())
7564         Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly));
7565       else if (isAssumedArgMemOnly())
7566         Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly));
7567       else if (isAssumedInaccessibleOrArgMemOnly())
7568         Attrs.push_back(
7569             Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly));
7570     }
7571     assert(Attrs.size() <= 1);
7572   }
7573 
7574   /// See AbstractAttribute::manifest(...).
7575   ChangeStatus manifest(Attributor &A) override {
7576     const IRPosition &IRP = getIRPosition();
7577 
7578     // Check if we would improve the existing attributes first.
7579     SmallVector<Attribute, 4> DeducedAttrs;
7580     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
7581     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
7582           return IRP.hasAttr(Attr.getKindAsEnum(),
7583                              /* IgnoreSubsumingPositions */ true);
7584         }))
7585       return ChangeStatus::UNCHANGED;
7586 
7587     // Clear existing attributes.
7588     IRP.removeAttrs(AttrKinds);
7589     if (isAssumedReadNone())
7590       IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds);
7591 
7592     // Use the generic manifest method.
7593     return IRAttribute::manifest(A);
7594   }
7595 
7596   /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...).
7597   bool checkForAllAccessesToMemoryKind(
7598       function_ref<bool(const Instruction *, const Value *, AccessKind,
7599                         MemoryLocationsKind)>
7600           Pred,
7601       MemoryLocationsKind RequestedMLK) const override {
7602     if (!isValidState())
7603       return false;
7604 
7605     MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
7606     if (AssumedMLK == NO_LOCATIONS)
7607       return true;
7608 
7609     unsigned Idx = 0;
7610     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS;
7611          CurMLK *= 2, ++Idx) {
7612       if (CurMLK & RequestedMLK)
7613         continue;
7614 
7615       if (const AccessSet *Accesses = AccessKind2Accesses[Idx])
7616         for (const AccessInfo &AI : *Accesses)
7617           if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
7618             return false;
7619     }
7620 
7621     return true;
7622   }
7623 
7624   ChangeStatus indicatePessimisticFixpoint() override {
7625     // If we give up and indicate a pessimistic fixpoint this instruction will
7626     // become an access for all potential access kinds:
7627     // TODO: Add pointers for argmemonly and globals to improve the results of
7628     //       checkForAllAccessesToMemoryKind.
7629     bool Changed = false;
7630     MemoryLocationsKind KnownMLK = getKnown();
7631     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
7632     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
7633       if (!(CurMLK & KnownMLK))
7634         updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed,
7635                                   getAccessKindFromInst(I));
7636     return AAMemoryLocation::indicatePessimisticFixpoint();
7637   }
7638 
7639 protected:
7640   /// Helper struct to tie together an instruction that has a read or write
7641   /// effect with the pointer it accesses (if any).
7642   struct AccessInfo {
7643 
7644     /// The instruction that caused the access.
7645     const Instruction *I;
7646 
7647     /// The base pointer that is accessed, or null if unknown.
7648     const Value *Ptr;
7649 
7650     /// The kind of access (read/write/read+write).
7651     AccessKind Kind;
7652 
7653     bool operator==(const AccessInfo &RHS) const {
7654       return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind;
7655     }
7656     bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const {
7657       if (LHS.I != RHS.I)
7658         return LHS.I < RHS.I;
7659       if (LHS.Ptr != RHS.Ptr)
7660         return LHS.Ptr < RHS.Ptr;
7661       if (LHS.Kind != RHS.Kind)
7662         return LHS.Kind < RHS.Kind;
7663       return false;
7664     }
7665   };
7666 
7667   /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the
7668   /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind.
7669   using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>;
7670   AccessSet *AccessKind2Accesses[llvm::CTLog2<VALID_STATE>()];
7671 
7672   /// Categorize the pointer arguments of CB that might access memory in
7673   /// AccessedLoc and update the state and access map accordingly.
7674   void
7675   categorizeArgumentPointerLocations(Attributor &A, CallBase &CB,
7676                                      AAMemoryLocation::StateType &AccessedLocs,
7677                                      bool &Changed);
7678 
7679   /// Return the kind(s) of location that may be accessed by \p V.
7680   AAMemoryLocation::MemoryLocationsKind
7681   categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed);
7682 
7683   /// Return the access kind as determined by \p I.
7684   AccessKind getAccessKindFromInst(const Instruction *I) {
7685     AccessKind AK = READ_WRITE;
7686     if (I) {
7687       AK = I->mayReadFromMemory() ? READ : NONE;
7688       AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE));
7689     }
7690     return AK;
7691   }
7692 
7693   /// Update the state \p State and the AccessKind2Accesses given that \p I is
7694   /// an access of kind \p AK to a \p MLK memory location with the access
7695   /// pointer \p Ptr.
7696   void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
7697                                  MemoryLocationsKind MLK, const Instruction *I,
7698                                  const Value *Ptr, bool &Changed,
7699                                  AccessKind AK = READ_WRITE) {
7700 
7701     assert(isPowerOf2_32(MLK) && "Expected a single location set!");
7702     auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)];
7703     if (!Accesses)
7704       Accesses = new (Allocator) AccessSet();
7705     Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second;
7706     State.removeAssumedBits(MLK);
7707   }
7708 
7709   /// Determine the underlying locations kinds for \p Ptr, e.g., globals or
7710   /// arguments, and update the state and access map accordingly.
7711   void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr,
7712                           AAMemoryLocation::StateType &State, bool &Changed);
7713 
7714   /// Used to allocate access sets.
7715   BumpPtrAllocator &Allocator;
7716 
7717   /// The set of IR attributes AAMemoryLocation deals with.
7718   static const Attribute::AttrKind AttrKinds[4];
7719 };
7720 
7721 const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = {
7722     Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly,
7723     Attribute::InaccessibleMemOrArgMemOnly};
7724 
7725 void AAMemoryLocationImpl::categorizePtrValue(
7726     Attributor &A, const Instruction &I, const Value &Ptr,
7727     AAMemoryLocation::StateType &State, bool &Changed) {
7728   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for "
7729                     << Ptr << " ["
7730                     << getMemoryLocationsAsStr(State.getAssumed()) << "]\n");
7731 
7732   SmallSetVector<Value *, 8> Objects;
7733   bool UsedAssumedInformation = false;
7734   if (!AA::getAssumedUnderlyingObjects(A, Ptr, Objects, *this, &I,
7735                                        UsedAssumedInformation,
7736                                        AA::Intraprocedural)) {
7737     LLVM_DEBUG(
7738         dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n");
7739     updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed,
7740                               getAccessKindFromInst(&I));
7741     return;
7742   }
7743 
7744   for (Value *Obj : Objects) {
7745     // TODO: recognize the TBAA used for constant accesses.
7746     MemoryLocationsKind MLK = NO_LOCATIONS;
7747     if (isa<UndefValue>(Obj))
7748       continue;
7749     if (isa<Argument>(Obj)) {
7750       // TODO: For now we do not treat byval arguments as local copies performed
7751       // on the call edge, though, we should. To make that happen we need to
7752       // teach various passes, e.g., DSE, about the copy effect of a byval. That
7753       // would also allow us to mark functions only accessing byval arguments as
7754       // readnone again, atguably their acceses have no effect outside of the
7755       // function, like accesses to allocas.
7756       MLK = NO_ARGUMENT_MEM;
7757     } else if (auto *GV = dyn_cast<GlobalValue>(Obj)) {
7758       // Reading constant memory is not treated as a read "effect" by the
7759       // function attr pass so we won't neither. Constants defined by TBAA are
7760       // similar. (We know we do not write it because it is constant.)
7761       if (auto *GVar = dyn_cast<GlobalVariable>(GV))
7762         if (GVar->isConstant())
7763           continue;
7764 
7765       if (GV->hasLocalLinkage())
7766         MLK = NO_GLOBAL_INTERNAL_MEM;
7767       else
7768         MLK = NO_GLOBAL_EXTERNAL_MEM;
7769     } else if (isa<ConstantPointerNull>(Obj) &&
7770                !NullPointerIsDefined(getAssociatedFunction(),
7771                                      Ptr.getType()->getPointerAddressSpace())) {
7772       continue;
7773     } else if (isa<AllocaInst>(Obj)) {
7774       MLK = NO_LOCAL_MEM;
7775     } else if (const auto *CB = dyn_cast<CallBase>(Obj)) {
7776       const auto &NoAliasAA = A.getAAFor<AANoAlias>(
7777           *this, IRPosition::callsite_returned(*CB), DepClassTy::OPTIONAL);
7778       if (NoAliasAA.isAssumedNoAlias())
7779         MLK = NO_MALLOCED_MEM;
7780       else
7781         MLK = NO_UNKOWN_MEM;
7782     } else {
7783       MLK = NO_UNKOWN_MEM;
7784     }
7785 
7786     assert(MLK != NO_LOCATIONS && "No location specified!");
7787     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value can be categorized: "
7788                       << *Obj << " -> " << getMemoryLocationsAsStr(MLK)
7789                       << "\n");
7790     updateStateAndAccessesMap(getState(), MLK, &I, Obj, Changed,
7791                               getAccessKindFromInst(&I));
7792   }
7793 
7794   LLVM_DEBUG(
7795       dbgs() << "[AAMemoryLocation] Accessed locations with pointer locations: "
7796              << getMemoryLocationsAsStr(State.getAssumed()) << "\n");
7797 }
7798 
7799 void AAMemoryLocationImpl::categorizeArgumentPointerLocations(
7800     Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs,
7801     bool &Changed) {
7802   for (unsigned ArgNo = 0, E = CB.arg_size(); ArgNo < E; ++ArgNo) {
7803 
7804     // Skip non-pointer arguments.
7805     const Value *ArgOp = CB.getArgOperand(ArgNo);
7806     if (!ArgOp->getType()->isPtrOrPtrVectorTy())
7807       continue;
7808 
7809     // Skip readnone arguments.
7810     const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo);
7811     const auto &ArgOpMemLocationAA =
7812         A.getAAFor<AAMemoryBehavior>(*this, ArgOpIRP, DepClassTy::OPTIONAL);
7813 
7814     if (ArgOpMemLocationAA.isAssumedReadNone())
7815       continue;
7816 
7817     // Categorize potentially accessed pointer arguments as if there was an
7818     // access instruction with them as pointer.
7819     categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed);
7820   }
7821 }
7822 
7823 AAMemoryLocation::MemoryLocationsKind
7824 AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I,
7825                                                   bool &Changed) {
7826   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for "
7827                     << I << "\n");
7828 
7829   AAMemoryLocation::StateType AccessedLocs;
7830   AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
7831 
7832   if (auto *CB = dyn_cast<CallBase>(&I)) {
7833 
7834     // First check if we assume any memory is access is visible.
7835     const auto &CBMemLocationAA = A.getAAFor<AAMemoryLocation>(
7836         *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL);
7837     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I
7838                       << " [" << CBMemLocationAA << "]\n");
7839 
7840     if (CBMemLocationAA.isAssumedReadNone())
7841       return NO_LOCATIONS;
7842 
7843     if (CBMemLocationAA.isAssumedInaccessibleMemOnly()) {
7844       updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr,
7845                                 Changed, getAccessKindFromInst(&I));
7846       return AccessedLocs.getAssumed();
7847     }
7848 
7849     uint32_t CBAssumedNotAccessedLocs =
7850         CBMemLocationAA.getAssumedNotAccessedLocation();
7851 
7852     // Set the argmemonly and global bit as we handle them separately below.
7853     uint32_t CBAssumedNotAccessedLocsNoArgMem =
7854         CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
7855 
7856     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
7857       if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
7858         continue;
7859       updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed,
7860                                 getAccessKindFromInst(&I));
7861     }
7862 
7863     // Now handle global memory if it might be accessed. This is slightly tricky
7864     // as NO_GLOBAL_MEM has multiple bits set.
7865     bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
7866     if (HasGlobalAccesses) {
7867       auto AccessPred = [&](const Instruction *, const Value *Ptr,
7868                             AccessKind Kind, MemoryLocationsKind MLK) {
7869         updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed,
7870                                   getAccessKindFromInst(&I));
7871         return true;
7872       };
7873       if (!CBMemLocationAA.checkForAllAccessesToMemoryKind(
7874               AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false)))
7875         return AccessedLocs.getWorstState();
7876     }
7877 
7878     LLVM_DEBUG(
7879         dbgs() << "[AAMemoryLocation] Accessed state before argument handling: "
7880                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
7881 
7882     // Now handle argument memory if it might be accessed.
7883     bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
7884     if (HasArgAccesses)
7885       categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed);
7886 
7887     LLVM_DEBUG(
7888         dbgs() << "[AAMemoryLocation] Accessed state after argument handling: "
7889                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
7890 
7891     return AccessedLocs.getAssumed();
7892   }
7893 
7894   if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) {
7895     LLVM_DEBUG(
7896         dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: "
7897                << I << " [" << *Ptr << "]\n");
7898     categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed);
7899     return AccessedLocs.getAssumed();
7900   }
7901 
7902   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: "
7903                     << I << "\n");
7904   updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed,
7905                             getAccessKindFromInst(&I));
7906   return AccessedLocs.getAssumed();
7907 }
7908 
7909 /// An AA to represent the memory behavior function attributes.
7910 struct AAMemoryLocationFunction final : public AAMemoryLocationImpl {
7911   AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A)
7912       : AAMemoryLocationImpl(IRP, A) {}
7913 
7914   /// See AbstractAttribute::updateImpl(Attributor &A).
7915   virtual ChangeStatus updateImpl(Attributor &A) override {
7916 
7917     const auto &MemBehaviorAA =
7918         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE);
7919     if (MemBehaviorAA.isAssumedReadNone()) {
7920       if (MemBehaviorAA.isKnownReadNone())
7921         return indicateOptimisticFixpoint();
7922       assert(isAssumedReadNone() &&
7923              "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
7924       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
7925       return ChangeStatus::UNCHANGED;
7926     }
7927 
7928     // The current assumed state used to determine a change.
7929     auto AssumedState = getAssumed();
7930     bool Changed = false;
7931 
7932     auto CheckRWInst = [&](Instruction &I) {
7933       MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed);
7934       LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I
7935                         << ": " << getMemoryLocationsAsStr(MLK) << "\n");
7936       removeAssumedBits(inverseLocation(MLK, false, false));
7937       // Stop once only the valid bit set in the *not assumed location*, thus
7938       // once we don't actually exclude any memory locations in the state.
7939       return getAssumedNotAccessedLocation() != VALID_STATE;
7940     };
7941 
7942     bool UsedAssumedInformation = false;
7943     if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this,
7944                                             UsedAssumedInformation))
7945       return indicatePessimisticFixpoint();
7946 
7947     Changed |= AssumedState != getAssumed();
7948     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
7949   }
7950 
7951   /// See AbstractAttribute::trackStatistics()
7952   void trackStatistics() const override {
7953     if (isAssumedReadNone())
7954       STATS_DECLTRACK_FN_ATTR(readnone)
7955     else if (isAssumedArgMemOnly())
7956       STATS_DECLTRACK_FN_ATTR(argmemonly)
7957     else if (isAssumedInaccessibleMemOnly())
7958       STATS_DECLTRACK_FN_ATTR(inaccessiblememonly)
7959     else if (isAssumedInaccessibleOrArgMemOnly())
7960       STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly)
7961   }
7962 };
7963 
7964 /// AAMemoryLocation attribute for call sites.
7965 struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
7966   AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A)
7967       : AAMemoryLocationImpl(IRP, A) {}
7968 
7969   /// See AbstractAttribute::initialize(...).
7970   void initialize(Attributor &A) override {
7971     AAMemoryLocationImpl::initialize(A);
7972     Function *F = getAssociatedFunction();
7973     if (!F || F->isDeclaration())
7974       indicatePessimisticFixpoint();
7975   }
7976 
7977   /// See AbstractAttribute::updateImpl(...).
7978   ChangeStatus updateImpl(Attributor &A) override {
7979     // TODO: Once we have call site specific value information we can provide
7980     //       call site specific liveness liveness information and then it makes
7981     //       sense to specialize attributes for call sites arguments instead of
7982     //       redirecting requests to the callee argument.
7983     Function *F = getAssociatedFunction();
7984     const IRPosition &FnPos = IRPosition::function(*F);
7985     auto &FnAA =
7986         A.getAAFor<AAMemoryLocation>(*this, FnPos, DepClassTy::REQUIRED);
7987     bool Changed = false;
7988     auto AccessPred = [&](const Instruction *I, const Value *Ptr,
7989                           AccessKind Kind, MemoryLocationsKind MLK) {
7990       updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed,
7991                                 getAccessKindFromInst(I));
7992       return true;
7993     };
7994     if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
7995       return indicatePessimisticFixpoint();
7996     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
7997   }
7998 
7999   /// See AbstractAttribute::trackStatistics()
8000   void trackStatistics() const override {
8001     if (isAssumedReadNone())
8002       STATS_DECLTRACK_CS_ATTR(readnone)
8003   }
8004 };
8005 } // namespace
8006 
8007 /// ------------------ Value Constant Range Attribute -------------------------
8008 
8009 namespace {
8010 struct AAValueConstantRangeImpl : AAValueConstantRange {
8011   using StateType = IntegerRangeState;
8012   AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A)
8013       : AAValueConstantRange(IRP, A) {}
8014 
8015   /// See AbstractAttribute::initialize(..).
8016   void initialize(Attributor &A) override {
8017     if (A.hasSimplificationCallback(getIRPosition())) {
8018       indicatePessimisticFixpoint();
8019       return;
8020     }
8021 
8022     // Intersect a range given by SCEV.
8023     intersectKnown(getConstantRangeFromSCEV(A, getCtxI()));
8024 
8025     // Intersect a range given by LVI.
8026     intersectKnown(getConstantRangeFromLVI(A, getCtxI()));
8027   }
8028 
8029   /// See AbstractAttribute::getAsStr().
8030   const std::string getAsStr() const override {
8031     std::string Str;
8032     llvm::raw_string_ostream OS(Str);
8033     OS << "range(" << getBitWidth() << ")<";
8034     getKnown().print(OS);
8035     OS << " / ";
8036     getAssumed().print(OS);
8037     OS << ">";
8038     return OS.str();
8039   }
8040 
8041   /// Helper function to get a SCEV expr for the associated value at program
8042   /// point \p I.
8043   const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const {
8044     if (!getAnchorScope())
8045       return nullptr;
8046 
8047     ScalarEvolution *SE =
8048         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
8049             *getAnchorScope());
8050 
8051     LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
8052         *getAnchorScope());
8053 
8054     if (!SE || !LI)
8055       return nullptr;
8056 
8057     const SCEV *S = SE->getSCEV(&getAssociatedValue());
8058     if (!I)
8059       return S;
8060 
8061     return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent()));
8062   }
8063 
8064   /// Helper function to get a range from SCEV for the associated value at
8065   /// program point \p I.
8066   ConstantRange getConstantRangeFromSCEV(Attributor &A,
8067                                          const Instruction *I = nullptr) const {
8068     if (!getAnchorScope())
8069       return getWorstState(getBitWidth());
8070 
8071     ScalarEvolution *SE =
8072         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
8073             *getAnchorScope());
8074 
8075     const SCEV *S = getSCEV(A, I);
8076     if (!SE || !S)
8077       return getWorstState(getBitWidth());
8078 
8079     return SE->getUnsignedRange(S);
8080   }
8081 
8082   /// Helper function to get a range from LVI for the associated value at
8083   /// program point \p I.
8084   ConstantRange
8085   getConstantRangeFromLVI(Attributor &A,
8086                           const Instruction *CtxI = nullptr) const {
8087     if (!getAnchorScope())
8088       return getWorstState(getBitWidth());
8089 
8090     LazyValueInfo *LVI =
8091         A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
8092             *getAnchorScope());
8093 
8094     if (!LVI || !CtxI)
8095       return getWorstState(getBitWidth());
8096     return LVI->getConstantRange(&getAssociatedValue(),
8097                                  const_cast<Instruction *>(CtxI));
8098   }
8099 
8100   /// Return true if \p CtxI is valid for querying outside analyses.
8101   /// This basically makes sure we do not ask intra-procedural analysis
8102   /// about a context in the wrong function or a context that violates
8103   /// dominance assumptions they might have. The \p AllowAACtxI flag indicates
8104   /// if the original context of this AA is OK or should be considered invalid.
8105   bool isValidCtxInstructionForOutsideAnalysis(Attributor &A,
8106                                                const Instruction *CtxI,
8107                                                bool AllowAACtxI) const {
8108     if (!CtxI || (!AllowAACtxI && CtxI == getCtxI()))
8109       return false;
8110 
8111     // Our context might be in a different function, neither intra-procedural
8112     // analysis (ScalarEvolution nor LazyValueInfo) can handle that.
8113     if (!AA::isValidInScope(getAssociatedValue(), CtxI->getFunction()))
8114       return false;
8115 
8116     // If the context is not dominated by the value there are paths to the
8117     // context that do not define the value. This cannot be handled by
8118     // LazyValueInfo so we need to bail.
8119     if (auto *I = dyn_cast<Instruction>(&getAssociatedValue())) {
8120       InformationCache &InfoCache = A.getInfoCache();
8121       const DominatorTree *DT =
8122           InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
8123               *I->getFunction());
8124       return DT && DT->dominates(I, CtxI);
8125     }
8126 
8127     return true;
8128   }
8129 
8130   /// See AAValueConstantRange::getKnownConstantRange(..).
8131   ConstantRange
8132   getKnownConstantRange(Attributor &A,
8133                         const Instruction *CtxI = nullptr) const override {
8134     if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI,
8135                                                  /* AllowAACtxI */ false))
8136       return getKnown();
8137 
8138     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
8139     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
8140     return getKnown().intersectWith(SCEVR).intersectWith(LVIR);
8141   }
8142 
8143   /// See AAValueConstantRange::getAssumedConstantRange(..).
8144   ConstantRange
8145   getAssumedConstantRange(Attributor &A,
8146                           const Instruction *CtxI = nullptr) const override {
8147     // TODO: Make SCEV use Attributor assumption.
8148     //       We may be able to bound a variable range via assumptions in
8149     //       Attributor. ex.) If x is assumed to be in [1, 3] and y is known to
8150     //       evolve to x^2 + x, then we can say that y is in [2, 12].
8151     if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI,
8152                                                  /* AllowAACtxI */ false))
8153       return getAssumed();
8154 
8155     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
8156     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
8157     return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
8158   }
8159 
8160   /// Helper function to create MDNode for range metadata.
8161   static MDNode *
8162   getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx,
8163                             const ConstantRange &AssumedConstantRange) {
8164     Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get(
8165                                   Ty, AssumedConstantRange.getLower())),
8166                               ConstantAsMetadata::get(ConstantInt::get(
8167                                   Ty, AssumedConstantRange.getUpper()))};
8168     return MDNode::get(Ctx, LowAndHigh);
8169   }
8170 
8171   /// Return true if \p Assumed is included in \p KnownRanges.
8172   static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) {
8173 
8174     if (Assumed.isFullSet())
8175       return false;
8176 
8177     if (!KnownRanges)
8178       return true;
8179 
8180     // If multiple ranges are annotated in IR, we give up to annotate assumed
8181     // range for now.
8182 
8183     // TODO:  If there exists a known range which containts assumed range, we
8184     // can say assumed range is better.
8185     if (KnownRanges->getNumOperands() > 2)
8186       return false;
8187 
8188     ConstantInt *Lower =
8189         mdconst::extract<ConstantInt>(KnownRanges->getOperand(0));
8190     ConstantInt *Upper =
8191         mdconst::extract<ConstantInt>(KnownRanges->getOperand(1));
8192 
8193     ConstantRange Known(Lower->getValue(), Upper->getValue());
8194     return Known.contains(Assumed) && Known != Assumed;
8195   }
8196 
8197   /// Helper function to set range metadata.
8198   static bool
8199   setRangeMetadataIfisBetterRange(Instruction *I,
8200                                   const ConstantRange &AssumedConstantRange) {
8201     auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range);
8202     if (isBetterRange(AssumedConstantRange, OldRangeMD)) {
8203       if (!AssumedConstantRange.isEmptySet()) {
8204         I->setMetadata(LLVMContext::MD_range,
8205                        getMDNodeForConstantRange(I->getType(), I->getContext(),
8206                                                  AssumedConstantRange));
8207         return true;
8208       }
8209     }
8210     return false;
8211   }
8212 
8213   /// See AbstractAttribute::manifest()
8214   ChangeStatus manifest(Attributor &A) override {
8215     ChangeStatus Changed = ChangeStatus::UNCHANGED;
8216     ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
8217     assert(!AssumedConstantRange.isFullSet() && "Invalid state");
8218 
8219     auto &V = getAssociatedValue();
8220     if (!AssumedConstantRange.isEmptySet() &&
8221         !AssumedConstantRange.isSingleElement()) {
8222       if (Instruction *I = dyn_cast<Instruction>(&V)) {
8223         assert(I == getCtxI() && "Should not annotate an instruction which is "
8224                                  "not the context instruction");
8225         if (isa<CallInst>(I) || isa<LoadInst>(I))
8226           if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange))
8227             Changed = ChangeStatus::CHANGED;
8228       }
8229     }
8230 
8231     return Changed;
8232   }
8233 };
8234 
8235 struct AAValueConstantRangeArgument final
8236     : AAArgumentFromCallSiteArguments<
8237           AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
8238           true /* BridgeCallBaseContext */> {
8239   using Base = AAArgumentFromCallSiteArguments<
8240       AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
8241       true /* BridgeCallBaseContext */>;
8242   AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A)
8243       : Base(IRP, A) {}
8244 
8245   /// See AbstractAttribute::initialize(..).
8246   void initialize(Attributor &A) override {
8247     if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
8248       indicatePessimisticFixpoint();
8249     } else {
8250       Base::initialize(A);
8251     }
8252   }
8253 
8254   /// See AbstractAttribute::trackStatistics()
8255   void trackStatistics() const override {
8256     STATS_DECLTRACK_ARG_ATTR(value_range)
8257   }
8258 };
8259 
8260 struct AAValueConstantRangeReturned
8261     : AAReturnedFromReturnedValues<AAValueConstantRange,
8262                                    AAValueConstantRangeImpl,
8263                                    AAValueConstantRangeImpl::StateType,
8264                                    /* PropogateCallBaseContext */ true> {
8265   using Base =
8266       AAReturnedFromReturnedValues<AAValueConstantRange,
8267                                    AAValueConstantRangeImpl,
8268                                    AAValueConstantRangeImpl::StateType,
8269                                    /* PropogateCallBaseContext */ true>;
8270   AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A)
8271       : Base(IRP, A) {}
8272 
8273   /// See AbstractAttribute::initialize(...).
8274   void initialize(Attributor &A) override {}
8275 
8276   /// See AbstractAttribute::trackStatistics()
8277   void trackStatistics() const override {
8278     STATS_DECLTRACK_FNRET_ATTR(value_range)
8279   }
8280 };
8281 
8282 struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
8283   AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A)
8284       : AAValueConstantRangeImpl(IRP, A) {}
8285 
8286   /// See AbstractAttribute::initialize(...).
8287   void initialize(Attributor &A) override {
8288     AAValueConstantRangeImpl::initialize(A);
8289     if (isAtFixpoint())
8290       return;
8291 
8292     Value &V = getAssociatedValue();
8293 
8294     if (auto *C = dyn_cast<ConstantInt>(&V)) {
8295       unionAssumed(ConstantRange(C->getValue()));
8296       indicateOptimisticFixpoint();
8297       return;
8298     }
8299 
8300     if (isa<UndefValue>(&V)) {
8301       // Collapse the undef state to 0.
8302       unionAssumed(ConstantRange(APInt(getBitWidth(), 0)));
8303       indicateOptimisticFixpoint();
8304       return;
8305     }
8306 
8307     if (isa<CallBase>(&V))
8308       return;
8309 
8310     if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V))
8311       return;
8312 
8313     // If it is a load instruction with range metadata, use it.
8314     if (LoadInst *LI = dyn_cast<LoadInst>(&V))
8315       if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
8316         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
8317         return;
8318       }
8319 
8320     // We can work with PHI and select instruction as we traverse their operands
8321     // during update.
8322     if (isa<SelectInst>(V) || isa<PHINode>(V))
8323       return;
8324 
8325     // Otherwise we give up.
8326     indicatePessimisticFixpoint();
8327 
8328     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: "
8329                       << getAssociatedValue() << "\n");
8330   }
8331 
8332   bool calculateBinaryOperator(
8333       Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T,
8334       const Instruction *CtxI,
8335       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
8336     Value *LHS = BinOp->getOperand(0);
8337     Value *RHS = BinOp->getOperand(1);
8338 
8339     // Simplify the operands first.
8340     bool UsedAssumedInformation = false;
8341     const auto &SimplifiedLHS = A.getAssumedSimplified(
8342         IRPosition::value(*LHS, getCallBaseContext()), *this,
8343         UsedAssumedInformation, AA::Interprocedural);
8344     if (!SimplifiedLHS.has_value())
8345       return true;
8346     if (!SimplifiedLHS.value())
8347       return false;
8348     LHS = *SimplifiedLHS;
8349 
8350     const auto &SimplifiedRHS = A.getAssumedSimplified(
8351         IRPosition::value(*RHS, getCallBaseContext()), *this,
8352         UsedAssumedInformation, AA::Interprocedural);
8353     if (!SimplifiedRHS.has_value())
8354       return true;
8355     if (!SimplifiedRHS.value())
8356       return false;
8357     RHS = *SimplifiedRHS;
8358 
8359     // TODO: Allow non integers as well.
8360     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
8361       return false;
8362 
8363     auto &LHSAA = A.getAAFor<AAValueConstantRange>(
8364         *this, IRPosition::value(*LHS, getCallBaseContext()),
8365         DepClassTy::REQUIRED);
8366     QuerriedAAs.push_back(&LHSAA);
8367     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
8368 
8369     auto &RHSAA = A.getAAFor<AAValueConstantRange>(
8370         *this, IRPosition::value(*RHS, getCallBaseContext()),
8371         DepClassTy::REQUIRED);
8372     QuerriedAAs.push_back(&RHSAA);
8373     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
8374 
8375     auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange);
8376 
8377     T.unionAssumed(AssumedRange);
8378 
8379     // TODO: Track a known state too.
8380 
8381     return T.isValidState();
8382   }
8383 
8384   bool calculateCastInst(
8385       Attributor &A, CastInst *CastI, IntegerRangeState &T,
8386       const Instruction *CtxI,
8387       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
8388     assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!");
8389     // TODO: Allow non integers as well.
8390     Value *OpV = CastI->getOperand(0);
8391 
8392     // Simplify the operand first.
8393     bool UsedAssumedInformation = false;
8394     const auto &SimplifiedOpV = A.getAssumedSimplified(
8395         IRPosition::value(*OpV, getCallBaseContext()), *this,
8396         UsedAssumedInformation, AA::Interprocedural);
8397     if (!SimplifiedOpV.has_value())
8398       return true;
8399     if (!SimplifiedOpV.value())
8400       return false;
8401     OpV = *SimplifiedOpV;
8402 
8403     if (!OpV->getType()->isIntegerTy())
8404       return false;
8405 
8406     auto &OpAA = A.getAAFor<AAValueConstantRange>(
8407         *this, IRPosition::value(*OpV, getCallBaseContext()),
8408         DepClassTy::REQUIRED);
8409     QuerriedAAs.push_back(&OpAA);
8410     T.unionAssumed(
8411         OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth()));
8412     return T.isValidState();
8413   }
8414 
8415   bool
8416   calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T,
8417                    const Instruction *CtxI,
8418                    SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
8419     Value *LHS = CmpI->getOperand(0);
8420     Value *RHS = CmpI->getOperand(1);
8421 
8422     // Simplify the operands first.
8423     bool UsedAssumedInformation = false;
8424     const auto &SimplifiedLHS = A.getAssumedSimplified(
8425         IRPosition::value(*LHS, getCallBaseContext()), *this,
8426         UsedAssumedInformation, AA::Interprocedural);
8427     if (!SimplifiedLHS.has_value())
8428       return true;
8429     if (!SimplifiedLHS.value())
8430       return false;
8431     LHS = *SimplifiedLHS;
8432 
8433     const auto &SimplifiedRHS = A.getAssumedSimplified(
8434         IRPosition::value(*RHS, getCallBaseContext()), *this,
8435         UsedAssumedInformation, AA::Interprocedural);
8436     if (!SimplifiedRHS.has_value())
8437       return true;
8438     if (!SimplifiedRHS.value())
8439       return false;
8440     RHS = *SimplifiedRHS;
8441 
8442     // TODO: Allow non integers as well.
8443     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
8444       return false;
8445 
8446     auto &LHSAA = A.getAAFor<AAValueConstantRange>(
8447         *this, IRPosition::value(*LHS, getCallBaseContext()),
8448         DepClassTy::REQUIRED);
8449     QuerriedAAs.push_back(&LHSAA);
8450     auto &RHSAA = A.getAAFor<AAValueConstantRange>(
8451         *this, IRPosition::value(*RHS, getCallBaseContext()),
8452         DepClassTy::REQUIRED);
8453     QuerriedAAs.push_back(&RHSAA);
8454     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
8455     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
8456 
8457     // If one of them is empty set, we can't decide.
8458     if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
8459       return true;
8460 
8461     bool MustTrue = false, MustFalse = false;
8462 
8463     auto AllowedRegion =
8464         ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange);
8465 
8466     if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
8467       MustFalse = true;
8468 
8469     if (LHSAARange.icmp(CmpI->getPredicate(), RHSAARange))
8470       MustTrue = true;
8471 
8472     assert((!MustTrue || !MustFalse) &&
8473            "Either MustTrue or MustFalse should be false!");
8474 
8475     if (MustTrue)
8476       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1)));
8477     else if (MustFalse)
8478       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0)));
8479     else
8480       T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true));
8481 
8482     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA
8483                       << " " << RHSAA << "\n");
8484 
8485     // TODO: Track a known state too.
8486     return T.isValidState();
8487   }
8488 
8489   /// See AbstractAttribute::updateImpl(...).
8490   ChangeStatus updateImpl(Attributor &A) override {
8491 
8492     IntegerRangeState T(getBitWidth());
8493     auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool {
8494       Instruction *I = dyn_cast<Instruction>(&V);
8495       if (!I || isa<CallBase>(I)) {
8496 
8497         // Simplify the operand first.
8498         bool UsedAssumedInformation = false;
8499         const auto &SimplifiedOpV = A.getAssumedSimplified(
8500             IRPosition::value(V, getCallBaseContext()), *this,
8501             UsedAssumedInformation, AA::Interprocedural);
8502         if (!SimplifiedOpV.has_value())
8503           return true;
8504         if (!SimplifiedOpV.value())
8505           return false;
8506         Value *VPtr = *SimplifiedOpV;
8507 
8508         // If the value is not instruction, we query AA to Attributor.
8509         const auto &AA = A.getAAFor<AAValueConstantRange>(
8510             *this, IRPosition::value(*VPtr, getCallBaseContext()),
8511             DepClassTy::REQUIRED);
8512 
8513         // Clamp operator is not used to utilize a program point CtxI.
8514         T.unionAssumed(AA.getAssumedConstantRange(A, CtxI));
8515 
8516         return T.isValidState();
8517       }
8518 
8519       SmallVector<const AAValueConstantRange *, 4> QuerriedAAs;
8520       if (auto *BinOp = dyn_cast<BinaryOperator>(I)) {
8521         if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs))
8522           return false;
8523       } else if (auto *CmpI = dyn_cast<CmpInst>(I)) {
8524         if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs))
8525           return false;
8526       } else if (auto *CastI = dyn_cast<CastInst>(I)) {
8527         if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs))
8528           return false;
8529       } else {
8530         // Give up with other instructions.
8531         // TODO: Add other instructions
8532 
8533         T.indicatePessimisticFixpoint();
8534         return false;
8535       }
8536 
8537       // Catch circular reasoning in a pessimistic way for now.
8538       // TODO: Check how the range evolves and if we stripped anything, see also
8539       //       AADereferenceable or AAAlign for similar situations.
8540       for (const AAValueConstantRange *QueriedAA : QuerriedAAs) {
8541         if (QueriedAA != this)
8542           continue;
8543         // If we are in a stady state we do not need to worry.
8544         if (T.getAssumed() == getState().getAssumed())
8545           continue;
8546         T.indicatePessimisticFixpoint();
8547       }
8548 
8549       return T.isValidState();
8550     };
8551 
8552     if (!VisitValueCB(getAssociatedValue(), getCtxI()))
8553       return indicatePessimisticFixpoint();
8554 
8555     // Ensure that long def-use chains can't cause circular reasoning either by
8556     // introducing a cutoff below.
8557     if (clampStateAndIndicateChange(getState(), T) == ChangeStatus::UNCHANGED)
8558       return ChangeStatus::UNCHANGED;
8559     if (++NumChanges > MaxNumChanges) {
8560       LLVM_DEBUG(dbgs() << "[AAValueConstantRange] performed " << NumChanges
8561                         << " but only " << MaxNumChanges
8562                         << " are allowed to avoid cyclic reasoning.");
8563       return indicatePessimisticFixpoint();
8564     }
8565     return ChangeStatus::CHANGED;
8566   }
8567 
8568   /// See AbstractAttribute::trackStatistics()
8569   void trackStatistics() const override {
8570     STATS_DECLTRACK_FLOATING_ATTR(value_range)
8571   }
8572 
8573   /// Tracker to bail after too many widening steps of the constant range.
8574   int NumChanges = 0;
8575 
8576   /// Upper bound for the number of allowed changes (=widening steps) for the
8577   /// constant range before we give up.
8578   static constexpr int MaxNumChanges = 5;
8579 };
8580 
8581 struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
8582   AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A)
8583       : AAValueConstantRangeImpl(IRP, A) {}
8584 
8585   /// See AbstractAttribute::initialize(...).
8586   ChangeStatus updateImpl(Attributor &A) override {
8587     llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will "
8588                      "not be called");
8589   }
8590 
8591   /// See AbstractAttribute::trackStatistics()
8592   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) }
8593 };
8594 
8595 struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
8596   AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A)
8597       : AAValueConstantRangeFunction(IRP, A) {}
8598 
8599   /// See AbstractAttribute::trackStatistics()
8600   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) }
8601 };
8602 
8603 struct AAValueConstantRangeCallSiteReturned
8604     : AACallSiteReturnedFromReturned<AAValueConstantRange,
8605                                      AAValueConstantRangeImpl,
8606                                      AAValueConstantRangeImpl::StateType,
8607                                      /* IntroduceCallBaseContext */ true> {
8608   AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A)
8609       : AACallSiteReturnedFromReturned<AAValueConstantRange,
8610                                        AAValueConstantRangeImpl,
8611                                        AAValueConstantRangeImpl::StateType,
8612                                        /* IntroduceCallBaseContext */ true>(IRP,
8613                                                                             A) {
8614   }
8615 
8616   /// See AbstractAttribute::initialize(...).
8617   void initialize(Attributor &A) override {
8618     // If it is a load instruction with range metadata, use the metadata.
8619     if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue()))
8620       if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range))
8621         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
8622 
8623     AAValueConstantRangeImpl::initialize(A);
8624   }
8625 
8626   /// See AbstractAttribute::trackStatistics()
8627   void trackStatistics() const override {
8628     STATS_DECLTRACK_CSRET_ATTR(value_range)
8629   }
8630 };
8631 struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
8632   AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A)
8633       : AAValueConstantRangeFloating(IRP, A) {}
8634 
8635   /// See AbstractAttribute::manifest()
8636   ChangeStatus manifest(Attributor &A) override {
8637     return ChangeStatus::UNCHANGED;
8638   }
8639 
8640   /// See AbstractAttribute::trackStatistics()
8641   void trackStatistics() const override {
8642     STATS_DECLTRACK_CSARG_ATTR(value_range)
8643   }
8644 };
8645 } // namespace
8646 
8647 /// ------------------ Potential Values Attribute -------------------------
8648 
8649 namespace {
8650 struct AAPotentialConstantValuesImpl : AAPotentialConstantValues {
8651   using StateType = PotentialConstantIntValuesState;
8652 
8653   AAPotentialConstantValuesImpl(const IRPosition &IRP, Attributor &A)
8654       : AAPotentialConstantValues(IRP, A) {}
8655 
8656   /// See AbstractAttribute::initialize(..).
8657   void initialize(Attributor &A) override {
8658     if (A.hasSimplificationCallback(getIRPosition()))
8659       indicatePessimisticFixpoint();
8660     else
8661       AAPotentialConstantValues::initialize(A);
8662   }
8663 
8664   bool fillSetWithConstantValues(Attributor &A, const IRPosition &IRP, SetTy &S,
8665                                  bool &ContainsUndef) {
8666     SmallVector<AA::ValueAndContext> Values;
8667     bool UsedAssumedInformation = false;
8668     if (!A.getAssumedSimplifiedValues(IRP, *this, Values, AA::Interprocedural,
8669                                       UsedAssumedInformation)) {
8670       if (!IRP.getAssociatedType()->isIntegerTy())
8671         return false;
8672       auto &PotentialValuesAA = A.getAAFor<AAPotentialConstantValues>(
8673           *this, IRP, DepClassTy::REQUIRED);
8674       if (!PotentialValuesAA.getState().isValidState())
8675         return false;
8676       ContainsUndef = PotentialValuesAA.getState().undefIsContained();
8677       S = PotentialValuesAA.getState().getAssumedSet();
8678       return true;
8679     }
8680 
8681     for (auto &It : Values) {
8682       if (isa<UndefValue>(It.getValue()))
8683         continue;
8684       auto *CI = dyn_cast<ConstantInt>(It.getValue());
8685       if (!CI)
8686         return false;
8687       S.insert(CI->getValue());
8688     }
8689     ContainsUndef = S.empty();
8690 
8691     return true;
8692   }
8693 
8694   /// See AbstractAttribute::getAsStr().
8695   const std::string getAsStr() const override {
8696     std::string Str;
8697     llvm::raw_string_ostream OS(Str);
8698     OS << getState();
8699     return OS.str();
8700   }
8701 
8702   /// See AbstractAttribute::updateImpl(...).
8703   ChangeStatus updateImpl(Attributor &A) override {
8704     return indicatePessimisticFixpoint();
8705   }
8706 };
8707 
8708 struct AAPotentialConstantValuesArgument final
8709     : AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
8710                                       AAPotentialConstantValuesImpl,
8711                                       PotentialConstantIntValuesState> {
8712   using Base = AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
8713                                                AAPotentialConstantValuesImpl,
8714                                                PotentialConstantIntValuesState>;
8715   AAPotentialConstantValuesArgument(const IRPosition &IRP, Attributor &A)
8716       : Base(IRP, A) {}
8717 
8718   /// See AbstractAttribute::initialize(..).
8719   void initialize(Attributor &A) override {
8720     if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
8721       indicatePessimisticFixpoint();
8722     } else {
8723       Base::initialize(A);
8724     }
8725   }
8726 
8727   /// See AbstractAttribute::trackStatistics()
8728   void trackStatistics() const override {
8729     STATS_DECLTRACK_ARG_ATTR(potential_values)
8730   }
8731 };
8732 
8733 struct AAPotentialConstantValuesReturned
8734     : AAReturnedFromReturnedValues<AAPotentialConstantValues,
8735                                    AAPotentialConstantValuesImpl> {
8736   using Base = AAReturnedFromReturnedValues<AAPotentialConstantValues,
8737                                             AAPotentialConstantValuesImpl>;
8738   AAPotentialConstantValuesReturned(const IRPosition &IRP, Attributor &A)
8739       : Base(IRP, A) {}
8740 
8741   /// See AbstractAttribute::trackStatistics()
8742   void trackStatistics() const override {
8743     STATS_DECLTRACK_FNRET_ATTR(potential_values)
8744   }
8745 };
8746 
8747 struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
8748   AAPotentialConstantValuesFloating(const IRPosition &IRP, Attributor &A)
8749       : AAPotentialConstantValuesImpl(IRP, A) {}
8750 
8751   /// See AbstractAttribute::initialize(..).
8752   void initialize(Attributor &A) override {
8753     AAPotentialConstantValuesImpl::initialize(A);
8754     if (isAtFixpoint())
8755       return;
8756 
8757     Value &V = getAssociatedValue();
8758 
8759     if (auto *C = dyn_cast<ConstantInt>(&V)) {
8760       unionAssumed(C->getValue());
8761       indicateOptimisticFixpoint();
8762       return;
8763     }
8764 
8765     if (isa<UndefValue>(&V)) {
8766       unionAssumedWithUndef();
8767       indicateOptimisticFixpoint();
8768       return;
8769     }
8770 
8771     if (isa<BinaryOperator>(&V) || isa<ICmpInst>(&V) || isa<CastInst>(&V))
8772       return;
8773 
8774     if (isa<SelectInst>(V) || isa<PHINode>(V) || isa<LoadInst>(V))
8775       return;
8776 
8777     indicatePessimisticFixpoint();
8778 
8779     LLVM_DEBUG(dbgs() << "[AAPotentialConstantValues] We give up: "
8780                       << getAssociatedValue() << "\n");
8781   }
8782 
8783   static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS,
8784                                 const APInt &RHS) {
8785     return ICmpInst::compare(LHS, RHS, ICI->getPredicate());
8786   }
8787 
8788   static APInt calculateCastInst(const CastInst *CI, const APInt &Src,
8789                                  uint32_t ResultBitWidth) {
8790     Instruction::CastOps CastOp = CI->getOpcode();
8791     switch (CastOp) {
8792     default:
8793       llvm_unreachable("unsupported or not integer cast");
8794     case Instruction::Trunc:
8795       return Src.trunc(ResultBitWidth);
8796     case Instruction::SExt:
8797       return Src.sext(ResultBitWidth);
8798     case Instruction::ZExt:
8799       return Src.zext(ResultBitWidth);
8800     case Instruction::BitCast:
8801       return Src;
8802     }
8803   }
8804 
8805   static APInt calculateBinaryOperator(const BinaryOperator *BinOp,
8806                                        const APInt &LHS, const APInt &RHS,
8807                                        bool &SkipOperation, bool &Unsupported) {
8808     Instruction::BinaryOps BinOpcode = BinOp->getOpcode();
8809     // Unsupported is set to true when the binary operator is not supported.
8810     // SkipOperation is set to true when UB occur with the given operand pair
8811     // (LHS, RHS).
8812     // TODO: we should look at nsw and nuw keywords to handle operations
8813     //       that create poison or undef value.
8814     switch (BinOpcode) {
8815     default:
8816       Unsupported = true;
8817       return LHS;
8818     case Instruction::Add:
8819       return LHS + RHS;
8820     case Instruction::Sub:
8821       return LHS - RHS;
8822     case Instruction::Mul:
8823       return LHS * RHS;
8824     case Instruction::UDiv:
8825       if (RHS.isZero()) {
8826         SkipOperation = true;
8827         return LHS;
8828       }
8829       return LHS.udiv(RHS);
8830     case Instruction::SDiv:
8831       if (RHS.isZero()) {
8832         SkipOperation = true;
8833         return LHS;
8834       }
8835       return LHS.sdiv(RHS);
8836     case Instruction::URem:
8837       if (RHS.isZero()) {
8838         SkipOperation = true;
8839         return LHS;
8840       }
8841       return LHS.urem(RHS);
8842     case Instruction::SRem:
8843       if (RHS.isZero()) {
8844         SkipOperation = true;
8845         return LHS;
8846       }
8847       return LHS.srem(RHS);
8848     case Instruction::Shl:
8849       return LHS.shl(RHS);
8850     case Instruction::LShr:
8851       return LHS.lshr(RHS);
8852     case Instruction::AShr:
8853       return LHS.ashr(RHS);
8854     case Instruction::And:
8855       return LHS & RHS;
8856     case Instruction::Or:
8857       return LHS | RHS;
8858     case Instruction::Xor:
8859       return LHS ^ RHS;
8860     }
8861   }
8862 
8863   bool calculateBinaryOperatorAndTakeUnion(const BinaryOperator *BinOp,
8864                                            const APInt &LHS, const APInt &RHS) {
8865     bool SkipOperation = false;
8866     bool Unsupported = false;
8867     APInt Result =
8868         calculateBinaryOperator(BinOp, LHS, RHS, SkipOperation, Unsupported);
8869     if (Unsupported)
8870       return false;
8871     // If SkipOperation is true, we can ignore this operand pair (L, R).
8872     if (!SkipOperation)
8873       unionAssumed(Result);
8874     return isValidState();
8875   }
8876 
8877   ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) {
8878     auto AssumedBefore = getAssumed();
8879     Value *LHS = ICI->getOperand(0);
8880     Value *RHS = ICI->getOperand(1);
8881 
8882     bool LHSContainsUndef = false, RHSContainsUndef = false;
8883     SetTy LHSAAPVS, RHSAAPVS;
8884     if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS,
8885                                    LHSContainsUndef) ||
8886         !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS,
8887                                    RHSContainsUndef))
8888       return indicatePessimisticFixpoint();
8889 
8890     // TODO: make use of undef flag to limit potential values aggressively.
8891     bool MaybeTrue = false, MaybeFalse = false;
8892     const APInt Zero(RHS->getType()->getIntegerBitWidth(), 0);
8893     if (LHSContainsUndef && RHSContainsUndef) {
8894       // The result of any comparison between undefs can be soundly replaced
8895       // with undef.
8896       unionAssumedWithUndef();
8897     } else if (LHSContainsUndef) {
8898       for (const APInt &R : RHSAAPVS) {
8899         bool CmpResult = calculateICmpInst(ICI, Zero, R);
8900         MaybeTrue |= CmpResult;
8901         MaybeFalse |= !CmpResult;
8902         if (MaybeTrue & MaybeFalse)
8903           return indicatePessimisticFixpoint();
8904       }
8905     } else if (RHSContainsUndef) {
8906       for (const APInt &L : LHSAAPVS) {
8907         bool CmpResult = calculateICmpInst(ICI, L, Zero);
8908         MaybeTrue |= CmpResult;
8909         MaybeFalse |= !CmpResult;
8910         if (MaybeTrue & MaybeFalse)
8911           return indicatePessimisticFixpoint();
8912       }
8913     } else {
8914       for (const APInt &L : LHSAAPVS) {
8915         for (const APInt &R : RHSAAPVS) {
8916           bool CmpResult = calculateICmpInst(ICI, L, R);
8917           MaybeTrue |= CmpResult;
8918           MaybeFalse |= !CmpResult;
8919           if (MaybeTrue & MaybeFalse)
8920             return indicatePessimisticFixpoint();
8921         }
8922       }
8923     }
8924     if (MaybeTrue)
8925       unionAssumed(APInt(/* numBits */ 1, /* val */ 1));
8926     if (MaybeFalse)
8927       unionAssumed(APInt(/* numBits */ 1, /* val */ 0));
8928     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
8929                                          : ChangeStatus::CHANGED;
8930   }
8931 
8932   ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) {
8933     auto AssumedBefore = getAssumed();
8934     Value *LHS = SI->getTrueValue();
8935     Value *RHS = SI->getFalseValue();
8936 
8937     bool UsedAssumedInformation = false;
8938     Optional<Constant *> C = A.getAssumedConstant(*SI->getCondition(), *this,
8939                                                   UsedAssumedInformation);
8940 
8941     // Check if we only need one operand.
8942     bool OnlyLeft = false, OnlyRight = false;
8943     if (C && *C && (*C)->isOneValue())
8944       OnlyLeft = true;
8945     else if (C && *C && (*C)->isZeroValue())
8946       OnlyRight = true;
8947 
8948     bool LHSContainsUndef = false, RHSContainsUndef = false;
8949     SetTy LHSAAPVS, RHSAAPVS;
8950     if (!OnlyRight && !fillSetWithConstantValues(A, IRPosition::value(*LHS),
8951                                                  LHSAAPVS, LHSContainsUndef))
8952       return indicatePessimisticFixpoint();
8953 
8954     if (!OnlyLeft && !fillSetWithConstantValues(A, IRPosition::value(*RHS),
8955                                                 RHSAAPVS, RHSContainsUndef))
8956       return indicatePessimisticFixpoint();
8957 
8958     if (OnlyLeft || OnlyRight) {
8959       // select (true/false), lhs, rhs
8960       auto *OpAA = OnlyLeft ? &LHSAAPVS : &RHSAAPVS;
8961       auto Undef = OnlyLeft ? LHSContainsUndef : RHSContainsUndef;
8962 
8963       if (Undef)
8964         unionAssumedWithUndef();
8965       else {
8966         for (auto &It : *OpAA)
8967           unionAssumed(It);
8968       }
8969 
8970     } else if (LHSContainsUndef && RHSContainsUndef) {
8971       // select i1 *, undef , undef => undef
8972       unionAssumedWithUndef();
8973     } else {
8974       for (auto &It : LHSAAPVS)
8975         unionAssumed(It);
8976       for (auto &It : RHSAAPVS)
8977         unionAssumed(It);
8978     }
8979     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
8980                                          : ChangeStatus::CHANGED;
8981   }
8982 
8983   ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) {
8984     auto AssumedBefore = getAssumed();
8985     if (!CI->isIntegerCast())
8986       return indicatePessimisticFixpoint();
8987     assert(CI->getNumOperands() == 1 && "Expected cast to be unary!");
8988     uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth();
8989     Value *Src = CI->getOperand(0);
8990 
8991     bool SrcContainsUndef = false;
8992     SetTy SrcPVS;
8993     if (!fillSetWithConstantValues(A, IRPosition::value(*Src), SrcPVS,
8994                                    SrcContainsUndef))
8995       return indicatePessimisticFixpoint();
8996 
8997     if (SrcContainsUndef)
8998       unionAssumedWithUndef();
8999     else {
9000       for (const APInt &S : SrcPVS) {
9001         APInt T = calculateCastInst(CI, S, ResultBitWidth);
9002         unionAssumed(T);
9003       }
9004     }
9005     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9006                                          : ChangeStatus::CHANGED;
9007   }
9008 
9009   ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) {
9010     auto AssumedBefore = getAssumed();
9011     Value *LHS = BinOp->getOperand(0);
9012     Value *RHS = BinOp->getOperand(1);
9013 
9014     bool LHSContainsUndef = false, RHSContainsUndef = false;
9015     SetTy LHSAAPVS, RHSAAPVS;
9016     if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS,
9017                                    LHSContainsUndef) ||
9018         !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS,
9019                                    RHSContainsUndef))
9020       return indicatePessimisticFixpoint();
9021 
9022     const APInt Zero = APInt(LHS->getType()->getIntegerBitWidth(), 0);
9023 
9024     // TODO: make use of undef flag to limit potential values aggressively.
9025     if (LHSContainsUndef && RHSContainsUndef) {
9026       if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, Zero))
9027         return indicatePessimisticFixpoint();
9028     } else if (LHSContainsUndef) {
9029       for (const APInt &R : RHSAAPVS) {
9030         if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, R))
9031           return indicatePessimisticFixpoint();
9032       }
9033     } else if (RHSContainsUndef) {
9034       for (const APInt &L : LHSAAPVS) {
9035         if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, Zero))
9036           return indicatePessimisticFixpoint();
9037       }
9038     } else {
9039       for (const APInt &L : LHSAAPVS) {
9040         for (const APInt &R : RHSAAPVS) {
9041           if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R))
9042             return indicatePessimisticFixpoint();
9043         }
9044       }
9045     }
9046     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9047                                          : ChangeStatus::CHANGED;
9048   }
9049 
9050   /// See AbstractAttribute::updateImpl(...).
9051   ChangeStatus updateImpl(Attributor &A) override {
9052     Value &V = getAssociatedValue();
9053     Instruction *I = dyn_cast<Instruction>(&V);
9054 
9055     if (auto *ICI = dyn_cast<ICmpInst>(I))
9056       return updateWithICmpInst(A, ICI);
9057 
9058     if (auto *SI = dyn_cast<SelectInst>(I))
9059       return updateWithSelectInst(A, SI);
9060 
9061     if (auto *CI = dyn_cast<CastInst>(I))
9062       return updateWithCastInst(A, CI);
9063 
9064     if (auto *BinOp = dyn_cast<BinaryOperator>(I))
9065       return updateWithBinaryOperator(A, BinOp);
9066 
9067     return indicatePessimisticFixpoint();
9068   }
9069 
9070   /// See AbstractAttribute::trackStatistics()
9071   void trackStatistics() const override {
9072     STATS_DECLTRACK_FLOATING_ATTR(potential_values)
9073   }
9074 };
9075 
9076 struct AAPotentialConstantValuesFunction : AAPotentialConstantValuesImpl {
9077   AAPotentialConstantValuesFunction(const IRPosition &IRP, Attributor &A)
9078       : AAPotentialConstantValuesImpl(IRP, A) {}
9079 
9080   /// See AbstractAttribute::initialize(...).
9081   ChangeStatus updateImpl(Attributor &A) override {
9082     llvm_unreachable(
9083         "AAPotentialConstantValues(Function|CallSite)::updateImpl will "
9084         "not be called");
9085   }
9086 
9087   /// See AbstractAttribute::trackStatistics()
9088   void trackStatistics() const override {
9089     STATS_DECLTRACK_FN_ATTR(potential_values)
9090   }
9091 };
9092 
9093 struct AAPotentialConstantValuesCallSite : AAPotentialConstantValuesFunction {
9094   AAPotentialConstantValuesCallSite(const IRPosition &IRP, Attributor &A)
9095       : AAPotentialConstantValuesFunction(IRP, A) {}
9096 
9097   /// See AbstractAttribute::trackStatistics()
9098   void trackStatistics() const override {
9099     STATS_DECLTRACK_CS_ATTR(potential_values)
9100   }
9101 };
9102 
9103 struct AAPotentialConstantValuesCallSiteReturned
9104     : AACallSiteReturnedFromReturned<AAPotentialConstantValues,
9105                                      AAPotentialConstantValuesImpl> {
9106   AAPotentialConstantValuesCallSiteReturned(const IRPosition &IRP,
9107                                             Attributor &A)
9108       : AACallSiteReturnedFromReturned<AAPotentialConstantValues,
9109                                        AAPotentialConstantValuesImpl>(IRP, A) {}
9110 
9111   /// See AbstractAttribute::trackStatistics()
9112   void trackStatistics() const override {
9113     STATS_DECLTRACK_CSRET_ATTR(potential_values)
9114   }
9115 };
9116 
9117 struct AAPotentialConstantValuesCallSiteArgument
9118     : AAPotentialConstantValuesFloating {
9119   AAPotentialConstantValuesCallSiteArgument(const IRPosition &IRP,
9120                                             Attributor &A)
9121       : AAPotentialConstantValuesFloating(IRP, A) {}
9122 
9123   /// See AbstractAttribute::initialize(..).
9124   void initialize(Attributor &A) override {
9125     AAPotentialConstantValuesImpl::initialize(A);
9126     if (isAtFixpoint())
9127       return;
9128 
9129     Value &V = getAssociatedValue();
9130 
9131     if (auto *C = dyn_cast<ConstantInt>(&V)) {
9132       unionAssumed(C->getValue());
9133       indicateOptimisticFixpoint();
9134       return;
9135     }
9136 
9137     if (isa<UndefValue>(&V)) {
9138       unionAssumedWithUndef();
9139       indicateOptimisticFixpoint();
9140       return;
9141     }
9142   }
9143 
9144   /// See AbstractAttribute::updateImpl(...).
9145   ChangeStatus updateImpl(Attributor &A) override {
9146     Value &V = getAssociatedValue();
9147     auto AssumedBefore = getAssumed();
9148     auto &AA = A.getAAFor<AAPotentialConstantValues>(
9149         *this, IRPosition::value(V), DepClassTy::REQUIRED);
9150     const auto &S = AA.getAssumed();
9151     unionAssumed(S);
9152     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9153                                          : ChangeStatus::CHANGED;
9154   }
9155 
9156   /// See AbstractAttribute::trackStatistics()
9157   void trackStatistics() const override {
9158     STATS_DECLTRACK_CSARG_ATTR(potential_values)
9159   }
9160 };
9161 
9162 /// ------------------------ NoUndef Attribute ---------------------------------
9163 struct AANoUndefImpl : AANoUndef {
9164   AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {}
9165 
9166   /// See AbstractAttribute::initialize(...).
9167   void initialize(Attributor &A) override {
9168     if (getIRPosition().hasAttr({Attribute::NoUndef})) {
9169       indicateOptimisticFixpoint();
9170       return;
9171     }
9172     Value &V = getAssociatedValue();
9173     if (isa<UndefValue>(V))
9174       indicatePessimisticFixpoint();
9175     else if (isa<FreezeInst>(V))
9176       indicateOptimisticFixpoint();
9177     else if (getPositionKind() != IRPosition::IRP_RETURNED &&
9178              isGuaranteedNotToBeUndefOrPoison(&V))
9179       indicateOptimisticFixpoint();
9180     else
9181       AANoUndef::initialize(A);
9182   }
9183 
9184   /// See followUsesInMBEC
9185   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
9186                        AANoUndef::StateType &State) {
9187     const Value *UseV = U->get();
9188     const DominatorTree *DT = nullptr;
9189     AssumptionCache *AC = nullptr;
9190     InformationCache &InfoCache = A.getInfoCache();
9191     if (Function *F = getAnchorScope()) {
9192       DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
9193       AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
9194     }
9195     State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, AC, I, DT));
9196     bool TrackUse = false;
9197     // Track use for instructions which must produce undef or poison bits when
9198     // at least one operand contains such bits.
9199     if (isa<CastInst>(*I) || isa<GetElementPtrInst>(*I))
9200       TrackUse = true;
9201     return TrackUse;
9202   }
9203 
9204   /// See AbstractAttribute::getAsStr().
9205   const std::string getAsStr() const override {
9206     return getAssumed() ? "noundef" : "may-undef-or-poison";
9207   }
9208 
9209   ChangeStatus manifest(Attributor &A) override {
9210     // We don't manifest noundef attribute for dead positions because the
9211     // associated values with dead positions would be replaced with undef
9212     // values.
9213     bool UsedAssumedInformation = false;
9214     if (A.isAssumedDead(getIRPosition(), nullptr, nullptr,
9215                         UsedAssumedInformation))
9216       return ChangeStatus::UNCHANGED;
9217     // A position whose simplified value does not have any value is
9218     // considered to be dead. We don't manifest noundef in such positions for
9219     // the same reason above.
9220     if (!A.getAssumedSimplified(getIRPosition(), *this, UsedAssumedInformation,
9221                                 AA::Interprocedural)
9222              .has_value())
9223       return ChangeStatus::UNCHANGED;
9224     return AANoUndef::manifest(A);
9225   }
9226 };
9227 
9228 struct AANoUndefFloating : public AANoUndefImpl {
9229   AANoUndefFloating(const IRPosition &IRP, Attributor &A)
9230       : AANoUndefImpl(IRP, A) {}
9231 
9232   /// See AbstractAttribute::initialize(...).
9233   void initialize(Attributor &A) override {
9234     AANoUndefImpl::initialize(A);
9235     if (!getState().isAtFixpoint())
9236       if (Instruction *CtxI = getCtxI())
9237         followUsesInMBEC(*this, A, getState(), *CtxI);
9238   }
9239 
9240   /// See AbstractAttribute::updateImpl(...).
9241   ChangeStatus updateImpl(Attributor &A) override {
9242 
9243     SmallVector<AA::ValueAndContext> Values;
9244     bool UsedAssumedInformation = false;
9245     if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
9246                                       AA::AnyScope, UsedAssumedInformation)) {
9247       Values.push_back({getAssociatedValue(), getCtxI()});
9248     }
9249 
9250     StateType T;
9251     auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool {
9252       const auto &AA = A.getAAFor<AANoUndef>(*this, IRPosition::value(V),
9253                                              DepClassTy::REQUIRED);
9254       if (this == &AA) {
9255         T.indicatePessimisticFixpoint();
9256       } else {
9257         const AANoUndef::StateType &S =
9258             static_cast<const AANoUndef::StateType &>(AA.getState());
9259         T ^= S;
9260       }
9261       return T.isValidState();
9262     };
9263 
9264     for (const auto &VAC : Values)
9265       if (!VisitValueCB(*VAC.getValue(), VAC.getCtxI()))
9266         return indicatePessimisticFixpoint();
9267 
9268     return clampStateAndIndicateChange(getState(), T);
9269   }
9270 
9271   /// See AbstractAttribute::trackStatistics()
9272   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
9273 };
9274 
9275 struct AANoUndefReturned final
9276     : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> {
9277   AANoUndefReturned(const IRPosition &IRP, Attributor &A)
9278       : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>(IRP, A) {}
9279 
9280   /// See AbstractAttribute::trackStatistics()
9281   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
9282 };
9283 
9284 struct AANoUndefArgument final
9285     : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> {
9286   AANoUndefArgument(const IRPosition &IRP, Attributor &A)
9287       : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {}
9288 
9289   /// See AbstractAttribute::trackStatistics()
9290   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) }
9291 };
9292 
9293 struct AANoUndefCallSiteArgument final : AANoUndefFloating {
9294   AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A)
9295       : AANoUndefFloating(IRP, A) {}
9296 
9297   /// See AbstractAttribute::trackStatistics()
9298   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) }
9299 };
9300 
9301 struct AANoUndefCallSiteReturned final
9302     : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl> {
9303   AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A)
9304       : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl>(IRP, A) {}
9305 
9306   /// See AbstractAttribute::trackStatistics()
9307   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) }
9308 };
9309 
9310 struct AACallEdgesImpl : public AACallEdges {
9311   AACallEdgesImpl(const IRPosition &IRP, Attributor &A) : AACallEdges(IRP, A) {}
9312 
9313   virtual const SetVector<Function *> &getOptimisticEdges() const override {
9314     return CalledFunctions;
9315   }
9316 
9317   virtual bool hasUnknownCallee() const override { return HasUnknownCallee; }
9318 
9319   virtual bool hasNonAsmUnknownCallee() const override {
9320     return HasUnknownCalleeNonAsm;
9321   }
9322 
9323   const std::string getAsStr() const override {
9324     return "CallEdges[" + std::to_string(HasUnknownCallee) + "," +
9325            std::to_string(CalledFunctions.size()) + "]";
9326   }
9327 
9328   void trackStatistics() const override {}
9329 
9330 protected:
9331   void addCalledFunction(Function *Fn, ChangeStatus &Change) {
9332     if (CalledFunctions.insert(Fn)) {
9333       Change = ChangeStatus::CHANGED;
9334       LLVM_DEBUG(dbgs() << "[AACallEdges] New call edge: " << Fn->getName()
9335                         << "\n");
9336     }
9337   }
9338 
9339   void setHasUnknownCallee(bool NonAsm, ChangeStatus &Change) {
9340     if (!HasUnknownCallee)
9341       Change = ChangeStatus::CHANGED;
9342     if (NonAsm && !HasUnknownCalleeNonAsm)
9343       Change = ChangeStatus::CHANGED;
9344     HasUnknownCalleeNonAsm |= NonAsm;
9345     HasUnknownCallee = true;
9346   }
9347 
9348 private:
9349   /// Optimistic set of functions that might be called by this position.
9350   SetVector<Function *> CalledFunctions;
9351 
9352   /// Is there any call with a unknown callee.
9353   bool HasUnknownCallee = false;
9354 
9355   /// Is there any call with a unknown callee, excluding any inline asm.
9356   bool HasUnknownCalleeNonAsm = false;
9357 };
9358 
9359 struct AACallEdgesCallSite : public AACallEdgesImpl {
9360   AACallEdgesCallSite(const IRPosition &IRP, Attributor &A)
9361       : AACallEdgesImpl(IRP, A) {}
9362   /// See AbstractAttribute::updateImpl(...).
9363   ChangeStatus updateImpl(Attributor &A) override {
9364     ChangeStatus Change = ChangeStatus::UNCHANGED;
9365 
9366     auto VisitValue = [&](Value &V, const Instruction *CtxI) -> bool {
9367       if (Function *Fn = dyn_cast<Function>(&V)) {
9368         addCalledFunction(Fn, Change);
9369       } else {
9370         LLVM_DEBUG(dbgs() << "[AACallEdges] Unrecognized value: " << V << "\n");
9371         setHasUnknownCallee(true, Change);
9372       }
9373 
9374       // Explore all values.
9375       return true;
9376     };
9377 
9378     SmallVector<AA::ValueAndContext> Values;
9379     // Process any value that we might call.
9380     auto ProcessCalledOperand = [&](Value *V, Instruction *CtxI) {
9381       bool UsedAssumedInformation = false;
9382       Values.clear();
9383       if (!A.getAssumedSimplifiedValues(IRPosition::value(*V), *this, Values,
9384                                         AA::AnyScope, UsedAssumedInformation)) {
9385         Values.push_back({*V, CtxI});
9386       }
9387       for (auto &VAC : Values)
9388         VisitValue(*VAC.getValue(), VAC.getCtxI());
9389     };
9390 
9391     CallBase *CB = cast<CallBase>(getCtxI());
9392 
9393     if (CB->isInlineAsm()) {
9394       if (!hasAssumption(*CB->getCaller(), "ompx_no_call_asm") &&
9395           !hasAssumption(*CB, "ompx_no_call_asm"))
9396         setHasUnknownCallee(false, Change);
9397       return Change;
9398     }
9399 
9400     // Process callee metadata if available.
9401     if (auto *MD = getCtxI()->getMetadata(LLVMContext::MD_callees)) {
9402       for (auto &Op : MD->operands()) {
9403         Function *Callee = mdconst::dyn_extract_or_null<Function>(Op);
9404         if (Callee)
9405           addCalledFunction(Callee, Change);
9406       }
9407       return Change;
9408     }
9409 
9410     // The most simple case.
9411     ProcessCalledOperand(CB->getCalledOperand(), CB);
9412 
9413     // Process callback functions.
9414     SmallVector<const Use *, 4u> CallbackUses;
9415     AbstractCallSite::getCallbackUses(*CB, CallbackUses);
9416     for (const Use *U : CallbackUses)
9417       ProcessCalledOperand(U->get(), CB);
9418 
9419     return Change;
9420   }
9421 };
9422 
9423 struct AACallEdgesFunction : public AACallEdgesImpl {
9424   AACallEdgesFunction(const IRPosition &IRP, Attributor &A)
9425       : AACallEdgesImpl(IRP, A) {}
9426 
9427   /// See AbstractAttribute::updateImpl(...).
9428   ChangeStatus updateImpl(Attributor &A) override {
9429     ChangeStatus Change = ChangeStatus::UNCHANGED;
9430 
9431     auto ProcessCallInst = [&](Instruction &Inst) {
9432       CallBase &CB = cast<CallBase>(Inst);
9433 
9434       auto &CBEdges = A.getAAFor<AACallEdges>(
9435           *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
9436       if (CBEdges.hasNonAsmUnknownCallee())
9437         setHasUnknownCallee(true, Change);
9438       if (CBEdges.hasUnknownCallee())
9439         setHasUnknownCallee(false, Change);
9440 
9441       for (Function *F : CBEdges.getOptimisticEdges())
9442         addCalledFunction(F, Change);
9443 
9444       return true;
9445     };
9446 
9447     // Visit all callable instructions.
9448     bool UsedAssumedInformation = false;
9449     if (!A.checkForAllCallLikeInstructions(ProcessCallInst, *this,
9450                                            UsedAssumedInformation,
9451                                            /* CheckBBLivenessOnly */ true)) {
9452       // If we haven't looked at all call like instructions, assume that there
9453       // are unknown callees.
9454       setHasUnknownCallee(true, Change);
9455     }
9456 
9457     return Change;
9458   }
9459 };
9460 
9461 struct AAFunctionReachabilityFunction : public AAFunctionReachability {
9462 private:
9463   struct QuerySet {
9464     void markReachable(const Function &Fn) {
9465       Reachable.insert(&Fn);
9466       Unreachable.erase(&Fn);
9467     }
9468 
9469     /// If there is no information about the function None is returned.
9470     Optional<bool> isCachedReachable(const Function &Fn) {
9471       // Assume that we can reach the function.
9472       // TODO: Be more specific with the unknown callee.
9473       if (CanReachUnknownCallee)
9474         return true;
9475 
9476       if (Reachable.count(&Fn))
9477         return true;
9478 
9479       if (Unreachable.count(&Fn))
9480         return false;
9481 
9482       return llvm::None;
9483     }
9484 
9485     /// Set of functions that we know for sure is reachable.
9486     DenseSet<const Function *> Reachable;
9487 
9488     /// Set of functions that are unreachable, but might become reachable.
9489     DenseSet<const Function *> Unreachable;
9490 
9491     /// If we can reach a function with a call to a unknown function we assume
9492     /// that we can reach any function.
9493     bool CanReachUnknownCallee = false;
9494   };
9495 
9496   struct QueryResolver : public QuerySet {
9497     ChangeStatus update(Attributor &A, const AAFunctionReachability &AA,
9498                         ArrayRef<const AACallEdges *> AAEdgesList) {
9499       ChangeStatus Change = ChangeStatus::UNCHANGED;
9500 
9501       for (auto *AAEdges : AAEdgesList) {
9502         if (AAEdges->hasUnknownCallee()) {
9503           if (!CanReachUnknownCallee) {
9504             LLVM_DEBUG(dbgs()
9505                        << "[QueryResolver] Edges include unknown callee!\n");
9506             Change = ChangeStatus::CHANGED;
9507           }
9508           CanReachUnknownCallee = true;
9509           return Change;
9510         }
9511       }
9512 
9513       for (const Function *Fn : make_early_inc_range(Unreachable)) {
9514         if (checkIfReachable(A, AA, AAEdgesList, *Fn)) {
9515           Change = ChangeStatus::CHANGED;
9516           markReachable(*Fn);
9517         }
9518       }
9519       return Change;
9520     }
9521 
9522     bool isReachable(Attributor &A, AAFunctionReachability &AA,
9523                      ArrayRef<const AACallEdges *> AAEdgesList,
9524                      const Function &Fn) {
9525       Optional<bool> Cached = isCachedReachable(Fn);
9526       if (Cached)
9527         return Cached.value();
9528 
9529       // The query was not cached, thus it is new. We need to request an update
9530       // explicitly to make sure this the information is properly run to a
9531       // fixpoint.
9532       A.registerForUpdate(AA);
9533 
9534       // We need to assume that this function can't reach Fn to prevent
9535       // an infinite loop if this function is recursive.
9536       Unreachable.insert(&Fn);
9537 
9538       bool Result = checkIfReachable(A, AA, AAEdgesList, Fn);
9539       if (Result)
9540         markReachable(Fn);
9541       return Result;
9542     }
9543 
9544     bool checkIfReachable(Attributor &A, const AAFunctionReachability &AA,
9545                           ArrayRef<const AACallEdges *> AAEdgesList,
9546                           const Function &Fn) const {
9547 
9548       // Handle the most trivial case first.
9549       for (auto *AAEdges : AAEdgesList) {
9550         const SetVector<Function *> &Edges = AAEdges->getOptimisticEdges();
9551 
9552         if (Edges.count(const_cast<Function *>(&Fn)))
9553           return true;
9554       }
9555 
9556       SmallVector<const AAFunctionReachability *, 8> Deps;
9557       for (auto &AAEdges : AAEdgesList) {
9558         const SetVector<Function *> &Edges = AAEdges->getOptimisticEdges();
9559 
9560         for (Function *Edge : Edges) {
9561           // Functions that do not call back into the module can be ignored.
9562           if (Edge->hasFnAttribute(Attribute::NoCallback))
9563             continue;
9564 
9565           // We don't need a dependency if the result is reachable.
9566           const AAFunctionReachability &EdgeReachability =
9567               A.getAAFor<AAFunctionReachability>(
9568                   AA, IRPosition::function(*Edge), DepClassTy::NONE);
9569           Deps.push_back(&EdgeReachability);
9570 
9571           if (EdgeReachability.canReach(A, Fn))
9572             return true;
9573         }
9574       }
9575 
9576       // The result is false for now, set dependencies and leave.
9577       for (auto *Dep : Deps)
9578         A.recordDependence(*Dep, AA, DepClassTy::REQUIRED);
9579 
9580       return false;
9581     }
9582   };
9583 
9584   /// Get call edges that can be reached by this instruction.
9585   bool getReachableCallEdges(Attributor &A, const AAReachability &Reachability,
9586                              const Instruction &Inst,
9587                              SmallVector<const AACallEdges *> &Result) const {
9588     // Determine call like instructions that we can reach from the inst.
9589     auto CheckCallBase = [&](Instruction &CBInst) {
9590       if (!Reachability.isAssumedReachable(A, Inst, CBInst))
9591         return true;
9592 
9593       auto &CB = cast<CallBase>(CBInst);
9594       const AACallEdges &AAEdges = A.getAAFor<AACallEdges>(
9595           *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
9596 
9597       Result.push_back(&AAEdges);
9598       return true;
9599     };
9600 
9601     bool UsedAssumedInformation = false;
9602     return A.checkForAllCallLikeInstructions(CheckCallBase, *this,
9603                                              UsedAssumedInformation,
9604                                              /* CheckBBLivenessOnly */ true);
9605   }
9606 
9607 public:
9608   AAFunctionReachabilityFunction(const IRPosition &IRP, Attributor &A)
9609       : AAFunctionReachability(IRP, A) {}
9610 
9611   bool canReach(Attributor &A, const Function &Fn) const override {
9612     if (!isValidState())
9613       return true;
9614 
9615     const AACallEdges &AAEdges =
9616         A.getAAFor<AACallEdges>(*this, getIRPosition(), DepClassTy::REQUIRED);
9617 
9618     // Attributor returns attributes as const, so this function has to be
9619     // const for users of this attribute to use it without having to do
9620     // a const_cast.
9621     // This is a hack for us to be able to cache queries.
9622     auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this);
9623     bool Result = NonConstThis->WholeFunction.isReachable(A, *NonConstThis,
9624                                                           {&AAEdges}, Fn);
9625 
9626     return Result;
9627   }
9628 
9629   /// Can \p CB reach \p Fn
9630   bool canReach(Attributor &A, CallBase &CB,
9631                 const Function &Fn) const override {
9632     if (!isValidState())
9633       return true;
9634 
9635     const AACallEdges &AAEdges = A.getAAFor<AACallEdges>(
9636         *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
9637 
9638     // Attributor returns attributes as const, so this function has to be
9639     // const for users of this attribute to use it without having to do
9640     // a const_cast.
9641     // This is a hack for us to be able to cache queries.
9642     auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this);
9643     QueryResolver &CBQuery = NonConstThis->CBQueries[&CB];
9644 
9645     bool Result = CBQuery.isReachable(A, *NonConstThis, {&AAEdges}, Fn);
9646 
9647     return Result;
9648   }
9649 
9650   bool instructionCanReach(Attributor &A, const Instruction &Inst,
9651                            const Function &Fn,
9652                            bool UseBackwards) const override {
9653     if (!isValidState())
9654       return true;
9655 
9656     if (UseBackwards)
9657       return AA::isPotentiallyReachable(A, Inst, Fn, *this, nullptr);
9658 
9659     const auto &Reachability = A.getAAFor<AAReachability>(
9660         *this, IRPosition::function(*getAssociatedFunction()),
9661         DepClassTy::REQUIRED);
9662 
9663     SmallVector<const AACallEdges *> CallEdges;
9664     bool AllKnown = getReachableCallEdges(A, Reachability, Inst, CallEdges);
9665     // Attributor returns attributes as const, so this function has to be
9666     // const for users of this attribute to use it without having to do
9667     // a const_cast.
9668     // This is a hack for us to be able to cache queries.
9669     auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this);
9670     QueryResolver &InstQSet = NonConstThis->InstQueries[&Inst];
9671     if (!AllKnown) {
9672       LLVM_DEBUG(dbgs() << "[AAReachability] Not all reachable edges known, "
9673                            "may reach unknown callee!\n");
9674       InstQSet.CanReachUnknownCallee = true;
9675     }
9676 
9677     return InstQSet.isReachable(A, *NonConstThis, CallEdges, Fn);
9678   }
9679 
9680   /// See AbstractAttribute::updateImpl(...).
9681   ChangeStatus updateImpl(Attributor &A) override {
9682     const AACallEdges &AAEdges =
9683         A.getAAFor<AACallEdges>(*this, getIRPosition(), DepClassTy::REQUIRED);
9684     ChangeStatus Change = ChangeStatus::UNCHANGED;
9685 
9686     Change |= WholeFunction.update(A, *this, {&AAEdges});
9687 
9688     for (auto &CBPair : CBQueries) {
9689       const AACallEdges &AAEdges = A.getAAFor<AACallEdges>(
9690           *this, IRPosition::callsite_function(*CBPair.first),
9691           DepClassTy::REQUIRED);
9692 
9693       Change |= CBPair.second.update(A, *this, {&AAEdges});
9694     }
9695 
9696     // Update the Instruction queries.
9697     if (!InstQueries.empty()) {
9698       const AAReachability *Reachability = &A.getAAFor<AAReachability>(
9699           *this, IRPosition::function(*getAssociatedFunction()),
9700           DepClassTy::REQUIRED);
9701 
9702       // Check for local callbases first.
9703       for (auto &InstPair : InstQueries) {
9704         SmallVector<const AACallEdges *> CallEdges;
9705         bool AllKnown =
9706             getReachableCallEdges(A, *Reachability, *InstPair.first, CallEdges);
9707         // Update will return change if we this effects any queries.
9708         if (!AllKnown) {
9709           LLVM_DEBUG(dbgs() << "[AAReachability] Not all reachable edges "
9710                                "known, may reach unknown callee!\n");
9711           InstPair.second.CanReachUnknownCallee = true;
9712         }
9713         Change |= InstPair.second.update(A, *this, CallEdges);
9714       }
9715     }
9716 
9717     return Change;
9718   }
9719 
9720   const std::string getAsStr() const override {
9721     size_t QueryCount =
9722         WholeFunction.Reachable.size() + WholeFunction.Unreachable.size();
9723 
9724     return "FunctionReachability [" +
9725            (canReachUnknownCallee()
9726                 ? "unknown"
9727                 : (std::to_string(WholeFunction.Reachable.size()) + "," +
9728                    std::to_string(QueryCount))) +
9729            "]";
9730   }
9731 
9732   void trackStatistics() const override {}
9733 
9734 private:
9735   bool canReachUnknownCallee() const override {
9736     return WholeFunction.CanReachUnknownCallee;
9737   }
9738 
9739   /// Used to answer if a the whole function can reacha a specific function.
9740   QueryResolver WholeFunction;
9741 
9742   /// Used to answer if a call base inside this function can reach a specific
9743   /// function.
9744   MapVector<const CallBase *, QueryResolver> CBQueries;
9745 
9746   /// This is for instruction queries than scan "forward".
9747   MapVector<const Instruction *, QueryResolver> InstQueries;
9748 };
9749 } // namespace
9750 
9751 template <typename AAType>
9752 static Optional<Constant *>
9753 askForAssumedConstant(Attributor &A, const AbstractAttribute &QueryingAA,
9754                       const IRPosition &IRP, Type &Ty) {
9755   if (!Ty.isIntegerTy())
9756     return nullptr;
9757 
9758   // This will also pass the call base context.
9759   const auto &AA = A.getAAFor<AAType>(QueryingAA, IRP, DepClassTy::NONE);
9760 
9761   Optional<Constant *> COpt = AA.getAssumedConstant(A);
9762 
9763   if (!COpt.has_value()) {
9764     A.recordDependence(AA, QueryingAA, DepClassTy::OPTIONAL);
9765     return llvm::None;
9766   }
9767   if (auto *C = COpt.value()) {
9768     A.recordDependence(AA, QueryingAA, DepClassTy::OPTIONAL);
9769     return C;
9770   }
9771   return nullptr;
9772 }
9773 
9774 Value *AAPotentialValues::getSingleValue(
9775     Attributor &A, const AbstractAttribute &AA, const IRPosition &IRP,
9776     SmallVectorImpl<AA::ValueAndContext> &Values) {
9777   Type &Ty = *IRP.getAssociatedType();
9778   Optional<Value *> V;
9779   for (auto &It : Values) {
9780     V = AA::combineOptionalValuesInAAValueLatice(V, It.getValue(), &Ty);
9781     if (V.has_value() && !V.value())
9782       break;
9783   }
9784   if (!V.has_value())
9785     return UndefValue::get(&Ty);
9786   return V.value();
9787 }
9788 
9789 namespace {
9790 struct AAPotentialValuesImpl : AAPotentialValues {
9791   using StateType = PotentialLLVMValuesState;
9792 
9793   AAPotentialValuesImpl(const IRPosition &IRP, Attributor &A)
9794       : AAPotentialValues(IRP, A) {}
9795 
9796   /// See AbstractAttribute::initialize(..).
9797   void initialize(Attributor &A) override {
9798     if (A.hasSimplificationCallback(getIRPosition())) {
9799       indicatePessimisticFixpoint();
9800       return;
9801     }
9802     Value *Stripped = getAssociatedValue().stripPointerCasts();
9803     if (isa<Constant>(Stripped)) {
9804       addValue(A, getState(), *Stripped, getCtxI(), AA::AnyScope,
9805                getAnchorScope());
9806       indicateOptimisticFixpoint();
9807       return;
9808     }
9809     AAPotentialValues::initialize(A);
9810   }
9811 
9812   /// See AbstractAttribute::getAsStr().
9813   const std::string getAsStr() const override {
9814     std::string Str;
9815     llvm::raw_string_ostream OS(Str);
9816     OS << getState();
9817     return OS.str();
9818   }
9819 
9820   template <typename AAType>
9821   static Optional<Value *> askOtherAA(Attributor &A,
9822                                       const AbstractAttribute &AA,
9823                                       const IRPosition &IRP, Type &Ty) {
9824     if (isa<Constant>(IRP.getAssociatedValue()))
9825       return &IRP.getAssociatedValue();
9826     Optional<Constant *> C = askForAssumedConstant<AAType>(A, AA, IRP, Ty);
9827     if (!C)
9828       return llvm::None;
9829     if (C.value())
9830       if (auto *CC = AA::getWithType(**C, Ty))
9831         return CC;
9832     return nullptr;
9833   }
9834 
9835   void addValue(Attributor &A, StateType &State, Value &V,
9836                 const Instruction *CtxI, AA::ValueScope S,
9837                 Function *AnchorScope) const {
9838 
9839     IRPosition ValIRP = IRPosition::value(V);
9840     if (auto *CB = dyn_cast_or_null<CallBase>(CtxI)) {
9841       for (auto &U : CB->args()) {
9842         if (U.get() != &V)
9843           continue;
9844         ValIRP = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
9845         break;
9846       }
9847     }
9848 
9849     Value *VPtr = &V;
9850     if (ValIRP.getAssociatedType()->isIntegerTy()) {
9851       Type &Ty = *getAssociatedType();
9852       Optional<Value *> SimpleV =
9853           askOtherAA<AAValueConstantRange>(A, *this, ValIRP, Ty);
9854       if (SimpleV.has_value() && !SimpleV.value()) {
9855         auto &PotentialConstantsAA = A.getAAFor<AAPotentialConstantValues>(
9856             *this, ValIRP, DepClassTy::OPTIONAL);
9857         if (PotentialConstantsAA.isValidState()) {
9858           for (auto &It : PotentialConstantsAA.getAssumedSet()) {
9859             State.unionAssumed({{*ConstantInt::get(&Ty, It), nullptr}, S});
9860           }
9861           assert(!PotentialConstantsAA.undefIsContained() &&
9862                  "Undef should be an explicit value!");
9863           return;
9864         }
9865       }
9866       if (!SimpleV.has_value())
9867         return;
9868 
9869       if (SimpleV.value())
9870         VPtr = SimpleV.value();
9871     }
9872 
9873     if (isa<ConstantInt>(VPtr))
9874       CtxI = nullptr;
9875     if (!AA::isValidInScope(*VPtr, AnchorScope))
9876       S = AA::ValueScope(S | AA::Interprocedural);
9877 
9878     State.unionAssumed({{*VPtr, CtxI}, S});
9879   }
9880 
9881   /// Helper struct to tie a value+context pair together with the scope for
9882   /// which this is the simplified version.
9883   struct ItemInfo {
9884     AA::ValueAndContext I;
9885     AA::ValueScope S;
9886   };
9887 
9888   bool recurseForValue(Attributor &A, const IRPosition &IRP, AA::ValueScope S) {
9889     SmallMapVector<AA::ValueAndContext, int, 8> ValueScopeMap;
9890     for (auto CS : {AA::Intraprocedural, AA::Interprocedural}) {
9891       if (!(CS & S))
9892         continue;
9893 
9894       bool UsedAssumedInformation = false;
9895       SmallVector<AA::ValueAndContext> Values;
9896       if (!A.getAssumedSimplifiedValues(IRP, this, Values, CS,
9897                                         UsedAssumedInformation))
9898         return false;
9899 
9900       for (auto &It : Values)
9901         ValueScopeMap[It] += CS;
9902     }
9903     for (auto &It : ValueScopeMap)
9904       addValue(A, getState(), *It.first.getValue(), It.first.getCtxI(),
9905                AA::ValueScope(It.second), getAnchorScope());
9906 
9907     return true;
9908   }
9909 
9910   void giveUpOnIntraprocedural(Attributor &A) {
9911     auto NewS = StateType::getBestState(getState());
9912     for (auto &It : getAssumedSet()) {
9913       if (It.second == AA::Intraprocedural)
9914         continue;
9915       addValue(A, NewS, *It.first.getValue(), It.first.getCtxI(),
9916                AA::Interprocedural, getAnchorScope());
9917     }
9918     assert(!undefIsContained() && "Undef should be an explicit value!");
9919     addValue(A, NewS, getAssociatedValue(), getCtxI(), AA::Intraprocedural,
9920              getAnchorScope());
9921     getState() = NewS;
9922   }
9923 
9924   /// See AbstractState::indicatePessimisticFixpoint(...).
9925   ChangeStatus indicatePessimisticFixpoint() override {
9926     getState() = StateType::getBestState(getState());
9927     getState().unionAssumed({{getAssociatedValue(), getCtxI()}, AA::AnyScope});
9928     AAPotentialValues::indicateOptimisticFixpoint();
9929     return ChangeStatus::CHANGED;
9930   }
9931 
9932   /// See AbstractAttribute::updateImpl(...).
9933   ChangeStatus updateImpl(Attributor &A) override {
9934     return indicatePessimisticFixpoint();
9935   }
9936 
9937   /// See AbstractAttribute::manifest(...).
9938   ChangeStatus manifest(Attributor &A) override {
9939     SmallVector<AA::ValueAndContext> Values;
9940     for (AA::ValueScope S : {AA::Interprocedural, AA::Intraprocedural}) {
9941       Values.clear();
9942       if (!getAssumedSimplifiedValues(A, Values, S))
9943         continue;
9944       Value &OldV = getAssociatedValue();
9945       if (isa<UndefValue>(OldV))
9946         continue;
9947       Value *NewV = getSingleValue(A, *this, getIRPosition(), Values);
9948       if (!NewV || NewV == &OldV)
9949         continue;
9950       if (getCtxI() &&
9951           !AA::isValidAtPosition({*NewV, *getCtxI()}, A.getInfoCache()))
9952         continue;
9953       if (A.changeAfterManifest(getIRPosition(), *NewV))
9954         return ChangeStatus::CHANGED;
9955     }
9956     return ChangeStatus::UNCHANGED;
9957   }
9958 
9959   bool getAssumedSimplifiedValues(Attributor &A,
9960                                   SmallVectorImpl<AA::ValueAndContext> &Values,
9961                                   AA::ValueScope S) const override {
9962     if (!isValidState())
9963       return false;
9964     for (auto &It : getAssumedSet())
9965       if (It.second & S)
9966         Values.push_back(It.first);
9967     assert(!undefIsContained() && "Undef should be an explicit value!");
9968     return true;
9969   }
9970 };
9971 
9972 struct AAPotentialValuesFloating : AAPotentialValuesImpl {
9973   AAPotentialValuesFloating(const IRPosition &IRP, Attributor &A)
9974       : AAPotentialValuesImpl(IRP, A) {}
9975 
9976   /// See AbstractAttribute::updateImpl(...).
9977   ChangeStatus updateImpl(Attributor &A) override {
9978     auto AssumedBefore = getAssumed();
9979 
9980     genericValueTraversal(A);
9981 
9982     return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
9983                                            : ChangeStatus::CHANGED;
9984   }
9985 
9986   /// Helper struct to remember which AAIsDead instances we actually used.
9987   struct LivenessInfo {
9988     const AAIsDead *LivenessAA = nullptr;
9989     bool AnyDead = false;
9990   };
9991 
9992   /// Check if \p Cmp is a comparison we can simplify.
9993   ///
9994   /// We handle multiple cases, one in which at least one operand is an
9995   /// (assumed) nullptr. If so, try to simplify it using AANonNull on the other
9996   /// operand. Return true if successful, in that case Worklist will be updated.
9997   bool handleCmp(Attributor &A, CmpInst &Cmp, ItemInfo II,
9998                  SmallVectorImpl<ItemInfo> &Worklist) {
9999     Value *LHS = Cmp.getOperand(0);
10000     Value *RHS = Cmp.getOperand(1);
10001 
10002     // Simplify the operands first.
10003     bool UsedAssumedInformation = false;
10004     const auto &SimplifiedLHS = A.getAssumedSimplified(
10005         IRPosition::value(*LHS, getCallBaseContext()), *this,
10006         UsedAssumedInformation, AA::Intraprocedural);
10007     if (!SimplifiedLHS.has_value())
10008       return true;
10009     if (!SimplifiedLHS.value())
10010       return false;
10011     LHS = *SimplifiedLHS;
10012 
10013     const auto &SimplifiedRHS = A.getAssumedSimplified(
10014         IRPosition::value(*RHS, getCallBaseContext()), *this,
10015         UsedAssumedInformation, AA::Intraprocedural);
10016     if (!SimplifiedRHS.has_value())
10017       return true;
10018     if (!SimplifiedRHS.value())
10019       return false;
10020     RHS = *SimplifiedRHS;
10021 
10022     LLVMContext &Ctx = Cmp.getContext();
10023     // Handle the trivial case first in which we don't even need to think about
10024     // null or non-null.
10025     if (LHS == RHS && (Cmp.isTrueWhenEqual() || Cmp.isFalseWhenEqual())) {
10026       Constant *NewV =
10027           ConstantInt::get(Type::getInt1Ty(Ctx), Cmp.isTrueWhenEqual());
10028       addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S,
10029                getAnchorScope());
10030       return true;
10031     }
10032 
10033     // From now on we only handle equalities (==, !=).
10034     ICmpInst *ICmp = dyn_cast<ICmpInst>(&Cmp);
10035     if (!ICmp || !ICmp->isEquality())
10036       return false;
10037 
10038     bool LHSIsNull = isa<ConstantPointerNull>(LHS);
10039     bool RHSIsNull = isa<ConstantPointerNull>(RHS);
10040     if (!LHSIsNull && !RHSIsNull)
10041       return false;
10042 
10043     // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the
10044     // non-nullptr operand and if we assume it's non-null we can conclude the
10045     // result of the comparison.
10046     assert((LHSIsNull || RHSIsNull) &&
10047            "Expected nullptr versus non-nullptr comparison at this point");
10048 
10049     // The index is the operand that we assume is not null.
10050     unsigned PtrIdx = LHSIsNull;
10051     auto &PtrNonNullAA = A.getAAFor<AANonNull>(
10052         *this, IRPosition::value(*ICmp->getOperand(PtrIdx)),
10053         DepClassTy::REQUIRED);
10054     if (!PtrNonNullAA.isAssumedNonNull())
10055       return false;
10056 
10057     // The new value depends on the predicate, true for != and false for ==.
10058     Constant *NewV = ConstantInt::get(Type::getInt1Ty(Ctx),
10059                                       ICmp->getPredicate() == CmpInst::ICMP_NE);
10060     addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S, getAnchorScope());
10061     return true;
10062   }
10063 
10064   bool handleSelectInst(Attributor &A, SelectInst &SI, ItemInfo II,
10065                         SmallVectorImpl<ItemInfo> &Worklist) {
10066     const Instruction *CtxI = II.I.getCtxI();
10067     bool UsedAssumedInformation = false;
10068 
10069     Optional<Constant *> C =
10070         A.getAssumedConstant(*SI.getCondition(), *this, UsedAssumedInformation);
10071     bool NoValueYet = !C.has_value();
10072     if (NoValueYet || isa_and_nonnull<UndefValue>(*C))
10073       return true;
10074     if (auto *CI = dyn_cast_or_null<ConstantInt>(*C)) {
10075       if (CI->isZero())
10076         Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S});
10077       else
10078         Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S});
10079     } else {
10080       // We could not simplify the condition, assume both values.
10081       Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S});
10082       Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S});
10083     }
10084     return true;
10085   }
10086 
10087   bool handleLoadInst(Attributor &A, LoadInst &LI, ItemInfo II,
10088                       SmallVectorImpl<ItemInfo> &Worklist) {
10089     SmallSetVector<Value *, 4> PotentialCopies;
10090     SmallSetVector<Instruction *, 4> PotentialValueOrigins;
10091     bool UsedAssumedInformation = false;
10092     if (!AA::getPotentiallyLoadedValues(A, LI, PotentialCopies,
10093                                         PotentialValueOrigins, *this,
10094                                         UsedAssumedInformation,
10095                                         /* OnlyExact */ true)) {
10096       LLVM_DEBUG(dbgs() << "[AAPotentialValues] Failed to get potentially "
10097                            "loaded values for load instruction "
10098                         << LI << "\n");
10099       return false;
10100     }
10101 
10102     // Do not simplify loads that are only used in llvm.assume if we cannot also
10103     // remove all stores that may feed into the load. The reason is that the
10104     // assume is probably worth something as long as the stores are around.
10105     InformationCache &InfoCache = A.getInfoCache();
10106     if (InfoCache.isOnlyUsedByAssume(LI)) {
10107       if (!llvm::all_of(PotentialValueOrigins, [&](Instruction *I) {
10108             if (!I)
10109               return true;
10110             if (auto *SI = dyn_cast<StoreInst>(I))
10111               return A.isAssumedDead(SI->getOperandUse(0), this,
10112                                      /* LivenessAA */ nullptr,
10113                                      UsedAssumedInformation,
10114                                      /* CheckBBLivenessOnly */ false);
10115             return A.isAssumedDead(*I, this, /* LivenessAA */ nullptr,
10116                                    UsedAssumedInformation,
10117                                    /* CheckBBLivenessOnly */ false);
10118           })) {
10119         LLVM_DEBUG(dbgs() << "[AAPotentialValues] Load is onl used by assumes "
10120                              "and we cannot delete all the stores: "
10121                           << LI << "\n");
10122         return false;
10123       }
10124     }
10125 
10126     // Values have to be dynamically unique or we loose the fact that a
10127     // single llvm::Value might represent two runtime values (e.g.,
10128     // stack locations in different recursive calls).
10129     const Instruction *CtxI = II.I.getCtxI();
10130     bool ScopeIsLocal = (II.S & AA::Intraprocedural);
10131     bool AllLocal = ScopeIsLocal;
10132     bool DynamicallyUnique = llvm::all_of(PotentialCopies, [&](Value *PC) {
10133       AllLocal &= AA::isValidInScope(*PC, getAnchorScope());
10134       return AA::isDynamicallyUnique(A, *this, *PC);
10135     });
10136     if (!DynamicallyUnique) {
10137       LLVM_DEBUG(dbgs() << "[AAPotentialValues] Not all potentially loaded "
10138                            "values are dynamically unique: "
10139                         << LI << "\n");
10140       return false;
10141     }
10142 
10143     for (auto *PotentialCopy : PotentialCopies) {
10144       if (AllLocal) {
10145         Worklist.push_back({{*PotentialCopy, CtxI}, II.S});
10146       } else {
10147         Worklist.push_back({{*PotentialCopy, CtxI}, AA::Interprocedural});
10148       }
10149     }
10150     if (!AllLocal && ScopeIsLocal)
10151       addValue(A, getState(), LI, CtxI, AA::Intraprocedural, getAnchorScope());
10152     return true;
10153   }
10154 
10155   bool handlePHINode(
10156       Attributor &A, PHINode &PHI, ItemInfo II,
10157       SmallVectorImpl<ItemInfo> &Worklist,
10158       SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
10159     auto GetLivenessInfo = [&](const Function &F) -> LivenessInfo & {
10160       LivenessInfo &LI = LivenessAAs[&F];
10161       if (!LI.LivenessAA)
10162         LI.LivenessAA = &A.getAAFor<AAIsDead>(*this, IRPosition::function(F),
10163                                               DepClassTy::NONE);
10164       return LI;
10165     };
10166 
10167     LivenessInfo &LI = GetLivenessInfo(*PHI.getFunction());
10168     for (unsigned u = 0, e = PHI.getNumIncomingValues(); u < e; u++) {
10169       BasicBlock *IncomingBB = PHI.getIncomingBlock(u);
10170       if (LI.LivenessAA->isEdgeDead(IncomingBB, PHI.getParent())) {
10171         LI.AnyDead = true;
10172         continue;
10173       }
10174       Worklist.push_back(
10175           {{*PHI.getIncomingValue(u), IncomingBB->getTerminator()}, II.S});
10176     }
10177     return true;
10178   }
10179 
10180   /// Use the generic, non-optimistic InstSimplfy functionality if we managed to
10181   /// simplify any operand of the instruction \p I. Return true if successful,
10182   /// in that case Worklist will be updated.
10183   bool handleGenericInst(Attributor &A, Instruction &I, ItemInfo II,
10184                          SmallVectorImpl<ItemInfo> &Worklist) {
10185     bool SomeSimplified = false;
10186     bool UsedAssumedInformation = false;
10187 
10188     SmallVector<Value *, 8> NewOps(I.getNumOperands());
10189     int Idx = 0;
10190     for (Value *Op : I.operands()) {
10191       const auto &SimplifiedOp = A.getAssumedSimplified(
10192           IRPosition::value(*Op, getCallBaseContext()), *this,
10193           UsedAssumedInformation, AA::Intraprocedural);
10194       // If we are not sure about any operand we are not sure about the entire
10195       // instruction, we'll wait.
10196       if (!SimplifiedOp.has_value())
10197         return true;
10198 
10199       if (SimplifiedOp.value())
10200         NewOps[Idx] = SimplifiedOp.value();
10201       else
10202         NewOps[Idx] = Op;
10203 
10204       SomeSimplified |= (NewOps[Idx] != Op);
10205       ++Idx;
10206     }
10207 
10208     // We won't bother with the InstSimplify interface if we didn't simplify any
10209     // operand ourselves.
10210     if (!SomeSimplified)
10211       return false;
10212 
10213     InformationCache &InfoCache = A.getInfoCache();
10214     Function *F = I.getFunction();
10215     const auto *DT =
10216         InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
10217     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
10218     auto *AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
10219     OptimizationRemarkEmitter *ORE = nullptr;
10220 
10221     const DataLayout &DL = I.getModule()->getDataLayout();
10222     SimplifyQuery Q(DL, TLI, DT, AC, &I);
10223     Value *NewV = simplifyInstructionWithOperands(&I, NewOps, Q, ORE);
10224     if (!NewV || NewV == &I)
10225       return false;
10226 
10227     LLVM_DEBUG(dbgs() << "Generic inst " << I << " assumed simplified to "
10228                       << *NewV << "\n");
10229     Worklist.push_back({{*NewV, II.I.getCtxI()}, II.S});
10230     return true;
10231   }
10232 
10233   bool simplifyInstruction(
10234       Attributor &A, Instruction &I, ItemInfo II,
10235       SmallVectorImpl<ItemInfo> &Worklist,
10236       SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
10237     if (auto *CI = dyn_cast<CmpInst>(&I))
10238       if (handleCmp(A, *CI, II, Worklist))
10239         return true;
10240 
10241     switch (I.getOpcode()) {
10242     case Instruction::Select:
10243       return handleSelectInst(A, cast<SelectInst>(I), II, Worklist);
10244     case Instruction::PHI:
10245       return handlePHINode(A, cast<PHINode>(I), II, Worklist, LivenessAAs);
10246     case Instruction::Load:
10247       return handleLoadInst(A, cast<LoadInst>(I), II, Worklist);
10248     default:
10249       return handleGenericInst(A, I, II, Worklist);
10250     };
10251     return false;
10252   }
10253 
10254   void genericValueTraversal(Attributor &A) {
10255     SmallMapVector<const Function *, LivenessInfo, 4> LivenessAAs;
10256 
10257     Value *InitialV = &getAssociatedValue();
10258     SmallSet<AA::ValueAndContext, 16> Visited;
10259     SmallVector<ItemInfo, 16> Worklist;
10260     Worklist.push_back({{*InitialV, getCtxI()}, AA::AnyScope});
10261 
10262     int Iteration = 0;
10263     do {
10264       ItemInfo II = Worklist.pop_back_val();
10265       Value *V = II.I.getValue();
10266       assert(V);
10267       const Instruction *CtxI = II.I.getCtxI();
10268       AA::ValueScope S = II.S;
10269 
10270       // Check if we should process the current value. To prevent endless
10271       // recursion keep a record of the values we followed!
10272       if (!Visited.insert(II.I).second)
10273         continue;
10274 
10275       // Make sure we limit the compile time for complex expressions.
10276       if (Iteration++ >= MaxPotentialValuesIterations) {
10277         LLVM_DEBUG(dbgs() << "Generic value traversal reached iteration limit: "
10278                           << Iteration << "!\n");
10279         addValue(A, getState(), *V, CtxI, S, getAnchorScope());
10280         continue;
10281       }
10282 
10283       // Explicitly look through calls with a "returned" attribute if we do
10284       // not have a pointer as stripPointerCasts only works on them.
10285       Value *NewV = nullptr;
10286       if (V->getType()->isPointerTy()) {
10287         NewV = AA::getWithType(*V->stripPointerCasts(), *V->getType());
10288       } else {
10289         auto *CB = dyn_cast<CallBase>(V);
10290         if (CB && CB->getCalledFunction()) {
10291           for (Argument &Arg : CB->getCalledFunction()->args())
10292             if (Arg.hasReturnedAttr()) {
10293               NewV = CB->getArgOperand(Arg.getArgNo());
10294               break;
10295             }
10296         }
10297       }
10298       if (NewV && NewV != V) {
10299         Worklist.push_back({{*NewV, CtxI}, S});
10300         continue;
10301       }
10302 
10303       if (auto *I = dyn_cast<Instruction>(V)) {
10304         if (simplifyInstruction(A, *I, II, Worklist, LivenessAAs))
10305           continue;
10306       }
10307 
10308       if (V != InitialV || isa<Argument>(V))
10309         if (recurseForValue(A, IRPosition::value(*V), II.S))
10310           continue;
10311 
10312       // If we haven't stripped anything we give up.
10313       if (V == InitialV && CtxI == getCtxI()) {
10314         indicatePessimisticFixpoint();
10315         return;
10316       }
10317 
10318       addValue(A, getState(), *V, CtxI, S, getAnchorScope());
10319     } while (!Worklist.empty());
10320 
10321     // If we actually used liveness information so we have to record a
10322     // dependence.
10323     for (auto &It : LivenessAAs)
10324       if (It.second.AnyDead)
10325         A.recordDependence(*It.second.LivenessAA, *this, DepClassTy::OPTIONAL);
10326   }
10327 
10328   /// See AbstractAttribute::trackStatistics()
10329   void trackStatistics() const override {
10330     STATS_DECLTRACK_FLOATING_ATTR(potential_values)
10331   }
10332 };
10333 
10334 struct AAPotentialValuesArgument final : AAPotentialValuesImpl {
10335   using Base = AAPotentialValuesImpl;
10336   AAPotentialValuesArgument(const IRPosition &IRP, Attributor &A)
10337       : Base(IRP, A) {}
10338 
10339   /// See AbstractAttribute::initialize(..).
10340   void initialize(Attributor &A) override {
10341     auto &Arg = cast<Argument>(getAssociatedValue());
10342     if (Arg.hasPointeeInMemoryValueAttr())
10343       indicatePessimisticFixpoint();
10344   }
10345 
10346   /// See AbstractAttribute::updateImpl(...).
10347   ChangeStatus updateImpl(Attributor &A) override {
10348     auto AssumedBefore = getAssumed();
10349 
10350     unsigned CSArgNo = getCallSiteArgNo();
10351 
10352     bool UsedAssumedInformation = false;
10353     SmallVector<AA::ValueAndContext> Values;
10354     auto CallSitePred = [&](AbstractCallSite ACS) {
10355       const auto CSArgIRP = IRPosition::callsite_argument(ACS, CSArgNo);
10356       if (CSArgIRP.getPositionKind() == IRP_INVALID)
10357         return false;
10358 
10359       if (!A.getAssumedSimplifiedValues(CSArgIRP, this, Values,
10360                                         AA::Interprocedural,
10361                                         UsedAssumedInformation))
10362         return false;
10363 
10364       return isValidState();
10365     };
10366 
10367     if (!A.checkForAllCallSites(CallSitePred, *this,
10368                                 /* RequireAllCallSites */ true,
10369                                 UsedAssumedInformation))
10370       return indicatePessimisticFixpoint();
10371 
10372     Function *Fn = getAssociatedFunction();
10373     bool AnyNonLocal = false;
10374     for (auto &It : Values) {
10375       if (isa<Constant>(It.getValue())) {
10376         addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope,
10377                  getAnchorScope());
10378         continue;
10379       }
10380       if (!AA::isDynamicallyUnique(A, *this, *It.getValue()))
10381         return indicatePessimisticFixpoint();
10382 
10383       if (auto *Arg = dyn_cast<Argument>(It.getValue()))
10384         if (Arg->getParent() == Fn) {
10385           addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope,
10386                    getAnchorScope());
10387           continue;
10388         }
10389       addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::Interprocedural,
10390                getAnchorScope());
10391       AnyNonLocal = true;
10392     }
10393     if (undefIsContained())
10394       unionAssumedWithUndef();
10395     if (AnyNonLocal)
10396       giveUpOnIntraprocedural(A);
10397 
10398     return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
10399                                            : ChangeStatus::CHANGED;
10400   }
10401 
10402   /// See AbstractAttribute::trackStatistics()
10403   void trackStatistics() const override {
10404     STATS_DECLTRACK_ARG_ATTR(potential_values)
10405   }
10406 };
10407 
10408 struct AAPotentialValuesReturned
10409     : AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl> {
10410   using Base =
10411       AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl>;
10412   AAPotentialValuesReturned(const IRPosition &IRP, Attributor &A)
10413       : Base(IRP, A) {}
10414 
10415   /// See AbstractAttribute::initialize(..).
10416   void initialize(Attributor &A) override {
10417     if (A.hasSimplificationCallback(getIRPosition()))
10418       indicatePessimisticFixpoint();
10419     else
10420       AAPotentialValues::initialize(A);
10421   }
10422 
10423   ChangeStatus manifest(Attributor &A) override {
10424     // We queried AAValueSimplify for the returned values so they will be
10425     // replaced if a simplified form was found. Nothing to do here.
10426     return ChangeStatus::UNCHANGED;
10427   }
10428 
10429   ChangeStatus indicatePessimisticFixpoint() override {
10430     return AAPotentialValues::indicatePessimisticFixpoint();
10431   }
10432 
10433   /// See AbstractAttribute::trackStatistics()
10434   void trackStatistics() const override {
10435     STATS_DECLTRACK_FNRET_ATTR(potential_values)
10436   }
10437 };
10438 
10439 struct AAPotentialValuesFunction : AAPotentialValuesImpl {
10440   AAPotentialValuesFunction(const IRPosition &IRP, Attributor &A)
10441       : AAPotentialValuesImpl(IRP, A) {}
10442 
10443   /// See AbstractAttribute::updateImpl(...).
10444   ChangeStatus updateImpl(Attributor &A) override {
10445     llvm_unreachable("AAPotentialValues(Function|CallSite)::updateImpl will "
10446                      "not be called");
10447   }
10448 
10449   /// See AbstractAttribute::trackStatistics()
10450   void trackStatistics() const override {
10451     STATS_DECLTRACK_FN_ATTR(potential_values)
10452   }
10453 };
10454 
10455 struct AAPotentialValuesCallSite : AAPotentialValuesFunction {
10456   AAPotentialValuesCallSite(const IRPosition &IRP, Attributor &A)
10457       : AAPotentialValuesFunction(IRP, A) {}
10458 
10459   /// See AbstractAttribute::trackStatistics()
10460   void trackStatistics() const override {
10461     STATS_DECLTRACK_CS_ATTR(potential_values)
10462   }
10463 };
10464 
10465 struct AAPotentialValuesCallSiteReturned : AAPotentialValuesImpl {
10466   AAPotentialValuesCallSiteReturned(const IRPosition &IRP, Attributor &A)
10467       : AAPotentialValuesImpl(IRP, A) {}
10468 
10469   /// See AbstractAttribute::updateImpl(...).
10470   ChangeStatus updateImpl(Attributor &A) override {
10471     auto AssumedBefore = getAssumed();
10472 
10473     Function *Callee = getAssociatedFunction();
10474     if (!Callee)
10475       return indicatePessimisticFixpoint();
10476 
10477     bool UsedAssumedInformation = false;
10478     auto *CB = cast<CallBase>(getCtxI());
10479     if (CB->isMustTailCall() &&
10480         !A.isAssumedDead(IRPosition::inst(*CB), this, nullptr,
10481                          UsedAssumedInformation))
10482       return indicatePessimisticFixpoint();
10483 
10484     SmallVector<AA::ValueAndContext> Values;
10485     if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this,
10486                                       Values, AA::Intraprocedural,
10487                                       UsedAssumedInformation))
10488       return indicatePessimisticFixpoint();
10489 
10490     Function *Caller = CB->getCaller();
10491 
10492     bool AnyNonLocal = false;
10493     for (auto &It : Values) {
10494       Value *V = It.getValue();
10495       Optional<Value *> CallerV = A.translateArgumentToCallSiteContent(
10496           V, *CB, *this, UsedAssumedInformation);
10497       if (!CallerV.has_value()) {
10498         // Nothing to do as long as no value was determined.
10499         continue;
10500       }
10501       V = CallerV.value() ? CallerV.value() : V;
10502       if (AA::isDynamicallyUnique(A, *this, *V) &&
10503           AA::isValidInScope(*V, Caller)) {
10504         if (CallerV.value()) {
10505           SmallVector<AA::ValueAndContext> ArgValues;
10506           IRPosition IRP = IRPosition::value(*V);
10507           if (auto *Arg = dyn_cast<Argument>(V))
10508             if (Arg->getParent() == CB->getCalledFunction())
10509               IRP = IRPosition::callsite_argument(*CB, Arg->getArgNo());
10510           if (recurseForValue(A, IRP, AA::AnyScope))
10511             continue;
10512         }
10513         addValue(A, getState(), *V, CB, AA::AnyScope, getAnchorScope());
10514       } else {
10515         AnyNonLocal = true;
10516         break;
10517       }
10518     }
10519     if (AnyNonLocal) {
10520       Values.clear();
10521       if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this,
10522                                         Values, AA::Interprocedural,
10523                                         UsedAssumedInformation))
10524         return indicatePessimisticFixpoint();
10525       AnyNonLocal = false;
10526       getState() = PotentialLLVMValuesState::getBestState();
10527       for (auto &It : Values) {
10528         Value *V = It.getValue();
10529         if (!AA::isDynamicallyUnique(A, *this, *V))
10530           return indicatePessimisticFixpoint();
10531         if (AA::isValidInScope(*V, Caller)) {
10532           addValue(A, getState(), *V, CB, AA::AnyScope, getAnchorScope());
10533         } else {
10534           AnyNonLocal = true;
10535           addValue(A, getState(), *V, CB, AA::Interprocedural,
10536                    getAnchorScope());
10537         }
10538       }
10539       if (AnyNonLocal)
10540         giveUpOnIntraprocedural(A);
10541     }
10542     return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
10543                                            : ChangeStatus::CHANGED;
10544   }
10545 
10546   ChangeStatus indicatePessimisticFixpoint() override {
10547     return AAPotentialValues::indicatePessimisticFixpoint();
10548   }
10549 
10550   /// See AbstractAttribute::trackStatistics()
10551   void trackStatistics() const override {
10552     STATS_DECLTRACK_CSRET_ATTR(potential_values)
10553   }
10554 };
10555 
10556 struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating {
10557   AAPotentialValuesCallSiteArgument(const IRPosition &IRP, Attributor &A)
10558       : AAPotentialValuesFloating(IRP, A) {}
10559 
10560   /// See AbstractAttribute::trackStatistics()
10561   void trackStatistics() const override {
10562     STATS_DECLTRACK_CSARG_ATTR(potential_values)
10563   }
10564 };
10565 } // namespace
10566 
10567 /// ---------------------- Assumption Propagation ------------------------------
10568 namespace {
10569 struct AAAssumptionInfoImpl : public AAAssumptionInfo {
10570   AAAssumptionInfoImpl(const IRPosition &IRP, Attributor &A,
10571                        const DenseSet<StringRef> &Known)
10572       : AAAssumptionInfo(IRP, A, Known) {}
10573 
10574   bool hasAssumption(const StringRef Assumption) const override {
10575     return isValidState() && setContains(Assumption);
10576   }
10577 
10578   /// See AbstractAttribute::getAsStr()
10579   const std::string getAsStr() const override {
10580     const SetContents &Known = getKnown();
10581     const SetContents &Assumed = getAssumed();
10582 
10583     const std::string KnownStr =
10584         llvm::join(Known.getSet().begin(), Known.getSet().end(), ",");
10585     const std::string AssumedStr =
10586         (Assumed.isUniversal())
10587             ? "Universal"
10588             : llvm::join(Assumed.getSet().begin(), Assumed.getSet().end(), ",");
10589 
10590     return "Known [" + KnownStr + "]," + " Assumed [" + AssumedStr + "]";
10591   }
10592 };
10593 
10594 /// Propagates assumption information from parent functions to all of their
10595 /// successors. An assumption can be propagated if the containing function
10596 /// dominates the called function.
10597 ///
10598 /// We start with a "known" set of assumptions already valid for the associated
10599 /// function and an "assumed" set that initially contains all possible
10600 /// assumptions. The assumed set is inter-procedurally updated by narrowing its
10601 /// contents as concrete values are known. The concrete values are seeded by the
10602 /// first nodes that are either entries into the call graph, or contains no
10603 /// assumptions. Each node is updated as the intersection of the assumed state
10604 /// with all of its predecessors.
10605 struct AAAssumptionInfoFunction final : AAAssumptionInfoImpl {
10606   AAAssumptionInfoFunction(const IRPosition &IRP, Attributor &A)
10607       : AAAssumptionInfoImpl(IRP, A,
10608                              getAssumptions(*IRP.getAssociatedFunction())) {}
10609 
10610   /// See AbstractAttribute::manifest(...).
10611   ChangeStatus manifest(Attributor &A) override {
10612     const auto &Assumptions = getKnown();
10613 
10614     // Don't manifest a universal set if it somehow made it here.
10615     if (Assumptions.isUniversal())
10616       return ChangeStatus::UNCHANGED;
10617 
10618     Function *AssociatedFunction = getAssociatedFunction();
10619 
10620     bool Changed = addAssumptions(*AssociatedFunction, Assumptions.getSet());
10621 
10622     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
10623   }
10624 
10625   /// See AbstractAttribute::updateImpl(...).
10626   ChangeStatus updateImpl(Attributor &A) override {
10627     bool Changed = false;
10628 
10629     auto CallSitePred = [&](AbstractCallSite ACS) {
10630       const auto &AssumptionAA = A.getAAFor<AAAssumptionInfo>(
10631           *this, IRPosition::callsite_function(*ACS.getInstruction()),
10632           DepClassTy::REQUIRED);
10633       // Get the set of assumptions shared by all of this function's callers.
10634       Changed |= getIntersection(AssumptionAA.getAssumed());
10635       return !getAssumed().empty() || !getKnown().empty();
10636     };
10637 
10638     bool UsedAssumedInformation = false;
10639     // Get the intersection of all assumptions held by this node's predecessors.
10640     // If we don't know all the call sites then this is either an entry into the
10641     // call graph or an empty node. This node is known to only contain its own
10642     // assumptions and can be propagated to its successors.
10643     if (!A.checkForAllCallSites(CallSitePred, *this, true,
10644                                 UsedAssumedInformation))
10645       return indicatePessimisticFixpoint();
10646 
10647     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
10648   }
10649 
10650   void trackStatistics() const override {}
10651 };
10652 
10653 /// Assumption Info defined for call sites.
10654 struct AAAssumptionInfoCallSite final : AAAssumptionInfoImpl {
10655 
10656   AAAssumptionInfoCallSite(const IRPosition &IRP, Attributor &A)
10657       : AAAssumptionInfoImpl(IRP, A, getInitialAssumptions(IRP)) {}
10658 
10659   /// See AbstractAttribute::initialize(...).
10660   void initialize(Attributor &A) override {
10661     const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
10662     A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED);
10663   }
10664 
10665   /// See AbstractAttribute::manifest(...).
10666   ChangeStatus manifest(Attributor &A) override {
10667     // Don't manifest a universal set if it somehow made it here.
10668     if (getKnown().isUniversal())
10669       return ChangeStatus::UNCHANGED;
10670 
10671     CallBase &AssociatedCall = cast<CallBase>(getAssociatedValue());
10672     bool Changed = addAssumptions(AssociatedCall, getAssumed().getSet());
10673 
10674     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
10675   }
10676 
10677   /// See AbstractAttribute::updateImpl(...).
10678   ChangeStatus updateImpl(Attributor &A) override {
10679     const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
10680     auto &AssumptionAA =
10681         A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED);
10682     bool Changed = getIntersection(AssumptionAA.getAssumed());
10683     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
10684   }
10685 
10686   /// See AbstractAttribute::trackStatistics()
10687   void trackStatistics() const override {}
10688 
10689 private:
10690   /// Helper to initialized the known set as all the assumptions this call and
10691   /// the callee contain.
10692   DenseSet<StringRef> getInitialAssumptions(const IRPosition &IRP) {
10693     const CallBase &CB = cast<CallBase>(IRP.getAssociatedValue());
10694     auto Assumptions = getAssumptions(CB);
10695     if (Function *F = IRP.getAssociatedFunction())
10696       set_union(Assumptions, getAssumptions(*F));
10697     if (Function *F = IRP.getAssociatedFunction())
10698       set_union(Assumptions, getAssumptions(*F));
10699     return Assumptions;
10700   }
10701 };
10702 } // namespace
10703 
10704 AACallGraphNode *AACallEdgeIterator::operator*() const {
10705   return static_cast<AACallGraphNode *>(const_cast<AACallEdges *>(
10706       &A.getOrCreateAAFor<AACallEdges>(IRPosition::function(**I))));
10707 }
10708 
10709 void AttributorCallGraph::print() { llvm::WriteGraph(outs(), this); }
10710 
10711 const char AAReturnedValues::ID = 0;
10712 const char AANoUnwind::ID = 0;
10713 const char AANoSync::ID = 0;
10714 const char AANoFree::ID = 0;
10715 const char AANonNull::ID = 0;
10716 const char AANoRecurse::ID = 0;
10717 const char AAWillReturn::ID = 0;
10718 const char AAUndefinedBehavior::ID = 0;
10719 const char AANoAlias::ID = 0;
10720 const char AAReachability::ID = 0;
10721 const char AANoReturn::ID = 0;
10722 const char AAIsDead::ID = 0;
10723 const char AADereferenceable::ID = 0;
10724 const char AAAlign::ID = 0;
10725 const char AAInstanceInfo::ID = 0;
10726 const char AANoCapture::ID = 0;
10727 const char AAValueSimplify::ID = 0;
10728 const char AAHeapToStack::ID = 0;
10729 const char AAPrivatizablePtr::ID = 0;
10730 const char AAMemoryBehavior::ID = 0;
10731 const char AAMemoryLocation::ID = 0;
10732 const char AAValueConstantRange::ID = 0;
10733 const char AAPotentialConstantValues::ID = 0;
10734 const char AAPotentialValues::ID = 0;
10735 const char AANoUndef::ID = 0;
10736 const char AACallEdges::ID = 0;
10737 const char AAFunctionReachability::ID = 0;
10738 const char AAPointerInfo::ID = 0;
10739 const char AAAssumptionInfo::ID = 0;
10740 
10741 // Macro magic to create the static generator function for attributes that
10742 // follow the naming scheme.
10743 
10744 #define SWITCH_PK_INV(CLASS, PK, POS_NAME)                                     \
10745   case IRPosition::PK:                                                         \
10746     llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
10747 
10748 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX)                               \
10749   case IRPosition::PK:                                                         \
10750     AA = new (A.Allocator) CLASS##SUFFIX(IRP, A);                              \
10751     ++NumAAs;                                                                  \
10752     break;
10753 
10754 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                 \
10755   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10756     CLASS *AA = nullptr;                                                       \
10757     switch (IRP.getPositionKind()) {                                           \
10758       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10759       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
10760       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
10761       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
10762       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
10763       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
10764       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
10765       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
10766     }                                                                          \
10767     return *AA;                                                                \
10768   }
10769 
10770 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                    \
10771   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10772     CLASS *AA = nullptr;                                                       \
10773     switch (IRP.getPositionKind()) {                                           \
10774       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10775       SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function")                           \
10776       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
10777       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
10778       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
10779       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
10780       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
10781       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
10782     }                                                                          \
10783     return *AA;                                                                \
10784   }
10785 
10786 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                      \
10787   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10788     CLASS *AA = nullptr;                                                       \
10789     switch (IRP.getPositionKind()) {                                           \
10790       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10791       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
10792       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
10793       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
10794       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
10795       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
10796       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
10797       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
10798     }                                                                          \
10799     return *AA;                                                                \
10800   }
10801 
10802 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)            \
10803   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10804     CLASS *AA = nullptr;                                                       \
10805     switch (IRP.getPositionKind()) {                                           \
10806       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10807       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
10808       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
10809       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
10810       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
10811       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
10812       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
10813       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
10814     }                                                                          \
10815     return *AA;                                                                \
10816   }
10817 
10818 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                  \
10819   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10820     CLASS *AA = nullptr;                                                       \
10821     switch (IRP.getPositionKind()) {                                           \
10822       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10823       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
10824       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
10825       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
10826       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
10827       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
10828       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
10829       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
10830     }                                                                          \
10831     return *AA;                                                                \
10832   }
10833 
10834 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind)
10835 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync)
10836 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse)
10837 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn)
10838 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn)
10839 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues)
10840 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation)
10841 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AACallEdges)
10842 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAssumptionInfo)
10843 
10844 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull)
10845 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias)
10846 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr)
10847 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable)
10848 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign)
10849 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAInstanceInfo)
10850 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture)
10851 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange)
10852 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialConstantValues)
10853 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialValues)
10854 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUndef)
10855 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPointerInfo)
10856 
10857 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify)
10858 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead)
10859 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree)
10860 
10861 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack)
10862 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability)
10863 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior)
10864 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAFunctionReachability)
10865 
10866 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior)
10867 
10868 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
10869 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
10870 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
10871 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
10872 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
10873 #undef SWITCH_PK_CREATE
10874 #undef SWITCH_PK_INV
10875