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