1 //===- Attributor.cpp - Module-wide attribute 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 // This file implements an inter procedural pass that deduces and/or propagating
10 // attributes. This is done in an abstract interpretation style fixpoint
11 // iteration. See the Attributor.h file comment and the class descriptions in
12 // that file for more information.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/IPO/Attributor.h"
17 
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/EHPersonalities.h"
26 #include "llvm/Analysis/GlobalsModRef.h"
27 #include "llvm/Analysis/Loads.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/Argument.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/InstIterator.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 
40 #include <cassert>
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "attributor"
45 
46 STATISTIC(NumFnWithExactDefinition,
47           "Number of function with exact definitions");
48 STATISTIC(NumFnWithoutExactDefinition,
49           "Number of function without exact definitions");
50 STATISTIC(NumAttributesTimedOut,
51           "Number of abstract attributes timed out before fixpoint");
52 STATISTIC(NumAttributesValidFixpoint,
53           "Number of abstract attributes in a valid fixpoint state");
54 STATISTIC(NumAttributesManifested,
55           "Number of abstract attributes manifested in IR");
56 
57 // Some helper macros to deal with statistics tracking.
58 //
59 // Usage:
60 // For simple IR attribute tracking overload trackStatistics in the abstract
61 // attribute and choose the right STATS_DECLTRACK_********* macro,
62 // e.g.,:
63 //  void trackStatistics() const override {
64 //    STATS_DECLTRACK_ARG_ATTR(returned)
65 //  }
66 // If there is a single "increment" side one can use the macro
67 // STATS_DECLTRACK with a custom message. If there are multiple increment
68 // sides, STATS_DECL and STATS_TRACK can also be used separatly.
69 //
70 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME)                                     \
71   ("Number of " #TYPE " marked '" #NAME "'")
72 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
73 #define STATS_DECL(NAME, TYPE, MSG) STATISTIC(BUILD_STAT_NAME(NAME, TYPE), MSG);
74 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
75 #define STATS_DECLTRACK(NAME, TYPE, MSG)                                       \
76   {                                                                            \
77     STATS_DECL(NAME, TYPE, MSG)                                                \
78     STATS_TRACK(NAME, TYPE)                                                    \
79   }
80 #define STATS_DECLTRACK_ARG_ATTR(NAME)                                         \
81   STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
82 #define STATS_DECLTRACK_CSARG_ATTR(NAME)                                       \
83   STATS_DECLTRACK(NAME, CSArguments,                                           \
84                   BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
85 #define STATS_DECLTRACK_FN_ATTR(NAME)                                          \
86   STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
87 #define STATS_DECLTRACK_CS_ATTR(NAME)                                          \
88   STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
89 #define STATS_DECLTRACK_FNRET_ATTR(NAME)                                       \
90   STATS_DECLTRACK(NAME, FunctionReturn,                                        \
91                   BUILD_STAT_MSG_IR_ATTR(function returns, NAME));
92 #define STATS_DECLTRACK_CSRET_ATTR(NAME)                                       \
93   STATS_DECLTRACK(NAME, CSReturn,                                              \
94                   BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
95 #define STATS_DECLTRACK_FLOATING_ATTR(NAME)                                    \
96   STATS_DECLTRACK(NAME, Floating,                                              \
97                   ("Number of floating values known to be '" #NAME "'"))
98 
99 // TODO: Determine a good default value.
100 //
101 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
102 // (when run with the first 5 abstract attributes). The results also indicate
103 // that we never reach 32 iterations but always find a fixpoint sooner.
104 //
105 // This will become more evolved once we perform two interleaved fixpoint
106 // iterations: bottom-up and top-down.
107 static cl::opt<unsigned>
108     MaxFixpointIterations("attributor-max-iterations", cl::Hidden,
109                           cl::desc("Maximal number of fixpoint iterations."),
110                           cl::init(32));
111 
112 static cl::opt<bool> DisableAttributor(
113     "attributor-disable", cl::Hidden,
114     cl::desc("Disable the attributor inter-procedural deduction pass."),
115     cl::init(true));
116 
117 static cl::opt<bool> VerifyAttributor(
118     "attributor-verify", cl::Hidden,
119     cl::desc("Verify the Attributor deduction and "
120              "manifestation of attributes -- may issue false-positive errors"),
121     cl::init(false));
122 
123 /// Logic operators for the change status enum class.
124 ///
125 ///{
126 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) {
127   return l == ChangeStatus::CHANGED ? l : r;
128 }
129 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) {
130   return l == ChangeStatus::UNCHANGED ? l : r;
131 }
132 ///}
133 
134 /// Recursively visit all values that might become \p IRP at some point. This
135 /// will be done by looking through cast instructions, selects, phis, and calls
136 /// with the "returned" attribute. Once we cannot look through the value any
137 /// further, the callback \p VisitValueCB is invoked and passed the current
138 /// value, the \p State, and a flag to indicate if we stripped anything. To
139 /// limit how much effort is invested, we will never visit more values than
140 /// specified by \p MaxValues.
141 template <typename AAType, typename StateTy>
142 bool genericValueTraversal(
143     Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State,
144     const function_ref<bool(Value &, StateTy &, bool)> &VisitValueCB,
145     int MaxValues = 8) {
146 
147   const AAIsDead *LivenessAA = nullptr;
148   if (IRP.getAnchorScope())
149     LivenessAA = &A.getAAFor<AAIsDead>(
150         QueryingAA, IRPosition::function(*IRP.getAnchorScope()));
151 
152   // TODO: Use Positions here to allow context sensitivity in VisitValueCB
153   SmallPtrSet<Value *, 16> Visited;
154   SmallVector<Value *, 16> Worklist;
155   Worklist.push_back(&IRP.getAssociatedValue());
156 
157   int Iteration = 0;
158   do {
159     Value *V = Worklist.pop_back_val();
160 
161     // Check if we should process the current value. To prevent endless
162     // recursion keep a record of the values we followed!
163     if (!Visited.insert(V).second)
164       continue;
165 
166     // Make sure we limit the compile time for complex expressions.
167     if (Iteration++ >= MaxValues)
168       return false;
169 
170     // Explicitly look through calls with a "returned" attribute if we do
171     // not have a pointer as stripPointerCasts only works on them.
172     Value *NewV = nullptr;
173     if (V->getType()->isPointerTy()) {
174       NewV = V->stripPointerCasts();
175     } else {
176       CallSite CS(V);
177       if (CS && CS.getCalledFunction()) {
178         for (Argument &Arg : CS.getCalledFunction()->args())
179           if (Arg.hasReturnedAttr()) {
180             NewV = CS.getArgOperand(Arg.getArgNo());
181             break;
182           }
183       }
184     }
185     if (NewV && NewV != V) {
186       Worklist.push_back(NewV);
187       continue;
188     }
189 
190     // Look through select instructions, visit both potential values.
191     if (auto *SI = dyn_cast<SelectInst>(V)) {
192       Worklist.push_back(SI->getTrueValue());
193       Worklist.push_back(SI->getFalseValue());
194       continue;
195     }
196 
197     // Look through phi nodes, visit all live operands.
198     if (auto *PHI = dyn_cast<PHINode>(V)) {
199       assert(LivenessAA &&
200              "Expected liveness in the presence of instructions!");
201       for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
202         const BasicBlock *IncomingBB = PHI->getIncomingBlock(u);
203         if (!LivenessAA->isAssumedDead(IncomingBB->getTerminator()))
204           Worklist.push_back(PHI->getIncomingValue(u));
205       }
206       continue;
207     }
208 
209     // Once a leaf is reached we inform the user through the callback.
210     if (!VisitValueCB(*V, State, Iteration > 1))
211       return false;
212   } while (!Worklist.empty());
213 
214   // All values have been visited.
215   return true;
216 }
217 
218 /// Return true if \p New is equal or worse than \p Old.
219 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
220   if (!Old.isIntAttribute())
221     return true;
222 
223   return Old.getValueAsInt() >= New.getValueAsInt();
224 }
225 
226 /// Return true if the information provided by \p Attr was added to the
227 /// attribute list \p Attrs. This is only the case if it was not already present
228 /// in \p Attrs at the position describe by \p PK and \p AttrIdx.
229 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
230                              AttributeList &Attrs, int AttrIdx) {
231 
232   if (Attr.isEnumAttribute()) {
233     Attribute::AttrKind Kind = Attr.getKindAsEnum();
234     if (Attrs.hasAttribute(AttrIdx, Kind))
235       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
236         return false;
237     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
238     return true;
239   }
240   if (Attr.isStringAttribute()) {
241     StringRef Kind = Attr.getKindAsString();
242     if (Attrs.hasAttribute(AttrIdx, Kind))
243       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
244         return false;
245     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
246     return true;
247   }
248   if (Attr.isIntAttribute()) {
249     Attribute::AttrKind Kind = Attr.getKindAsEnum();
250     if (Attrs.hasAttribute(AttrIdx, Kind))
251       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
252         return false;
253     Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind);
254     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
255     return true;
256   }
257 
258   llvm_unreachable("Expected enum or string attribute!");
259 }
260 
261 ChangeStatus AbstractAttribute::update(Attributor &A) {
262   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
263   if (getState().isAtFixpoint())
264     return HasChanged;
265 
266   LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
267 
268   HasChanged = updateImpl(A);
269 
270   LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
271                     << "\n");
272 
273   return HasChanged;
274 }
275 
276 ChangeStatus
277 IRAttributeManifest::manifestAttrs(Attributor &A, IRPosition &IRP,
278                                    const ArrayRef<Attribute> &DeducedAttrs) {
279   Function *ScopeFn = IRP.getAssociatedFunction();
280   IRPosition::Kind PK = IRP.getPositionKind();
281 
282   // In the following some generic code that will manifest attributes in
283   // DeducedAttrs if they improve the current IR. Due to the different
284   // annotation positions we use the underlying AttributeList interface.
285 
286   AttributeList Attrs;
287   switch (PK) {
288   case IRPosition::IRP_INVALID:
289   case IRPosition::IRP_FLOAT:
290     return ChangeStatus::UNCHANGED;
291   case IRPosition::IRP_ARGUMENT:
292   case IRPosition::IRP_FUNCTION:
293   case IRPosition::IRP_RETURNED:
294     Attrs = ScopeFn->getAttributes();
295     break;
296   case IRPosition::IRP_CALL_SITE:
297   case IRPosition::IRP_CALL_SITE_RETURNED:
298   case IRPosition::IRP_CALL_SITE_ARGUMENT:
299     Attrs = ImmutableCallSite(&IRP.getAnchorValue()).getAttributes();
300     break;
301   }
302 
303   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
304   LLVMContext &Ctx = IRP.getAnchorValue().getContext();
305   for (const Attribute &Attr : DeducedAttrs) {
306     if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx()))
307       continue;
308 
309     HasChanged = ChangeStatus::CHANGED;
310   }
311 
312   if (HasChanged == ChangeStatus::UNCHANGED)
313     return HasChanged;
314 
315   switch (PK) {
316   case IRPosition::IRP_ARGUMENT:
317   case IRPosition::IRP_FUNCTION:
318   case IRPosition::IRP_RETURNED:
319     ScopeFn->setAttributes(Attrs);
320     break;
321   case IRPosition::IRP_CALL_SITE:
322   case IRPosition::IRP_CALL_SITE_RETURNED:
323   case IRPosition::IRP_CALL_SITE_ARGUMENT:
324     CallSite(&IRP.getAnchorValue()).setAttributes(Attrs);
325     break;
326   case IRPosition::IRP_INVALID:
327   case IRPosition::IRP_FLOAT:
328     break;
329   }
330 
331   return HasChanged;
332 }
333 
334 const IRPosition IRPosition::EmptyKey(255);
335 const IRPosition IRPosition::TombstoneKey(256);
336 
337 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
338   IRPositions.emplace_back(IRP);
339 
340   ImmutableCallSite ICS(&IRP.getAnchorValue());
341   switch (IRP.getPositionKind()) {
342   case IRPosition::IRP_INVALID:
343   case IRPosition::IRP_FLOAT:
344   case IRPosition::IRP_FUNCTION:
345     return;
346   case IRPosition::IRP_ARGUMENT:
347   case IRPosition::IRP_RETURNED:
348     IRPositions.emplace_back(
349         IRPosition::function(*IRP.getAssociatedFunction()));
350     return;
351   case IRPosition::IRP_CALL_SITE:
352     assert(ICS && "Expected call site!");
353     // TODO: We need to look at the operand bundles similar to the redirection
354     //       in CallBase.
355     if (!ICS.hasOperandBundles())
356       if (const Function *Callee = ICS.getCalledFunction())
357         IRPositions.emplace_back(IRPosition::function(*Callee));
358     return;
359   case IRPosition::IRP_CALL_SITE_RETURNED:
360     assert(ICS && "Expected call site!");
361     // TODO: We need to look at the operand bundles similar to the redirection
362     //       in CallBase.
363     if (!ICS.hasOperandBundles()) {
364       if (const Function *Callee = ICS.getCalledFunction()) {
365         IRPositions.emplace_back(IRPosition::returned(*Callee));
366         IRPositions.emplace_back(IRPosition::function(*Callee));
367       }
368     }
369     IRPositions.emplace_back(
370         IRPosition::callsite_function(cast<CallBase>(*ICS.getInstruction())));
371     return;
372   case IRPosition::IRP_CALL_SITE_ARGUMENT: {
373     int ArgNo = IRP.getArgNo();
374     assert(ICS && ArgNo >= 0 && "Expected call site!");
375     // TODO: We need to look at the operand bundles similar to the redirection
376     //       in CallBase.
377     if (!ICS.hasOperandBundles()) {
378       const Function *Callee = ICS.getCalledFunction();
379       if (Callee && Callee->arg_size() > unsigned(ArgNo))
380         IRPositions.emplace_back(IRPosition::argument(*Callee->getArg(ArgNo)));
381       if (Callee)
382         IRPositions.emplace_back(IRPosition::function(*Callee));
383     }
384     IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue()));
385     return;
386   }
387   }
388 }
389 
390 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs) const {
391   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this))
392     for (Attribute::AttrKind AK : AKs)
393       if (EquivIRP.getAttr(AK).getKindAsEnum() == AK)
394         return true;
395   return false;
396 }
397 
398 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs,
399                           SmallVectorImpl<Attribute> &Attrs) const {
400   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this))
401     for (Attribute::AttrKind AK : AKs) {
402       const Attribute &Attr = EquivIRP.getAttr(AK);
403       if (Attr.getKindAsEnum() == AK)
404         Attrs.push_back(Attr);
405     }
406 }
407 
408 void IRPosition::verify() {
409   switch (KindOrArgNo) {
410   default:
411     assert(KindOrArgNo >= 0 && "Expected argument or call site argument!");
412     assert((isa<CallBase>(AnchorVal) || isa<Argument>(AnchorVal)) &&
413            "Expected call base or argument for positive attribute index!");
414     if (auto *Arg = dyn_cast<Argument>(AnchorVal)) {
415       assert(Arg->getArgNo() == unsigned(getArgNo()) &&
416              "Argument number mismatch!");
417       assert(Arg == &getAssociatedValue() && "Associated value mismatch!");
418     } else {
419       auto &CB = cast<CallBase>(*AnchorVal);
420       (void)CB;
421       assert(CB.arg_size() > unsigned(getArgNo()) &&
422              "Call site argument number mismatch!");
423       assert(CB.getArgOperand(getArgNo()) == &getAssociatedValue() &&
424              "Associated value mismatch!");
425     }
426     break;
427   case IRP_INVALID:
428     assert(!AnchorVal && "Expected no value for an invalid position!");
429     break;
430   case IRP_FLOAT:
431     assert((!isa<CallBase>(&getAssociatedValue()) &&
432             !isa<Argument>(&getAssociatedValue())) &&
433            "Expected specialized kind for call base and argument values!");
434     break;
435   case IRP_RETURNED:
436     assert(isa<Function>(AnchorVal) &&
437            "Expected function for a 'returned' position!");
438     assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!");
439     break;
440   case IRP_CALL_SITE_RETURNED:
441     assert((isa<CallBase>(AnchorVal)) &&
442            "Expected call base for 'call site returned' position!");
443     assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!");
444     break;
445   case IRP_CALL_SITE:
446     assert((isa<CallBase>(AnchorVal)) &&
447            "Expected call base for 'call site function' position!");
448     assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!");
449     break;
450   case IRP_FUNCTION:
451     assert(isa<Function>(AnchorVal) &&
452            "Expected function for a 'function' position!");
453     assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!");
454     break;
455   }
456 }
457 
458 /// Helper functions to clamp a state \p S of type \p StateType with the
459 /// information in \p R and indicate/return if \p S did change (as-in update is
460 /// required to be run again).
461 ///
462 ///{
463 template <typename StateType>
464 ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R);
465 
466 template <>
467 ChangeStatus clampStateAndIndicateChange<IntegerState>(IntegerState &S,
468                                                        const IntegerState &R) {
469   auto Assumed = S.getAssumed();
470   S ^= R;
471   return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
472                                    : ChangeStatus::CHANGED;
473 }
474 
475 template <>
476 ChangeStatus clampStateAndIndicateChange<BooleanState>(BooleanState &S,
477                                                        const BooleanState &R) {
478   return clampStateAndIndicateChange<IntegerState>(S, R);
479 }
480 ///}
481 
482 /// Clamp the information known for all returned values of a function
483 /// (identified by \p QueryingAA) into \p S.
484 template <typename AAType, typename StateType = typename AAType::StateType>
485 static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA,
486                                      StateType &S) {
487   LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for "
488                     << static_cast<const AbstractAttribute &>(QueryingAA)
489                     << " into " << S << "\n");
490 
491   assert((QueryingAA.getIRPosition().getPositionKind() ==
492               IRPosition::IRP_RETURNED ||
493           QueryingAA.getIRPosition().getPositionKind() ==
494               IRPosition::IRP_CALL_SITE_RETURNED) &&
495          "Can only clamp returned value states for a function returned or call "
496          "site returned position!");
497 
498   // Use an optional state as there might not be any return values and we want
499   // to join (IntegerState::operator&) the state of all there are.
500   Optional<StateType> T;
501 
502   // Callback for each possibly returned value.
503   auto CheckReturnValue = [&](Value &RV) -> bool {
504     const IRPosition &RVPos = IRPosition::value(RV);
505     const AAType &AA = A.getAAFor<AAType>(QueryingAA, RVPos);
506     LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr()
507                       << " @ " << RVPos << "\n");
508     const StateType &AAS = static_cast<const StateType &>(AA.getState());
509     if (T.hasValue())
510       *T &= AAS;
511     else
512       T = AAS;
513     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T
514                       << "\n");
515     return T->isValidState();
516   };
517 
518   if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA))
519     S.indicatePessimisticFixpoint();
520   else if (T.hasValue())
521     S ^= *T;
522 }
523 
524 /// Helper class for generic deduction: return value -> returned position.
525 template <typename AAType, typename Base,
526           typename StateType = typename AAType::StateType>
527 struct AAReturnedFromReturnedValues : public Base {
528   AAReturnedFromReturnedValues(const IRPosition &IRP) : Base(IRP) {}
529 
530   /// See AbstractAttribute::updateImpl(...).
531   ChangeStatus updateImpl(Attributor &A) override {
532     StateType S;
533     clampReturnedValueStates<AAType, StateType>(A, *this, S);
534     // TODO: If we know we visited all returned values, thus no are assumed
535     // dead, we can take the known information from the state T.
536     return clampStateAndIndicateChange<StateType>(this->getState(), S);
537   }
538 };
539 
540 /// Clamp the information known at all call sites for a given argument
541 /// (identified by \p QueryingAA) into \p S.
542 template <typename AAType, typename StateType = typename AAType::StateType>
543 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA,
544                                         StateType &S) {
545   LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for "
546                     << static_cast<const AbstractAttribute &>(QueryingAA)
547                     << " into " << S << "\n");
548 
549   assert(QueryingAA.getIRPosition().getPositionKind() ==
550              IRPosition::IRP_ARGUMENT &&
551          "Can only clamp call site argument states for an argument position!");
552 
553   // Use an optional state as there might not be any return values and we want
554   // to join (IntegerState::operator&) the state of all there are.
555   Optional<StateType> T;
556 
557   // The argument number which is also the call site argument number.
558   unsigned ArgNo = QueryingAA.getIRPosition().getArgNo();
559 
560   auto CallSiteCheck = [&](CallSite CS) {
561     const IRPosition &CSArgPos = IRPosition::callsite_argument(CS, ArgNo);
562     const AAType &AA = A.getAAFor<AAType>(QueryingAA, CSArgPos);
563     LLVM_DEBUG(dbgs() << "[Attributor] CS: " << *CS.getInstruction()
564                       << " AA: " << AA.getAsStr() << " @" << CSArgPos << "\n");
565     const StateType &AAS = static_cast<const StateType &>(AA.getState());
566     if (T.hasValue())
567       *T &= AAS;
568     else
569       T = AAS;
570     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T
571                       << "\n");
572     return T->isValidState();
573   };
574 
575   if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true))
576     S.indicatePessimisticFixpoint();
577   else if (T.hasValue())
578     S ^= *T;
579 }
580 
581 /// Helper class for generic deduction: call site argument -> argument position.
582 template <typename AAType, typename Base,
583           typename StateType = typename AAType::StateType>
584 struct AAArgumentFromCallSiteArguments : public Base {
585   AAArgumentFromCallSiteArguments(const IRPosition &IRP) : Base(IRP) {}
586 
587   /// See AbstractAttribute::updateImpl(...).
588   ChangeStatus updateImpl(Attributor &A) override {
589     StateType S;
590     clampCallSiteArgumentStates<AAType, StateType>(A, *this, S);
591     // TODO: If we know we visited all incoming values, thus no are assumed
592     // dead, we can take the known information from the state T.
593     return clampStateAndIndicateChange<StateType>(this->getState(), S);
594   }
595 };
596 
597 /// Helper class for generic replication: function returned -> cs returned.
598 template <typename AAType, typename Base>
599 struct AACallSiteReturnedFromReturned : public Base {
600   AACallSiteReturnedFromReturned(const IRPosition &IRP) : Base(IRP) {}
601 
602   /// See AbstractAttribute::updateImpl(...).
603   ChangeStatus updateImpl(Attributor &A) override {
604     assert(this->getIRPosition().getPositionKind() ==
605                IRPosition::IRP_CALL_SITE_RETURNED &&
606            "Can only wrap function returned positions for call site returned "
607            "positions!");
608     auto &S = this->getState();
609 
610     const Function *AssociatedFunction =
611         this->getIRPosition().getAssociatedFunction();
612     if (!AssociatedFunction)
613       return S.indicatePessimisticFixpoint();
614 
615     IRPosition FnPos = IRPosition::returned(*AssociatedFunction);
616     const AAType &AA = A.getAAFor<AAType>(*this, FnPos);
617     return clampStateAndIndicateChange(
618         S, static_cast<const typename AAType::StateType &>(AA.getState()));
619   }
620 };
621 
622 /// -----------------------NoUnwind Function Attribute--------------------------
623 
624 struct AANoUnwindImpl : AANoUnwind {
625   AANoUnwindImpl(const IRPosition &IRP) : AANoUnwind(IRP) {}
626 
627   /// See AbstractAttribute::initialize(...).
628   void initialize(Attributor &A) override {
629     if (hasAttr({Attribute::NoUnwind}))
630       indicateOptimisticFixpoint();
631   }
632 
633   const std::string getAsStr() const override {
634     return getAssumed() ? "nounwind" : "may-unwind";
635   }
636 
637   /// See AbstractAttribute::updateImpl(...).
638   ChangeStatus updateImpl(Attributor &A) override {
639     auto Opcodes = {
640         (unsigned)Instruction::Invoke,      (unsigned)Instruction::CallBr,
641         (unsigned)Instruction::Call,        (unsigned)Instruction::CleanupRet,
642         (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
643 
644     auto CheckForNoUnwind = [&](Instruction &I) {
645       if (!I.mayThrow())
646         return true;
647 
648       if (ImmutableCallSite ICS = ImmutableCallSite(&I)) {
649         const auto &NoUnwindAA =
650             A.getAAFor<AANoUnwind>(*this, IRPosition::callsite_function(ICS));
651         return NoUnwindAA.isAssumedNoUnwind();
652       }
653       return false;
654     };
655 
656     if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes))
657       return indicatePessimisticFixpoint();
658 
659     return ChangeStatus::UNCHANGED;
660   }
661 };
662 
663 struct AANoUnwindFunction final : public AANoUnwindImpl {
664   AANoUnwindFunction(const IRPosition &IRP) : AANoUnwindImpl(IRP) {}
665 
666   /// See AbstractAttribute::trackStatistics()
667   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
668 };
669 
670 /// NoUnwind attribute deduction for a call sites.
671 using AANoUnwindCallSite = AANoUnwindFunction;
672 
673 /// --------------------- Function Return Values -------------------------------
674 
675 /// "Attribute" that collects all potential returned values and the return
676 /// instructions that they arise from.
677 ///
678 /// If there is a unique returned value R, the manifest method will:
679 ///   - mark R with the "returned" attribute, if R is an argument.
680 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState {
681 
682   /// Mapping of values potentially returned by the associated function to the
683   /// return instructions that might return them.
684   DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> ReturnedValues;
685 
686   SmallPtrSet<CallBase *, 8> UnresolvedCalls;
687 
688   /// State flags
689   ///
690   ///{
691   bool IsFixed;
692   bool IsValidState;
693   ///}
694 
695 public:
696   AAReturnedValuesImpl(const IRPosition &IRP) : AAReturnedValues(IRP) {}
697 
698   /// See AbstractAttribute::initialize(...).
699   void initialize(Attributor &A) override {
700     // Reset the state.
701     IsFixed = false;
702     IsValidState = true;
703     ReturnedValues.clear();
704 
705     Function *F = getAssociatedFunction();
706     if (!F || !F->hasExactDefinition()) {
707       indicatePessimisticFixpoint();
708       return;
709     }
710 
711     // The map from instruction opcodes to those instructions in the function.
712     auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F);
713 
714     // Look through all arguments, if one is marked as returned we are done.
715     for (Argument &Arg : F->args()) {
716       if (Arg.hasReturnedAttr()) {
717         auto &ReturnInstSet = ReturnedValues[&Arg];
718         for (Instruction *RI : OpcodeInstMap[Instruction::Ret])
719           ReturnInstSet.insert(cast<ReturnInst>(RI));
720 
721         indicateOptimisticFixpoint();
722         return;
723       }
724     }
725   }
726 
727   /// See AbstractAttribute::manifest(...).
728   ChangeStatus manifest(Attributor &A) override;
729 
730   /// See AbstractAttribute::getState(...).
731   AbstractState &getState() override { return *this; }
732 
733   /// See AbstractAttribute::getState(...).
734   const AbstractState &getState() const override { return *this; }
735 
736   /// See AbstractAttribute::updateImpl(Attributor &A).
737   ChangeStatus updateImpl(Attributor &A) override;
738 
739   llvm::iterator_range<iterator> returned_values() override {
740     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
741   }
742 
743   llvm::iterator_range<const_iterator> returned_values() const override {
744     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
745   }
746 
747   const SmallPtrSetImpl<CallBase *> &getUnresolvedCalls() const override {
748     return UnresolvedCalls;
749   }
750 
751   /// Return the number of potential return values, -1 if unknown.
752   size_t getNumReturnValues() const override {
753     return isValidState() ? ReturnedValues.size() : -1;
754   }
755 
756   /// Return an assumed unique return value if a single candidate is found. If
757   /// there cannot be one, return a nullptr. If it is not clear yet, return the
758   /// Optional::NoneType.
759   Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const;
760 
761   /// See AbstractState::checkForAllReturnedValues(...).
762   bool checkForAllReturnedValuesAndReturnInsts(
763       const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
764           &Pred) const override;
765 
766   /// Pretty print the attribute similar to the IR representation.
767   const std::string getAsStr() const override;
768 
769   /// See AbstractState::isAtFixpoint().
770   bool isAtFixpoint() const override { return IsFixed; }
771 
772   /// See AbstractState::isValidState().
773   bool isValidState() const override { return IsValidState; }
774 
775   /// See AbstractState::indicateOptimisticFixpoint(...).
776   ChangeStatus indicateOptimisticFixpoint() override {
777     IsFixed = true;
778     IsValidState &= true;
779     return ChangeStatus::UNCHANGED;
780   }
781 
782   ChangeStatus indicatePessimisticFixpoint() override {
783     IsFixed = true;
784     IsValidState = false;
785     return ChangeStatus::CHANGED;
786   }
787 };
788 
789 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
790   ChangeStatus Changed = ChangeStatus::UNCHANGED;
791 
792   // Bookkeeping.
793   assert(isValidState());
794   STATS_DECLTRACK(KnownReturnValues, FunctionReturn,
795                   "Number of function with known return values");
796 
797   // Check if we have an assumed unique return value that we could manifest.
798   Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
799 
800   if (!UniqueRV.hasValue() || !UniqueRV.getValue())
801     return Changed;
802 
803   // Bookkeeping.
804   STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
805                   "Number of function with unique return");
806 
807   // If the assumed unique return value is an argument, annotate it.
808   if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
809     getIRPosition() = IRPosition::argument(*UniqueRVArg);
810     Changed = IRAttribute::manifest(A) | Changed;
811   }
812 
813   return Changed;
814 }
815 
816 const std::string AAReturnedValuesImpl::getAsStr() const {
817   return (isAtFixpoint() ? "returns(#" : "may-return(#") +
818          (isValidState() ? std::to_string(getNumReturnValues()) : "?") +
819          ")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]";
820 }
821 
822 Optional<Value *>
823 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const {
824   // If checkForAllReturnedValues provides a unique value, ignoring potential
825   // undef values that can also be present, it is assumed to be the actual
826   // return value and forwarded to the caller of this method. If there are
827   // multiple, a nullptr is returned indicating there cannot be a unique
828   // returned value.
829   Optional<Value *> UniqueRV;
830 
831   auto Pred = [&](Value &RV) -> bool {
832     // If we found a second returned value and neither the current nor the saved
833     // one is an undef, there is no unique returned value. Undefs are special
834     // since we can pretend they have any value.
835     if (UniqueRV.hasValue() && UniqueRV != &RV &&
836         !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) {
837       UniqueRV = nullptr;
838       return false;
839     }
840 
841     // Do not overwrite a value with an undef.
842     if (!UniqueRV.hasValue() || !isa<UndefValue>(RV))
843       UniqueRV = &RV;
844 
845     return true;
846   };
847 
848   if (!A.checkForAllReturnedValues(Pred, *this))
849     UniqueRV = nullptr;
850 
851   return UniqueRV;
852 }
853 
854 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
855     const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
856         &Pred) const {
857   if (!isValidState())
858     return false;
859 
860   // Check all returned values but ignore call sites as long as we have not
861   // encountered an overdefined one during an update.
862   for (auto &It : ReturnedValues) {
863     Value *RV = It.first;
864     const SmallPtrSetImpl<ReturnInst *> &RetInsts = It.second;
865 
866     CallBase *CB = dyn_cast<CallBase>(RV);
867     if (CB && !UnresolvedCalls.count(CB))
868       continue;
869 
870     if (!Pred(*RV, RetInsts))
871       return false;
872   }
873 
874   return true;
875 }
876 
877 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) {
878   size_t NumUnresolvedCalls = UnresolvedCalls.size();
879   bool Changed = false;
880 
881   // State used in the value traversals starting in returned values.
882   struct RVState {
883     // The map in which we collect return values -> return instrs.
884     decltype(ReturnedValues) &RetValsMap;
885     // The flag to indicate a change.
886     bool &Changed;
887     // The return instrs we come from.
888     SmallPtrSet<ReturnInst *, 2> RetInsts;
889   };
890 
891   // Callback for a leaf value returned by the associated function.
892   auto VisitValueCB = [](Value &Val, RVState &RVS, bool) -> bool {
893     auto Size = RVS.RetValsMap[&Val].size();
894     RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end());
895     bool Inserted = RVS.RetValsMap[&Val].size() != Size;
896     RVS.Changed |= Inserted;
897     LLVM_DEBUG({
898       if (Inserted)
899         dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val
900                << " => " << RVS.RetInsts.size() << "\n";
901     });
902     return true;
903   };
904 
905   // Helper method to invoke the generic value traversal.
906   auto VisitReturnedValue = [&](Value &RV, RVState &RVS) {
907     IRPosition RetValPos = IRPosition::value(RV);
908     return genericValueTraversal<AAReturnedValues, RVState>(A, RetValPos, *this,
909                                                             RVS, VisitValueCB);
910   };
911 
912   // Callback for all "return intructions" live in the associated function.
913   auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) {
914     ReturnInst &Ret = cast<ReturnInst>(I);
915     RVState RVS({ReturnedValues, Changed, {}});
916     RVS.RetInsts.insert(&Ret);
917     return VisitReturnedValue(*Ret.getReturnValue(), RVS);
918   };
919 
920   // Start by discovering returned values from all live returned instructions in
921   // the associated function.
922   if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret}))
923     return indicatePessimisticFixpoint();
924 
925   // Once returned values "directly" present in the code are handled we try to
926   // resolve returned calls.
927   decltype(ReturnedValues) NewRVsMap;
928   for (auto &It : ReturnedValues) {
929     LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *It.first
930                       << " by #" << It.second.size() << " RIs\n");
931     CallBase *CB = dyn_cast<CallBase>(It.first);
932     if (!CB || UnresolvedCalls.count(CB))
933       continue;
934 
935     const auto &RetValAA =
936         A.getAAFor<AAReturnedValues>(*this, IRPosition::callsite_function(*CB));
937     LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: "
938                       << static_cast<const AbstractAttribute &>(RetValAA)
939                       << "\n");
940 
941     // Skip dead ends, thus if we do not know anything about the returned
942     // call we mark it as unresolved and it will stay that way.
943     if (!RetValAA.getState().isValidState()) {
944       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB
945                         << "\n");
946       UnresolvedCalls.insert(CB);
947       continue;
948     }
949 
950     // Do not try to learn partial information. If the callee has unresolved
951     // return values we will treat the call as unresolved/opaque.
952     auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls();
953     if (!RetValAAUnresolvedCalls.empty()) {
954       UnresolvedCalls.insert(CB);
955       continue;
956     }
957 
958     // Now check if we can track transitively returned values. If possible, thus
959     // if all return value can be represented in the current scope, do so.
960     bool Unresolved = false;
961     for (auto &RetValAAIt : RetValAA.returned_values()) {
962       Value *RetVal = RetValAAIt.first;
963       if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) ||
964           isa<Constant>(RetVal))
965         continue;
966       // Anything that did not fit in the above categories cannot be resolved,
967       // mark the call as unresolved.
968       LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value "
969                            "cannot be translated: "
970                         << *RetVal << "\n");
971       UnresolvedCalls.insert(CB);
972       Unresolved = true;
973       break;
974     }
975 
976     if (Unresolved)
977       continue;
978 
979     for (auto &RetValAAIt : RetValAA.returned_values()) {
980       Value *RetVal = RetValAAIt.first;
981       if (Argument *Arg = dyn_cast<Argument>(RetVal)) {
982         // Arguments are mapped to call site operands and we begin the traversal
983         // again.
984         bool Unused = false;
985         RVState RVS({NewRVsMap, Unused, RetValAAIt.second});
986         VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS);
987         continue;
988       } else if (isa<CallBase>(RetVal)) {
989         // Call sites are resolved by the callee attribute over time, no need to
990         // do anything for us.
991         continue;
992       } else if (isa<Constant>(RetVal)) {
993         // Constants are valid everywhere, we can simply take them.
994         NewRVsMap[RetVal].insert(It.second.begin(), It.second.end());
995         continue;
996       }
997     }
998   }
999 
1000   // To avoid modifications to the ReturnedValues map while we iterate over it
1001   // we kept record of potential new entries in a copy map, NewRVsMap.
1002   for (auto &It : NewRVsMap) {
1003     assert(!It.second.empty() && "Entry does not add anything.");
1004     auto &ReturnInsts = ReturnedValues[It.first];
1005     for (ReturnInst *RI : It.second)
1006       if (ReturnInsts.insert(RI).second) {
1007         LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value "
1008                           << *It.first << " => " << *RI << "\n");
1009         Changed = true;
1010       }
1011   }
1012 
1013   Changed |= (NumUnresolvedCalls != UnresolvedCalls.size());
1014   return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
1015 }
1016 
1017 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl {
1018   AAReturnedValuesFunction(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {}
1019 
1020   /// See AbstractAttribute::trackStatistics()
1021   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) }
1022 };
1023 
1024 /// Returned values information for a call sites.
1025 using AAReturnedValuesCallSite = AAReturnedValuesFunction;
1026 
1027 /// ------------------------ NoSync Function Attribute -------------------------
1028 
1029 struct AANoSyncImpl : AANoSync {
1030   AANoSyncImpl(const IRPosition &IRP) : AANoSync(IRP) {}
1031 
1032   /// See AbstractAttribute::initialize(...).
1033   void initialize(Attributor &A) override {
1034     if (hasAttr({Attribute::NoSync}))
1035       indicateOptimisticFixpoint();
1036   }
1037 
1038   const std::string getAsStr() const override {
1039     return getAssumed() ? "nosync" : "may-sync";
1040   }
1041 
1042   /// See AbstractAttribute::updateImpl(...).
1043   ChangeStatus updateImpl(Attributor &A) override;
1044 
1045   /// Helper function used to determine whether an instruction is non-relaxed
1046   /// atomic. In other words, if an atomic instruction does not have unordered
1047   /// or monotonic ordering
1048   static bool isNonRelaxedAtomic(Instruction *I);
1049 
1050   /// Helper function used to determine whether an instruction is volatile.
1051   static bool isVolatile(Instruction *I);
1052 
1053   /// Helper function uset to check if intrinsic is volatile (memcpy, memmove,
1054   /// memset).
1055   static bool isNoSyncIntrinsic(Instruction *I);
1056 };
1057 
1058 bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) {
1059   if (!I->isAtomic())
1060     return false;
1061 
1062   AtomicOrdering Ordering;
1063   switch (I->getOpcode()) {
1064   case Instruction::AtomicRMW:
1065     Ordering = cast<AtomicRMWInst>(I)->getOrdering();
1066     break;
1067   case Instruction::Store:
1068     Ordering = cast<StoreInst>(I)->getOrdering();
1069     break;
1070   case Instruction::Load:
1071     Ordering = cast<LoadInst>(I)->getOrdering();
1072     break;
1073   case Instruction::Fence: {
1074     auto *FI = cast<FenceInst>(I);
1075     if (FI->getSyncScopeID() == SyncScope::SingleThread)
1076       return false;
1077     Ordering = FI->getOrdering();
1078     break;
1079   }
1080   case Instruction::AtomicCmpXchg: {
1081     AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering();
1082     AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering();
1083     // Only if both are relaxed, than it can be treated as relaxed.
1084     // Otherwise it is non-relaxed.
1085     if (Success != AtomicOrdering::Unordered &&
1086         Success != AtomicOrdering::Monotonic)
1087       return true;
1088     if (Failure != AtomicOrdering::Unordered &&
1089         Failure != AtomicOrdering::Monotonic)
1090       return true;
1091     return false;
1092   }
1093   default:
1094     llvm_unreachable(
1095         "New atomic operations need to be known in the attributor.");
1096   }
1097 
1098   // Relaxed.
1099   if (Ordering == AtomicOrdering::Unordered ||
1100       Ordering == AtomicOrdering::Monotonic)
1101     return false;
1102   return true;
1103 }
1104 
1105 /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics.
1106 /// FIXME: We should ipmrove the handling of intrinsics.
1107 bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) {
1108   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1109     switch (II->getIntrinsicID()) {
1110     /// Element wise atomic memory intrinsics are can only be unordered,
1111     /// therefore nosync.
1112     case Intrinsic::memset_element_unordered_atomic:
1113     case Intrinsic::memmove_element_unordered_atomic:
1114     case Intrinsic::memcpy_element_unordered_atomic:
1115       return true;
1116     case Intrinsic::memset:
1117     case Intrinsic::memmove:
1118     case Intrinsic::memcpy:
1119       if (!cast<MemIntrinsic>(II)->isVolatile())
1120         return true;
1121       return false;
1122     default:
1123       return false;
1124     }
1125   }
1126   return false;
1127 }
1128 
1129 bool AANoSyncImpl::isVolatile(Instruction *I) {
1130   assert(!ImmutableCallSite(I) && !isa<CallBase>(I) &&
1131          "Calls should not be checked here");
1132 
1133   switch (I->getOpcode()) {
1134   case Instruction::AtomicRMW:
1135     return cast<AtomicRMWInst>(I)->isVolatile();
1136   case Instruction::Store:
1137     return cast<StoreInst>(I)->isVolatile();
1138   case Instruction::Load:
1139     return cast<LoadInst>(I)->isVolatile();
1140   case Instruction::AtomicCmpXchg:
1141     return cast<AtomicCmpXchgInst>(I)->isVolatile();
1142   default:
1143     return false;
1144   }
1145 }
1146 
1147 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
1148 
1149   auto CheckRWInstForNoSync = [&](Instruction &I) {
1150     /// We are looking for volatile instructions or Non-Relaxed atomics.
1151     /// FIXME: We should ipmrove the handling of intrinsics.
1152 
1153     if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I))
1154       return true;
1155 
1156     if (ImmutableCallSite ICS = ImmutableCallSite(&I)) {
1157       if (ICS.hasFnAttr(Attribute::NoSync))
1158         return true;
1159 
1160       const auto &NoSyncAA =
1161           A.getAAFor<AANoSync>(*this, IRPosition::callsite_function(ICS));
1162       if (NoSyncAA.isAssumedNoSync())
1163         return true;
1164       return false;
1165     }
1166 
1167     if (!isVolatile(&I) && !isNonRelaxedAtomic(&I))
1168       return true;
1169 
1170     return false;
1171   };
1172 
1173   auto CheckForNoSync = [&](Instruction &I) {
1174     // At this point we handled all read/write effects and they are all
1175     // nosync, so they can be skipped.
1176     if (I.mayReadOrWriteMemory())
1177       return true;
1178 
1179     // non-convergent and readnone imply nosync.
1180     return !ImmutableCallSite(&I).isConvergent();
1181   };
1182 
1183   if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) ||
1184       !A.checkForAllCallLikeInstructions(CheckForNoSync, *this))
1185     return indicatePessimisticFixpoint();
1186 
1187   return ChangeStatus::UNCHANGED;
1188 }
1189 
1190 struct AANoSyncFunction final : public AANoSyncImpl {
1191   AANoSyncFunction(const IRPosition &IRP) : AANoSyncImpl(IRP) {}
1192 
1193   /// See AbstractAttribute::trackStatistics()
1194   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
1195 };
1196 
1197 /// NoSync attribute deduction for a call sites.
1198 using AANoSyncCallSite = AANoSyncFunction;
1199 
1200 /// ------------------------ No-Free Attributes ----------------------------
1201 
1202 struct AANoFreeImpl : public AANoFree {
1203   AANoFreeImpl(const IRPosition &IRP) : AANoFree(IRP) {}
1204 
1205   /// See AbstractAttribute::initialize(...).
1206   void initialize(Attributor &A) override {
1207     if (hasAttr({Attribute::NoFree}))
1208       indicateOptimisticFixpoint();
1209   }
1210 
1211   /// See AbstractAttribute::updateImpl(...).
1212   ChangeStatus updateImpl(Attributor &A) override {
1213     auto CheckForNoFree = [&](Instruction &I) {
1214       ImmutableCallSite ICS(&I);
1215       if (ICS.hasFnAttr(Attribute::NoFree))
1216         return true;
1217 
1218       const auto &NoFreeAA =
1219           A.getAAFor<AANoFree>(*this, IRPosition::callsite_function(ICS));
1220       return NoFreeAA.isAssumedNoFree();
1221     };
1222 
1223     if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this))
1224       return indicatePessimisticFixpoint();
1225     return ChangeStatus::UNCHANGED;
1226   }
1227 
1228   /// See AbstractAttribute::getAsStr().
1229   const std::string getAsStr() const override {
1230     return getAssumed() ? "nofree" : "may-free";
1231   }
1232 };
1233 
1234 struct AANoFreeFunction final : public AANoFreeImpl {
1235   AANoFreeFunction(const IRPosition &IRP) : AANoFreeImpl(IRP) {}
1236 
1237   /// See AbstractAttribute::trackStatistics()
1238   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
1239 };
1240 
1241 /// NoFree attribute deduction for a call sites.
1242 using AANoFreeCallSite = AANoFreeFunction;
1243 
1244 /// ------------------------ NonNull Argument Attribute ------------------------
1245 struct AANonNullImpl : AANonNull {
1246   AANonNullImpl(const IRPosition &IRP) : AANonNull(IRP) {}
1247 
1248   /// See AbstractAttribute::initialize(...).
1249   void initialize(Attributor &A) override {
1250     if (hasAttr({Attribute::NonNull, Attribute::Dereferenceable}))
1251       indicateOptimisticFixpoint();
1252   }
1253 
1254   /// See AbstractAttribute::getAsStr().
1255   const std::string getAsStr() const override {
1256     return getAssumed() ? "nonnull" : "may-null";
1257   }
1258 };
1259 
1260 /// NonNull attribute for a floating value.
1261 struct AANonNullFloating : AANonNullImpl {
1262   AANonNullFloating(const IRPosition &IRP) : AANonNullImpl(IRP) {}
1263 
1264   /// See AbstractAttribute::initialize(...).
1265   void initialize(Attributor &A) override {
1266     AANonNullImpl::initialize(A);
1267 
1268     if (isAtFixpoint())
1269       return;
1270 
1271     const IRPosition &IRP = getIRPosition();
1272     const Value &V = IRP.getAssociatedValue();
1273     const DataLayout &DL = A.getDataLayout();
1274 
1275     // TODO: This context sensitive query should be removed once we can do
1276     // context sensitive queries in the genericValueTraversal below.
1277     if (isKnownNonZero(&V, DL, 0, /* TODO: AC */ nullptr, IRP.getCtxI(),
1278                        /* TODO: DT */ nullptr))
1279       indicateOptimisticFixpoint();
1280   }
1281 
1282   /// See AbstractAttribute::updateImpl(...).
1283   ChangeStatus updateImpl(Attributor &A) override {
1284     const DataLayout &DL = A.getDataLayout();
1285 
1286     auto VisitValueCB = [&](Value &V, AAAlign::StateType &T,
1287                             bool Stripped) -> bool {
1288       const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V));
1289       if (!Stripped && this == &AA) {
1290         if (!isKnownNonZero(&V, DL, 0, /* TODO: AC */ nullptr,
1291                          /* TODO: CtxI */ nullptr,
1292                          /* TODO: DT */ nullptr))
1293           T.indicatePessimisticFixpoint();
1294       } else {
1295         // Use abstract attribute information.
1296         const AANonNull::StateType &NS =
1297             static_cast<const AANonNull::StateType &>(AA.getState());
1298         T ^= NS;
1299       }
1300       return T.isValidState();
1301     };
1302 
1303     StateType T;
1304     if (!genericValueTraversal<AANonNull, StateType>(A, getIRPosition(), *this,
1305                                                      T, VisitValueCB))
1306       return indicatePessimisticFixpoint();
1307 
1308     return clampStateAndIndicateChange(getState(), T);
1309   }
1310 
1311   /// See AbstractAttribute::trackStatistics()
1312   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
1313 };
1314 
1315 /// NonNull attribute for function return value.
1316 struct AANonNullReturned final
1317     : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl> {
1318   AANonNullReturned(const IRPosition &IRP)
1319       : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl>(IRP) {}
1320 
1321   /// See AbstractAttribute::trackStatistics()
1322   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
1323 };
1324 
1325 /// NonNull attribute for function argument.
1326 struct AANonNullArgument final
1327     : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> {
1328   AANonNullArgument(const IRPosition &IRP)
1329       : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP) {}
1330 
1331   /// See AbstractAttribute::trackStatistics()
1332   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
1333 };
1334 
1335 struct AANonNullCallSiteArgument final : AANonNullFloating {
1336   AANonNullCallSiteArgument(const IRPosition &IRP) : AANonNullFloating(IRP) {}
1337 
1338   /// See AbstractAttribute::trackStatistics()
1339   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
1340 };
1341 
1342 /// NonNull attribute for a call site return position.
1343 struct AANonNullCallSiteReturned final
1344     : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl> {
1345   AANonNullCallSiteReturned(const IRPosition &IRP)
1346       : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl>(IRP) {}
1347 
1348   /// See AbstractAttribute::trackStatistics()
1349   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) }
1350 };
1351 
1352 /// ------------------------ No-Recurse Attributes ----------------------------
1353 
1354 struct AANoRecurseImpl : public AANoRecurse {
1355   AANoRecurseImpl(const IRPosition &IRP) : AANoRecurse(IRP) {}
1356 
1357   /// See AbstractAttribute::initialize(...).
1358   void initialize(Attributor &A) override {
1359     if (hasAttr({getAttrKind()})) {
1360       indicateOptimisticFixpoint();
1361       return;
1362     }
1363   }
1364 
1365   /// See AbstractAttribute::getAsStr()
1366   const std::string getAsStr() const override {
1367     return getAssumed() ? "norecurse" : "may-recurse";
1368   }
1369 };
1370 
1371 struct AANoRecurseFunction final : AANoRecurseImpl {
1372   AANoRecurseFunction(const IRPosition &IRP) : AANoRecurseImpl(IRP) {}
1373 
1374   /// See AbstractAttribute::updateImpl(...).
1375   ChangeStatus updateImpl(Attributor &A) override {
1376     // TODO: Implement this.
1377     return indicatePessimisticFixpoint();
1378   }
1379 
1380   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
1381 };
1382 
1383 using AANoRecurseCallSite = AANoRecurseFunction;
1384 
1385 /// ------------------------ Will-Return Attributes ----------------------------
1386 
1387 // Helper function that checks whether a function has any cycle.
1388 // TODO: Replace with more efficent code
1389 static bool containsCycle(Function &F) {
1390   SmallPtrSet<BasicBlock *, 32> Visited;
1391 
1392   // Traverse BB by dfs and check whether successor is already visited.
1393   for (BasicBlock *BB : depth_first(&F)) {
1394     Visited.insert(BB);
1395     for (auto *SuccBB : successors(BB)) {
1396       if (Visited.count(SuccBB))
1397         return true;
1398     }
1399   }
1400   return false;
1401 }
1402 
1403 // Helper function that checks the function have a loop which might become an
1404 // endless loop
1405 // FIXME: Any cycle is regarded as endless loop for now.
1406 //        We have to allow some patterns.
1407 static bool containsPossiblyEndlessLoop(Function *F) {
1408   return !F || !F->hasExactDefinition() || containsCycle(*F);
1409 }
1410 
1411 struct AAWillReturnImpl : public AAWillReturn {
1412   AAWillReturnImpl(const IRPosition &IRP) : AAWillReturn(IRP) {}
1413 
1414   /// See AbstractAttribute::initialize(...).
1415   void initialize(Attributor &A) override {
1416     if (hasAttr({Attribute::WillReturn})) {
1417       indicateOptimisticFixpoint();
1418       return;
1419     }
1420 
1421     Function *F = getAssociatedFunction();
1422     if (containsPossiblyEndlessLoop(F))
1423       indicatePessimisticFixpoint();
1424   }
1425 
1426   /// See AbstractAttribute::updateImpl(...).
1427   ChangeStatus updateImpl(Attributor &A) override {
1428     auto CheckForWillReturn = [&](Instruction &I) {
1429       IRPosition IPos = IRPosition::callsite_function(ImmutableCallSite(&I));
1430       const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos);
1431       if (WillReturnAA.isKnownWillReturn())
1432         return true;
1433       if (!WillReturnAA.isAssumedWillReturn())
1434         return false;
1435       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos);
1436       return NoRecurseAA.isAssumedNoRecurse();
1437     };
1438 
1439     if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this))
1440       return indicatePessimisticFixpoint();
1441 
1442     return ChangeStatus::UNCHANGED;
1443   }
1444 
1445   /// See AbstractAttribute::getAsStr()
1446   const std::string getAsStr() const override {
1447     return getAssumed() ? "willreturn" : "may-noreturn";
1448   }
1449 };
1450 
1451 struct AAWillReturnFunction final : AAWillReturnImpl {
1452   AAWillReturnFunction(const IRPosition &IRP) : AAWillReturnImpl(IRP) {}
1453 
1454   /// See AbstractAttribute::trackStatistics()
1455   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
1456 };
1457 
1458 /// WillReturn attribute deduction for a call sites.
1459 using AAWillReturnCallSite = AAWillReturnFunction;
1460 
1461 /// ------------------------ NoAlias Argument Attribute ------------------------
1462 
1463 struct AANoAliasImpl : AANoAlias {
1464   AANoAliasImpl(const IRPosition &IRP) : AANoAlias(IRP) {}
1465 
1466   /// See AbstractAttribute::initialize(...).
1467   void initialize(Attributor &A) override {
1468     if (hasAttr({Attribute::NoAlias}))
1469       indicateOptimisticFixpoint();
1470   }
1471 
1472   const std::string getAsStr() const override {
1473     return getAssumed() ? "noalias" : "may-alias";
1474   }
1475 };
1476 
1477 /// NoAlias attribute for a floating value.
1478 struct AANoAliasFloating final : AANoAliasImpl {
1479   AANoAliasFloating(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
1480 
1481   /// See AbstractAttribute::updateImpl(...).
1482   ChangeStatus updateImpl(Attributor &A) override {
1483     // TODO: Implement this.
1484     return indicatePessimisticFixpoint();
1485   }
1486 
1487   /// See AbstractAttribute::trackStatistics()
1488   void trackStatistics() const override {
1489     STATS_DECLTRACK_FLOATING_ATTR(noalias)
1490   }
1491 };
1492 
1493 /// NoAlias attribute for an argument.
1494 struct AANoAliasArgument final : AANoAliasImpl {
1495   AANoAliasArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
1496 
1497   /// See AbstractAttribute::updateImpl(...).
1498   ChangeStatus updateImpl(Attributor &A) override {
1499     // TODO: Implement this.
1500     return indicatePessimisticFixpoint();
1501   }
1502 
1503   /// See AbstractAttribute::trackStatistics()
1504   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
1505 };
1506 
1507 struct AANoAliasCallSiteArgument final : AANoAliasImpl {
1508   AANoAliasCallSiteArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
1509 
1510   /// See AbstractAttribute::updateImpl(...).
1511   ChangeStatus updateImpl(Attributor &A) override {
1512     // TODO: Implement this.
1513     return indicatePessimisticFixpoint();
1514   }
1515 
1516   /// See AbstractAttribute::trackStatistics()
1517   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
1518 };
1519 
1520 /// NoAlias attribute for function return value.
1521 struct AANoAliasReturned final : AANoAliasImpl {
1522   AANoAliasReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {}
1523 
1524   /// See AbstractAttribute::updateImpl(...).
1525   virtual ChangeStatus updateImpl(Attributor &A) override {
1526 
1527     auto CheckReturnValue = [&](Value &RV) -> bool {
1528       if (Constant *C = dyn_cast<Constant>(&RV))
1529         if (C->isNullValue() || isa<UndefValue>(C))
1530           return true;
1531 
1532       /// For now, we can only deduce noalias if we have call sites.
1533       /// FIXME: add more support.
1534       ImmutableCallSite ICS(&RV);
1535       if (!ICS)
1536         return false;
1537 
1538       const auto &NoAliasAA =
1539           A.getAAFor<AANoAlias>(*this, IRPosition::callsite_returned(ICS));
1540       if (!NoAliasAA.isAssumedNoAlias())
1541         return false;
1542 
1543       /// FIXME: We can improve capture check in two ways:
1544       /// 1. Use the AANoCapture facilities.
1545       /// 2. Use the location of return insts for escape queries.
1546       if (PointerMayBeCaptured(&RV, /* ReturnCaptures */ false,
1547                                /* StoreCaptures */ true))
1548         return false;
1549 
1550       return true;
1551     };
1552 
1553     if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
1554       return indicatePessimisticFixpoint();
1555 
1556     return ChangeStatus::UNCHANGED;
1557   }
1558 
1559   /// See AbstractAttribute::trackStatistics()
1560   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
1561 };
1562 
1563 /// NoAlias attribute deduction for a call site return value.
1564 using AANoAliasCallSiteReturned = AANoAliasReturned;
1565 
1566 /// -------------------AAIsDead Function Attribute-----------------------
1567 
1568 struct AAIsDeadImpl : public AAIsDead {
1569   AAIsDeadImpl(const IRPosition &IRP) : AAIsDead(IRP) {}
1570 
1571   void initialize(Attributor &A) override {
1572     const Function *F = getAssociatedFunction();
1573     if (!F || !F->hasExactDefinition()) {
1574       indicatePessimisticFixpoint();
1575       return;
1576     }
1577 
1578     ToBeExploredPaths.insert(&(F->getEntryBlock().front()));
1579     AssumedLiveBlocks.insert(&(F->getEntryBlock()));
1580     for (size_t i = 0; i < ToBeExploredPaths.size(); ++i)
1581       if (const Instruction *NextNoReturnI =
1582               findNextNoReturn(A, ToBeExploredPaths[i]))
1583         NoReturnCalls.insert(NextNoReturnI);
1584   }
1585 
1586   /// Find the next assumed noreturn instruction in the block of \p I starting
1587   /// from, thus including, \p I.
1588   ///
1589   /// The caller is responsible to monitor the ToBeExploredPaths set as new
1590   /// instructions discovered in other basic block will be placed in there.
1591   ///
1592   /// \returns The next assumed noreturn instructions in the block of \p I
1593   ///          starting from, thus including, \p I.
1594   const Instruction *findNextNoReturn(Attributor &A, const Instruction *I);
1595 
1596   /// See AbstractAttribute::getAsStr().
1597   const std::string getAsStr() const override {
1598     return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
1599            std::to_string(getAssociatedFunction()->size()) + "][#NRI " +
1600            std::to_string(NoReturnCalls.size()) + "]";
1601   }
1602 
1603   /// See AbstractAttribute::manifest(...).
1604   ChangeStatus manifest(Attributor &A) override {
1605     assert(getState().isValidState() &&
1606            "Attempted to manifest an invalid state!");
1607 
1608     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1609     const Function &F = *getAssociatedFunction();
1610 
1611     // Flag to determine if we can change an invoke to a call assuming the
1612     // callee is nounwind. This is not possible if the personality of the
1613     // function allows to catch asynchronous exceptions.
1614     bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
1615 
1616     for (const Instruction *NRC : NoReturnCalls) {
1617       Instruction *I = const_cast<Instruction *>(NRC);
1618       BasicBlock *BB = I->getParent();
1619       Instruction *SplitPos = I->getNextNode();
1620 
1621       if (auto *II = dyn_cast<InvokeInst>(I)) {
1622         // If we keep the invoke the split position is at the beginning of the
1623         // normal desitination block (it invokes a noreturn function after all).
1624         BasicBlock *NormalDestBB = II->getNormalDest();
1625         SplitPos = &NormalDestBB->front();
1626 
1627         /// Invoke is replaced with a call and unreachable is placed after it if
1628         /// the callee is nounwind and noreturn. Otherwise, we keep the invoke
1629         /// and only place an unreachable in the normal successor.
1630         if (Invoke2CallAllowed) {
1631           if (Function *Callee = II->getCalledFunction()) {
1632             const IRPosition &IPos = IRPosition::callsite_function(*II);
1633             const auto &AANoUnw = A.getAAFor<AANoUnwind>(*this, IPos);
1634             if (AANoUnw.isAssumedNoUnwind()) {
1635               LLVM_DEBUG(dbgs()
1636                          << "[AAIsDead] Replace invoke with call inst\n");
1637               // We do not need an invoke (II) but instead want a call followed
1638               // by an unreachable. However, we do not remove II as other
1639               // abstract attributes might have it cached as part of their
1640               // results. Given that we modify the CFG anyway, we simply keep II
1641               // around but in a new dead block. To avoid II being live through
1642               // a different edge we have to ensure the block we place it in is
1643               // only reached from the current block of II and then not reached
1644               // at all when we insert the unreachable.
1645               SplitBlockPredecessors(NormalDestBB, {BB}, ".i2c");
1646               CallInst *CI = createCallMatchingInvoke(II);
1647               CI->insertBefore(II);
1648               CI->takeName(II);
1649               II->replaceAllUsesWith(CI);
1650               SplitPos = CI->getNextNode();
1651             }
1652           }
1653         }
1654       }
1655 
1656       BB = SplitPos->getParent();
1657       SplitBlock(BB, SplitPos);
1658       changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false);
1659       HasChanged = ChangeStatus::CHANGED;
1660     }
1661 
1662     return HasChanged;
1663   }
1664 
1665   /// See AbstractAttribute::updateImpl(...).
1666   ChangeStatus updateImpl(Attributor &A) override;
1667 
1668   /// See AAIsDead::isAssumedDead(BasicBlock *).
1669   bool isAssumedDead(const BasicBlock *BB) const override {
1670     assert(BB->getParent() == getAssociatedFunction() &&
1671            "BB must be in the same anchor scope function.");
1672 
1673     if (!getAssumed())
1674       return false;
1675     return !AssumedLiveBlocks.count(BB);
1676   }
1677 
1678   /// See AAIsDead::isKnownDead(BasicBlock *).
1679   bool isKnownDead(const BasicBlock *BB) const override {
1680     return getKnown() && isAssumedDead(BB);
1681   }
1682 
1683   /// See AAIsDead::isAssumed(Instruction *I).
1684   bool isAssumedDead(const Instruction *I) const override {
1685     assert(I->getParent()->getParent() == getAssociatedFunction() &&
1686            "Instruction must be in the same anchor scope function.");
1687 
1688     if (!getAssumed())
1689       return false;
1690 
1691     // If it is not in AssumedLiveBlocks then it for sure dead.
1692     // Otherwise, it can still be after noreturn call in a live block.
1693     if (!AssumedLiveBlocks.count(I->getParent()))
1694       return true;
1695 
1696     // If it is not after a noreturn call, than it is live.
1697     return isAfterNoReturn(I);
1698   }
1699 
1700   /// See AAIsDead::isKnownDead(Instruction *I).
1701   bool isKnownDead(const Instruction *I) const override {
1702     return getKnown() && isAssumedDead(I);
1703   }
1704 
1705   /// Check if instruction is after noreturn call, in other words, assumed dead.
1706   bool isAfterNoReturn(const Instruction *I) const;
1707 
1708   /// Determine if \p F might catch asynchronous exceptions.
1709   static bool mayCatchAsynchronousExceptions(const Function &F) {
1710     return F.hasPersonalityFn() && !canSimplifyInvokeNoUnwind(&F);
1711   }
1712 
1713   /// Collection of to be explored paths.
1714   SmallSetVector<const Instruction *, 8> ToBeExploredPaths;
1715 
1716   /// Collection of all assumed live BasicBlocks.
1717   DenseSet<const BasicBlock *> AssumedLiveBlocks;
1718 
1719   /// Collection of calls with noreturn attribute, assumed or knwon.
1720   SmallSetVector<const Instruction *, 4> NoReturnCalls;
1721 };
1722 
1723 struct AAIsDeadFunction final : public AAIsDeadImpl {
1724   AAIsDeadFunction(const IRPosition &IRP) : AAIsDeadImpl(IRP) {}
1725 
1726   /// See AbstractAttribute::trackStatistics()
1727   void trackStatistics() const override {
1728     STATS_DECL(DeadBlocks, Function,
1729                "Number of basic blocks classified as dead");
1730     BUILD_STAT_NAME(DeadBlocks, Function) +=
1731         getAssociatedFunction()->size() - AssumedLiveBlocks.size();
1732     STATS_DECL(PartiallyDeadBlocks, Function,
1733                "Number of basic blocks classified as partially dead");
1734     BUILD_STAT_NAME(PartiallyDeadBlocks, Function) += NoReturnCalls.size();
1735   }
1736 };
1737 
1738 bool AAIsDeadImpl::isAfterNoReturn(const Instruction *I) const {
1739   const Instruction *PrevI = I->getPrevNode();
1740   while (PrevI) {
1741     if (NoReturnCalls.count(PrevI))
1742       return true;
1743     PrevI = PrevI->getPrevNode();
1744   }
1745   return false;
1746 }
1747 
1748 const Instruction *AAIsDeadImpl::findNextNoReturn(Attributor &A,
1749                                                   const Instruction *I) {
1750   const BasicBlock *BB = I->getParent();
1751   const Function &F = *BB->getParent();
1752 
1753   // Flag to determine if we can change an invoke to a call assuming the callee
1754   // is nounwind. This is not possible if the personality of the function allows
1755   // to catch asynchronous exceptions.
1756   bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
1757 
1758   // TODO: We should have a function that determines if an "edge" is dead.
1759   //       Edges could be from an instruction to the next or from a terminator
1760   //       to the successor. For now, we need to special case the unwind block
1761   //       of InvokeInst below.
1762 
1763   while (I) {
1764     ImmutableCallSite ICS(I);
1765 
1766     if (ICS) {
1767       const IRPosition &IPos = IRPosition::callsite_function(ICS);
1768       // Regarless of the no-return property of an invoke instruction we only
1769       // learn that the regular successor is not reachable through this
1770       // instruction but the unwind block might still be.
1771       if (auto *Invoke = dyn_cast<InvokeInst>(I)) {
1772         // Use nounwind to justify the unwind block is dead as well.
1773         const auto &AANoUnw = A.getAAFor<AANoUnwind>(*this, IPos);
1774         if (!Invoke2CallAllowed || !AANoUnw.isAssumedNoUnwind()) {
1775           AssumedLiveBlocks.insert(Invoke->getUnwindDest());
1776           ToBeExploredPaths.insert(&Invoke->getUnwindDest()->front());
1777         }
1778       }
1779 
1780       const auto &NoReturnAA = A.getAAFor<AANoReturn>(*this, IPos);
1781       if (NoReturnAA.isAssumedNoReturn())
1782         return I;
1783     }
1784 
1785     I = I->getNextNode();
1786   }
1787 
1788   // get new paths (reachable blocks).
1789   for (const BasicBlock *SuccBB : successors(BB)) {
1790     AssumedLiveBlocks.insert(SuccBB);
1791     ToBeExploredPaths.insert(&SuccBB->front());
1792   }
1793 
1794   // No noreturn instruction found.
1795   return nullptr;
1796 }
1797 
1798 ChangeStatus AAIsDeadImpl::updateImpl(Attributor &A) {
1799   // Temporary collection to iterate over existing noreturn instructions. This
1800   // will alow easier modification of NoReturnCalls collection
1801   SmallVector<const Instruction *, 8> NoReturnChanged;
1802   ChangeStatus Status = ChangeStatus::UNCHANGED;
1803 
1804   for (const Instruction *I : NoReturnCalls)
1805     NoReturnChanged.push_back(I);
1806 
1807   for (const Instruction *I : NoReturnChanged) {
1808     size_t Size = ToBeExploredPaths.size();
1809 
1810     const Instruction *NextNoReturnI = findNextNoReturn(A, I);
1811     if (NextNoReturnI != I) {
1812       Status = ChangeStatus::CHANGED;
1813       NoReturnCalls.remove(I);
1814       if (NextNoReturnI)
1815         NoReturnCalls.insert(NextNoReturnI);
1816     }
1817 
1818     // Explore new paths.
1819     while (Size != ToBeExploredPaths.size()) {
1820       Status = ChangeStatus::CHANGED;
1821       if (const Instruction *NextNoReturnI =
1822               findNextNoReturn(A, ToBeExploredPaths[Size++]))
1823         NoReturnCalls.insert(NextNoReturnI);
1824     }
1825   }
1826 
1827   LLVM_DEBUG(dbgs() << "[AAIsDead] AssumedLiveBlocks: "
1828                     << AssumedLiveBlocks.size() << " Total number of blocks: "
1829                     << getAssociatedFunction()->size() << "\n");
1830 
1831   // If we know everything is live there is no need to query for liveness.
1832   if (NoReturnCalls.empty() &&
1833       getAssociatedFunction()->size() == AssumedLiveBlocks.size()) {
1834     // Indicating a pessimistic fixpoint will cause the state to be "invalid"
1835     // which will cause the Attributor to not return the AAIsDead on request,
1836     // which will prevent us from querying isAssumedDead().
1837     indicatePessimisticFixpoint();
1838     assert(!isValidState() && "Expected an invalid state!");
1839   }
1840 
1841   return Status;
1842 }
1843 
1844 /// Liveness information for a call sites.
1845 //
1846 // TODO: Once we have call site specific value information we can provide call
1847 //       site specific liveness liveness information and then it makes sense to
1848 //       specialize attributes for call sites instead of redirecting requests to
1849 //       the callee.
1850 using AAIsDeadCallSite = AAIsDeadFunction;
1851 
1852 /// -------------------- Dereferenceable Argument Attribute --------------------
1853 
1854 struct DerefState : AbstractState {
1855 
1856   /// State representing for dereferenceable bytes.
1857   IntegerState DerefBytesState;
1858 
1859   /// State representing that whether the value is globaly dereferenceable.
1860   BooleanState GlobalState;
1861 
1862   /// See AbstractState::isValidState()
1863   bool isValidState() const override { return DerefBytesState.isValidState(); }
1864 
1865   /// See AbstractState::isAtFixpoint()
1866   bool isAtFixpoint() const override {
1867     return !isValidState() ||
1868            (DerefBytesState.isAtFixpoint() && GlobalState.isAtFixpoint());
1869   }
1870 
1871   /// See AbstractState::indicateOptimisticFixpoint(...)
1872   ChangeStatus indicateOptimisticFixpoint() override {
1873     DerefBytesState.indicateOptimisticFixpoint();
1874     GlobalState.indicateOptimisticFixpoint();
1875     return ChangeStatus::UNCHANGED;
1876   }
1877 
1878   /// See AbstractState::indicatePessimisticFixpoint(...)
1879   ChangeStatus indicatePessimisticFixpoint() override {
1880     DerefBytesState.indicatePessimisticFixpoint();
1881     GlobalState.indicatePessimisticFixpoint();
1882     return ChangeStatus::CHANGED;
1883   }
1884 
1885   /// Update known dereferenceable bytes.
1886   void takeKnownDerefBytesMaximum(uint64_t Bytes) {
1887     DerefBytesState.takeKnownMaximum(Bytes);
1888   }
1889 
1890   /// Update assumed dereferenceable bytes.
1891   void takeAssumedDerefBytesMinimum(uint64_t Bytes) {
1892     DerefBytesState.takeAssumedMinimum(Bytes);
1893   }
1894 
1895   /// Equality for DerefState.
1896   bool operator==(const DerefState &R) {
1897     return this->DerefBytesState == R.DerefBytesState &&
1898            this->GlobalState == R.GlobalState;
1899   }
1900 
1901   /// Inequality for IntegerState.
1902   bool operator!=(const DerefState &R) { return !(*this == R); }
1903 
1904   /// See IntegerState::operator^=
1905   DerefState operator^=(const DerefState &R) {
1906     DerefBytesState ^= R.DerefBytesState;
1907     GlobalState ^= R.GlobalState;
1908     return *this;
1909   }
1910 
1911   /// See IntegerState::operator&=
1912   DerefState operator&=(const DerefState &R) {
1913     DerefBytesState &= R.DerefBytesState;
1914     GlobalState &= R.GlobalState;
1915     return *this;
1916   }
1917 
1918   /// See IntegerState::operator|=
1919   DerefState operator|=(const DerefState &R) {
1920     DerefBytesState |= R.DerefBytesState;
1921     GlobalState |= R.GlobalState;
1922     return *this;
1923   }
1924 };
1925 
1926 template <>
1927 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S,
1928                                                      const DerefState &R) {
1929   ChangeStatus CS0 = clampStateAndIndicateChange<IntegerState>(
1930       S.DerefBytesState, R.DerefBytesState);
1931   ChangeStatus CS1 =
1932       clampStateAndIndicateChange<IntegerState>(S.GlobalState, R.GlobalState);
1933   return CS0 | CS1;
1934 }
1935 
1936 struct AADereferenceableImpl : AADereferenceable, DerefState {
1937   AADereferenceableImpl(const IRPosition &IRP) : AADereferenceable(IRP) {}
1938   using StateType = DerefState;
1939 
1940   void initialize(Attributor &A) override {
1941     SmallVector<Attribute, 4> Attrs;
1942     getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
1943              Attrs);
1944     for (const Attribute &Attr : Attrs)
1945       takeKnownDerefBytesMaximum(Attr.getValueAsInt());
1946 
1947     NonNullAA = &A.getAAFor<AANonNull>(*this, getIRPosition());
1948   }
1949 
1950   /// See AbstractAttribute::getState()
1951   /// {
1952   StateType &getState() override { return *this; }
1953   const StateType &getState() const override { return *this; }
1954   /// }
1955 
1956   /// See AADereferenceable::getAssumedDereferenceableBytes().
1957   uint32_t getAssumedDereferenceableBytes() const override {
1958     return DerefBytesState.getAssumed();
1959   }
1960 
1961   /// See AADereferenceable::getKnownDereferenceableBytes().
1962   uint32_t getKnownDereferenceableBytes() const override {
1963     return DerefBytesState.getKnown();
1964   }
1965 
1966   /// See AADereferenceable::isAssumedGlobal().
1967   bool isAssumedGlobal() const override { return GlobalState.getAssumed(); }
1968 
1969   /// See AADereferenceable::isKnownGlobal().
1970   bool isKnownGlobal() const override { return GlobalState.getKnown(); }
1971 
1972   bool isAssumedNonNull() const override {
1973     return NonNullAA && NonNullAA->isAssumedNonNull();
1974   }
1975 
1976   void getDeducedAttributes(LLVMContext &Ctx,
1977                             SmallVectorImpl<Attribute> &Attrs) const override {
1978     // TODO: Add *_globally support
1979     if (isAssumedNonNull())
1980       Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
1981           Ctx, getAssumedDereferenceableBytes()));
1982     else
1983       Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
1984           Ctx, getAssumedDereferenceableBytes()));
1985   }
1986 
1987   /// See AbstractAttribute::getAsStr().
1988   const std::string getAsStr() const override {
1989     if (!getAssumedDereferenceableBytes())
1990       return "unknown-dereferenceable";
1991     return std::string("dereferenceable") +
1992            (isAssumedNonNull() ? "" : "_or_null") +
1993            (isAssumedGlobal() ? "_globally" : "") + "<" +
1994            std::to_string(getKnownDereferenceableBytes()) + "-" +
1995            std::to_string(getAssumedDereferenceableBytes()) + ">";
1996   }
1997 
1998 private:
1999   const AANonNull *NonNullAA = nullptr;
2000 };
2001 
2002 /// Dereferenceable attribute for a floating value.
2003 struct AADereferenceableFloating : AADereferenceableImpl {
2004   AADereferenceableFloating(const IRPosition &IRP)
2005       : AADereferenceableImpl(IRP) {}
2006 
2007   /// See AbstractAttribute::updateImpl(...).
2008   ChangeStatus updateImpl(Attributor &A) override {
2009     const DataLayout &DL = A.getDataLayout();
2010 
2011     auto VisitValueCB = [&](Value &V, DerefState &T, bool Stripped) -> bool {
2012       unsigned IdxWidth =
2013           DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
2014       APInt Offset(IdxWidth, 0);
2015       const Value *Base =
2016           V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
2017 
2018       const auto &AA =
2019           A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base));
2020       int64_t DerefBytes = 0;
2021       if (!Stripped && this == &AA) {
2022         // Use IR information if we did not strip anything.
2023         // TODO: track globally.
2024         bool CanBeNull;
2025         DerefBytes = Base->getPointerDereferenceableBytes(DL, CanBeNull);
2026         T.GlobalState.indicatePessimisticFixpoint();
2027       } else {
2028         const DerefState &DS = static_cast<const DerefState &>(AA.getState());
2029         DerefBytes = DS.DerefBytesState.getAssumed();
2030         T.GlobalState &= DS.GlobalState;
2031       }
2032 
2033       T.takeAssumedDerefBytesMinimum(
2034           std::max(int64_t(0), DerefBytes - Offset.getSExtValue()));
2035 
2036       if (!Stripped && this == &AA) {
2037         T.takeKnownDerefBytesMaximum(
2038             std::max(int64_t(0), DerefBytes - Offset.getSExtValue()));
2039         T.indicatePessimisticFixpoint();
2040       }
2041 
2042       return T.isValidState();
2043     };
2044 
2045     DerefState T;
2046     if (!genericValueTraversal<AADereferenceable, DerefState>(
2047             A, getIRPosition(), *this, T, VisitValueCB))
2048       return indicatePessimisticFixpoint();
2049 
2050     return clampStateAndIndicateChange(getState(), T);
2051   }
2052 
2053   /// See AbstractAttribute::trackStatistics()
2054   void trackStatistics() const override {
2055     STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
2056   }
2057 };
2058 
2059 /// Dereferenceable attribute for a return value.
2060 struct AADereferenceableReturned final
2061     : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl,
2062                                    DerefState> {
2063   AADereferenceableReturned(const IRPosition &IRP)
2064       : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl,
2065                                      DerefState>(IRP) {}
2066 
2067   /// See AbstractAttribute::trackStatistics()
2068   void trackStatistics() const override {
2069     STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
2070   }
2071 };
2072 
2073 /// Dereferenceable attribute for an argument
2074 struct AADereferenceableArgument final
2075     : AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl,
2076                                       DerefState> {
2077   AADereferenceableArgument(const IRPosition &IRP)
2078       : AAArgumentFromCallSiteArguments<AADereferenceable,
2079                                         AADereferenceableImpl, DerefState>(
2080             IRP) {}
2081 
2082   /// See AbstractAttribute::trackStatistics()
2083   void trackStatistics() const override{
2084     STATS_DECLTRACK_ARG_ATTR(dereferenceable)
2085   }
2086 };
2087 
2088 /// Dereferenceable attribute for a call site argument.
2089 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
2090   AADereferenceableCallSiteArgument(const IRPosition &IRP)
2091       : AADereferenceableFloating(IRP) {}
2092 
2093   /// See AbstractAttribute::trackStatistics()
2094   void trackStatistics() const override {
2095     STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
2096   }
2097 };
2098 
2099 /// Dereferenceable attribute deduction for a call site return value.
2100 using AADereferenceableCallSiteReturned = AADereferenceableReturned;
2101 
2102 // ------------------------ Align Argument Attribute ------------------------
2103 
2104 struct AAAlignImpl : AAAlign {
2105   AAAlignImpl(const IRPosition &IRP) : AAAlign(IRP) {}
2106 
2107   // Max alignemnt value allowed in IR
2108   static const unsigned MAX_ALIGN = 1U << 29;
2109 
2110   /// See AbstractAttribute::initialize(...).
2111   void initialize(Attributor &A) override {
2112     takeAssumedMinimum(MAX_ALIGN);
2113 
2114     SmallVector<Attribute, 4> Attrs;
2115     getAttrs({Attribute::Alignment}, Attrs);
2116     for (const Attribute &Attr : Attrs)
2117       takeKnownMaximum(Attr.getValueAsInt());
2118   }
2119 
2120   /// See AbstractAttribute::getDeducedAttributes
2121   virtual void
2122   getDeducedAttributes(LLVMContext &Ctx,
2123                        SmallVectorImpl<Attribute> &Attrs) const override {
2124     if (getAssumedAlign() > 1)
2125       Attrs.emplace_back(Attribute::getWithAlignment(Ctx, getAssumedAlign()));
2126   }
2127 
2128   /// See AbstractAttribute::getAsStr().
2129   const std::string getAsStr() const override {
2130     return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
2131                                 "-" + std::to_string(getAssumedAlign()) + ">")
2132                              : "unknown-align";
2133   }
2134 };
2135 
2136 /// Align attribute for a floating value.
2137 struct AAAlignFloating : AAAlignImpl {
2138   AAAlignFloating(const IRPosition &IRP) : AAAlignImpl(IRP) {}
2139 
2140   /// See AbstractAttribute::updateImpl(...).
2141   ChangeStatus updateImpl(Attributor &A) override {
2142     const DataLayout &DL = A.getDataLayout();
2143 
2144     auto VisitValueCB = [&](Value &V, AAAlign::StateType &T,
2145                             bool Stripped) -> bool {
2146       const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V));
2147       if (!Stripped && this == &AA) {
2148         // Use only IR information if we did not strip anything.
2149         T.takeKnownMaximum(V.getPointerAlignment(DL));
2150         T.indicatePessimisticFixpoint();
2151       } else {
2152         // Use abstract attribute information.
2153         const AAAlign::StateType &DS =
2154             static_cast<const AAAlign::StateType &>(AA.getState());
2155         T ^= DS;
2156       }
2157       return T.isValidState();
2158     };
2159 
2160     StateType T;
2161     if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T,
2162                                                    VisitValueCB))
2163       return indicatePessimisticFixpoint();
2164 
2165     // TODO: If we know we visited all incoming values, thus no are assumed
2166     // dead, we can take the known information from the state T.
2167     return clampStateAndIndicateChange(getState(), T);
2168   }
2169 
2170   /// See AbstractAttribute::trackStatistics()
2171   void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
2172 };
2173 
2174 /// Align attribute for function return value.
2175 struct AAAlignReturned final
2176     : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
2177   AAAlignReturned(const IRPosition &IRP)
2178       : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>(IRP) {}
2179 
2180   /// See AbstractAttribute::trackStatistics()
2181   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
2182 };
2183 
2184 /// Align attribute for function argument.
2185 struct AAAlignArgument final
2186     : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
2187   AAAlignArgument(const IRPosition &IRP)
2188       : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>(IRP) {}
2189 
2190   /// See AbstractAttribute::trackStatistics()
2191   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
2192 };
2193 
2194 struct AAAlignCallSiteArgument final : AAAlignFloating {
2195   AAAlignCallSiteArgument(const IRPosition &IRP) : AAAlignFloating(IRP) {}
2196 
2197   /// See AbstractAttribute::trackStatistics()
2198   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
2199 };
2200 
2201 /// Align attribute deduction for a call site return value.
2202 using AAAlignCallSiteReturned = AAAlignReturned;
2203 
2204 /// ------------------ Function No-Return Attribute ----------------------------
2205 struct AANoReturnImpl : public AANoReturn {
2206   AANoReturnImpl(const IRPosition &IRP) : AANoReturn(IRP) {}
2207 
2208   /// See AbstractAttribute::getAsStr().
2209   const std::string getAsStr() const override {
2210     return getAssumed() ? "noreturn" : "may-return";
2211   }
2212 
2213   /// See AbstractAttribute::initialize(...).
2214   void initialize(Attributor &A) override {
2215     if (hasAttr({getAttrKind()}))
2216       indicateOptimisticFixpoint();
2217   }
2218 
2219   /// See AbstractAttribute::updateImpl(Attributor &A).
2220   virtual ChangeStatus updateImpl(Attributor &A) override {
2221     auto CheckForNoReturn = [](Instruction &) { return false; };
2222     if (!A.checkForAllInstructions(CheckForNoReturn, *this,
2223                                    {(unsigned)Instruction::Ret}))
2224       return indicatePessimisticFixpoint();
2225     return ChangeStatus::UNCHANGED;
2226   }
2227 };
2228 
2229 struct AANoReturnFunction final : AANoReturnImpl {
2230   AANoReturnFunction(const IRPosition &IRP) : AANoReturnImpl(IRP) {}
2231 
2232   /// See AbstractAttribute::trackStatistics()
2233   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
2234 };
2235 
2236 /// NoReturn attribute deduction for a call sites.
2237 using AANoReturnCallSite = AANoReturnFunction;
2238 
2239 /// ----------------------------------------------------------------------------
2240 ///                               Attributor
2241 /// ----------------------------------------------------------------------------
2242 
2243 bool Attributor::isAssumedDead(const AbstractAttribute &AA,
2244                                const AAIsDead *LivenessAA) {
2245   const Instruction *CtxI = AA.getIRPosition().getCtxI();
2246   if (!CtxI)
2247     return false;
2248 
2249   if (!LivenessAA)
2250     LivenessAA =
2251         &getAAFor<AAIsDead>(AA, IRPosition::function(*CtxI->getFunction()));
2252   if (!LivenessAA->isAssumedDead(CtxI))
2253     return false;
2254 
2255   // TODO: Do not track dependences automatically but add it here as only a
2256   //       "is-assumed-dead" result causes a dependence.
2257   return true;
2258 }
2259 
2260 bool Attributor::checkForAllCallSites(const function_ref<bool(CallSite)> &Pred,
2261                                       const AbstractAttribute &QueryingAA,
2262                                       bool RequireAllCallSites) {
2263   // We can try to determine information from
2264   // the call sites. However, this is only possible all call sites are known,
2265   // hence the function has internal linkage.
2266   const IRPosition &IRP = QueryingAA.getIRPosition();
2267   const Function *AssociatedFunction = IRP.getAssociatedFunction();
2268   if (!AssociatedFunction)
2269     return false;
2270 
2271   if (RequireAllCallSites && !AssociatedFunction->hasInternalLinkage()) {
2272     LLVM_DEBUG(
2273         dbgs()
2274         << "[Attributor] Function " << AssociatedFunction->getName()
2275         << " has no internal linkage, hence not all call sites are known\n");
2276     return false;
2277   }
2278 
2279   for (const Use &U : AssociatedFunction->uses()) {
2280     Instruction *I = cast<Instruction>(U.getUser());
2281     Function *Caller = I->getFunction();
2282 
2283     const auto &LivenessAA =
2284         getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*Caller));
2285 
2286     // Skip dead calls.
2287     if (LivenessAA.isAssumedDead(I))
2288       continue;
2289 
2290     CallSite CS(U.getUser());
2291     if (!CS || !CS.isCallee(&U) || !CS.getCaller()->hasExactDefinition()) {
2292       if (!RequireAllCallSites)
2293         continue;
2294 
2295       LLVM_DEBUG(dbgs() << "[Attributor] User " << *U.getUser()
2296                         << " is an invalid use of "
2297                         << AssociatedFunction->getName() << "\n");
2298       return false;
2299     }
2300 
2301     if (Pred(CS))
2302       continue;
2303 
2304     LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
2305                       << *CS.getInstruction() << "\n");
2306     return false;
2307   }
2308 
2309   return true;
2310 }
2311 
2312 bool Attributor::checkForAllReturnedValuesAndReturnInsts(
2313     const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)>
2314         &Pred,
2315     const AbstractAttribute &QueryingAA) {
2316 
2317   const IRPosition &IRP = QueryingAA.getIRPosition();
2318   // Since we need to provide return instructions we have to have an exact
2319   // definition.
2320   const Function *AssociatedFunction = IRP.getAssociatedFunction();
2321   if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition())
2322     return false;
2323 
2324   // If this is a call site query we use the call site specific return values
2325   // and liveness information.
2326   const IRPosition &QueryIRP = IRPosition::function_scope(IRP);
2327   const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP);
2328   if (!AARetVal.getState().isValidState())
2329     return false;
2330 
2331   return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred);
2332 }
2333 
2334 bool Attributor::checkForAllReturnedValues(
2335     const function_ref<bool(Value &)> &Pred,
2336     const AbstractAttribute &QueryingAA) {
2337 
2338   const IRPosition &IRP = QueryingAA.getIRPosition();
2339   const Function *AssociatedFunction = IRP.getAssociatedFunction();
2340   if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition())
2341     return false;
2342 
2343   const IRPosition &QueryIRP = IRPosition::function_scope(IRP);
2344   const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP);
2345   if (!AARetVal.getState().isValidState())
2346     return false;
2347 
2348   return AARetVal.checkForAllReturnedValuesAndReturnInsts(
2349       [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &) {
2350         return Pred(RV);
2351       });
2352 }
2353 
2354 bool Attributor::checkForAllInstructions(
2355     const llvm::function_ref<bool(Instruction &)> &Pred,
2356     const AbstractAttribute &QueryingAA, const ArrayRef<unsigned> &Opcodes) {
2357 
2358   const IRPosition &IRP = QueryingAA.getIRPosition();
2359   // Since we need to provide instructions we have to have an exact definition.
2360   const Function *AssociatedFunction = IRP.getAssociatedFunction();
2361   if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition())
2362     return false;
2363 
2364   const IRPosition &QueryIRP = IRPosition::function_scope(IRP);
2365   const auto &LivenessAA = getAAFor<AAIsDead>(QueryingAA, QueryIRP);
2366 
2367   auto &OpcodeInstMap =
2368       InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction);
2369   for (unsigned Opcode : Opcodes) {
2370     for (Instruction *I : OpcodeInstMap[Opcode]) {
2371       // Skip dead instructions.
2372       if (LivenessAA.isAssumedDead(I))
2373         continue;
2374 
2375       if (!Pred(*I))
2376         return false;
2377     }
2378   }
2379 
2380   return true;
2381 }
2382 
2383 bool Attributor::checkForAllReadWriteInstructions(
2384     const llvm::function_ref<bool(Instruction &)> &Pred,
2385     AbstractAttribute &QueryingAA) {
2386 
2387   const Function *AssociatedFunction =
2388       QueryingAA.getIRPosition().getAssociatedFunction();
2389   if (!AssociatedFunction)
2390     return false;
2391 
2392   const auto &LivenessAA =
2393       getAAFor<AAIsDead>(QueryingAA, QueryingAA.getIRPosition());
2394 
2395   for (Instruction *I :
2396        InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
2397     // Skip dead instructions.
2398     if (LivenessAA.isAssumedDead(I))
2399       continue;
2400 
2401     if (!Pred(*I))
2402       return false;
2403   }
2404 
2405   return true;
2406 }
2407 
2408 ChangeStatus Attributor::run() {
2409   // Initialize all abstract attributes, allow new ones to be created.
2410   for (unsigned u = 0; u < AllAbstractAttributes.size(); u++)
2411     AllAbstractAttributes[u]->initialize(*this);
2412 
2413   LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
2414                     << AllAbstractAttributes.size()
2415                     << " abstract attributes.\n");
2416 
2417   // Now that all abstract attributes are collected and initialized we start
2418   // the abstract analysis.
2419 
2420   unsigned IterationCounter = 1;
2421 
2422   SmallVector<AbstractAttribute *, 64> ChangedAAs;
2423   SetVector<AbstractAttribute *> Worklist;
2424   Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end());
2425 
2426   do {
2427     // Remember the size to determine new attributes.
2428     size_t NumAAs = AllAbstractAttributes.size();
2429     LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
2430                       << ", Worklist size: " << Worklist.size() << "\n");
2431 
2432     // Add all abstract attributes that are potentially dependent on one that
2433     // changed to the work list.
2434     for (AbstractAttribute *ChangedAA : ChangedAAs) {
2435       auto &QuerriedAAs = QueryMap[ChangedAA];
2436       Worklist.insert(QuerriedAAs.begin(), QuerriedAAs.end());
2437     }
2438 
2439     // Reset the changed set.
2440     ChangedAAs.clear();
2441 
2442     // Update all abstract attribute in the work list and record the ones that
2443     // changed.
2444     for (AbstractAttribute *AA : Worklist)
2445       if (!isAssumedDead(*AA, nullptr))
2446         if (AA->update(*this) == ChangeStatus::CHANGED)
2447           ChangedAAs.push_back(AA);
2448 
2449     // Reset the work list and repopulate with the changed abstract attributes.
2450     // Note that dependent ones are added above.
2451     Worklist.clear();
2452     Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
2453 
2454     // Add attributes to the worklist that have been created in the last
2455     // iteration.
2456     Worklist.insert(AllAbstractAttributes.begin() + NumAAs,
2457                     AllAbstractAttributes.end());
2458 
2459   } while (!Worklist.empty() && ++IterationCounter < MaxFixpointIterations);
2460 
2461   size_t NumFinalAAs = AllAbstractAttributes.size();
2462 
2463   LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
2464                     << IterationCounter << "/" << MaxFixpointIterations
2465                     << " iterations\n");
2466 
2467   bool FinishedAtFixpoint = Worklist.empty();
2468 
2469   // Reset abstract arguments not settled in a sound fixpoint by now. This
2470   // happens when we stopped the fixpoint iteration early. Note that only the
2471   // ones marked as "changed" *and* the ones transitively depending on them
2472   // need to be reverted to a pessimistic state. Others might not be in a
2473   // fixpoint state but we can use the optimistic results for them anyway.
2474   SmallPtrSet<AbstractAttribute *, 32> Visited;
2475   for (unsigned u = 0; u < ChangedAAs.size(); u++) {
2476     AbstractAttribute *ChangedAA = ChangedAAs[u];
2477     if (!Visited.insert(ChangedAA).second)
2478       continue;
2479 
2480     AbstractState &State = ChangedAA->getState();
2481     if (!State.isAtFixpoint()) {
2482       State.indicatePessimisticFixpoint();
2483 
2484       NumAttributesTimedOut++;
2485     }
2486 
2487     auto &QuerriedAAs = QueryMap[ChangedAA];
2488     ChangedAAs.append(QuerriedAAs.begin(), QuerriedAAs.end());
2489   }
2490 
2491   LLVM_DEBUG({
2492     if (!Visited.empty())
2493       dbgs() << "\n[Attributor] Finalized " << Visited.size()
2494              << " abstract attributes.\n";
2495   });
2496 
2497   unsigned NumManifested = 0;
2498   unsigned NumAtFixpoint = 0;
2499   ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
2500   for (AbstractAttribute *AA : AllAbstractAttributes) {
2501     AbstractState &State = AA->getState();
2502 
2503     // If there is not already a fixpoint reached, we can now take the
2504     // optimistic state. This is correct because we enforced a pessimistic one
2505     // on abstract attributes that were transitively dependent on a changed one
2506     // already above.
2507     if (!State.isAtFixpoint())
2508       State.indicateOptimisticFixpoint();
2509 
2510     // If the state is invalid, we do not try to manifest it.
2511     if (!State.isValidState())
2512       continue;
2513 
2514     // Skip dead code.
2515     if (isAssumedDead(*AA, nullptr))
2516       continue;
2517     // Manifest the state and record if we changed the IR.
2518     ChangeStatus LocalChange = AA->manifest(*this);
2519     if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
2520       AA->trackStatistics();
2521 
2522     ManifestChange = ManifestChange | LocalChange;
2523 
2524     NumAtFixpoint++;
2525     NumManifested += (LocalChange == ChangeStatus::CHANGED);
2526   }
2527 
2528   (void)NumManifested;
2529   (void)NumAtFixpoint;
2530   LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
2531                     << " arguments while " << NumAtFixpoint
2532                     << " were in a valid fixpoint state\n");
2533 
2534   // If verification is requested, we finished this run at a fixpoint, and the
2535   // IR was changed, we re-run the whole fixpoint analysis, starting at
2536   // re-initialization of the arguments. This re-run should not result in an IR
2537   // change. Though, the (virtual) state of attributes at the end of the re-run
2538   // might be more optimistic than the known state or the IR state if the better
2539   // state cannot be manifested.
2540   if (VerifyAttributor && FinishedAtFixpoint &&
2541       ManifestChange == ChangeStatus::CHANGED) {
2542     VerifyAttributor = false;
2543     ChangeStatus VerifyStatus = run();
2544     if (VerifyStatus != ChangeStatus::UNCHANGED)
2545       llvm_unreachable(
2546           "Attributor verification failed, re-run did result in an IR change "
2547           "even after a fixpoint was reached in the original run. (False "
2548           "positives possible!)");
2549     VerifyAttributor = true;
2550   }
2551 
2552   NumAttributesManifested += NumManifested;
2553   NumAttributesValidFixpoint += NumAtFixpoint;
2554 
2555   (void)NumFinalAAs;
2556   assert(
2557       NumFinalAAs == AllAbstractAttributes.size() &&
2558       "Expected the final number of abstract attributes to remain unchanged!");
2559   return ManifestChange;
2560 }
2561 
2562 /// Helper function that checks if an abstract attribute of type \p AAType
2563 /// should be created for IR position \p IRP and if so creates and registers it
2564 /// with the Attributor \p A.
2565 ///
2566 /// This method will look at the provided whitelist. If one is given and the
2567 /// kind \p AAType::ID is not contained, no abstract attribute is created.
2568 ///
2569 /// \returns The created abstract argument, or nullptr if none was created.
2570 template <typename AAType>
2571 static const AAType *checkAndRegisterAA(const IRPosition &IRP, Attributor &A,
2572                                         DenseSet<const char *> *Whitelist) {
2573   if (Whitelist && !Whitelist->count(&AAType::ID))
2574     return nullptr;
2575 
2576   return &A.registerAA<AAType>(*new AAType(IRP));
2577 }
2578 
2579 void Attributor::identifyDefaultAbstractAttributes(
2580     Function &F, DenseSet<const char *> *Whitelist) {
2581 
2582   IRPosition FPos = IRPosition::function(F);
2583 
2584   // Check for dead BasicBlocks in every function.
2585   // We need dead instruction detection because we do not want to deal with
2586   // broken IR in which SSA rules do not apply.
2587   checkAndRegisterAA<AAIsDeadFunction>(FPos, *this, /* Whitelist */ nullptr);
2588 
2589   // Every function might be "will-return".
2590   checkAndRegisterAA<AAWillReturnFunction>(FPos, *this, Whitelist);
2591 
2592   // Every function can be nounwind.
2593   checkAndRegisterAA<AANoUnwindFunction>(FPos, *this, Whitelist);
2594 
2595   // Every function might be marked "nosync"
2596   checkAndRegisterAA<AANoSyncFunction>(FPos, *this, Whitelist);
2597 
2598   // Every function might be "no-free".
2599   checkAndRegisterAA<AANoFreeFunction>(FPos, *this, Whitelist);
2600 
2601   // Every function might be "no-return".
2602   checkAndRegisterAA<AANoReturnFunction>(FPos, *this, Whitelist);
2603 
2604   // Return attributes are only appropriate if the return type is non void.
2605   Type *ReturnType = F.getReturnType();
2606   if (!ReturnType->isVoidTy()) {
2607     // Argument attribute "returned" --- Create only one per function even
2608     // though it is an argument attribute.
2609     checkAndRegisterAA<AAReturnedValuesFunction>(FPos, *this, Whitelist);
2610 
2611     if (ReturnType->isPointerTy()) {
2612       IRPosition RetPos = IRPosition::returned(F);
2613 
2614       // Every function with pointer return type might be marked align.
2615       checkAndRegisterAA<AAAlignReturned>(RetPos, *this, Whitelist);
2616 
2617       // Every function with pointer return type might be marked nonnull.
2618       checkAndRegisterAA<AANonNullReturned>(RetPos, *this, Whitelist);
2619 
2620       // Every function with pointer return type might be marked noalias.
2621       checkAndRegisterAA<AANoAliasReturned>(RetPos, *this, Whitelist);
2622 
2623       // Every function with pointer return type might be marked
2624       // dereferenceable.
2625       checkAndRegisterAA<AADereferenceableReturned>(RetPos, *this, Whitelist);
2626     }
2627   }
2628 
2629   for (Argument &Arg : F.args()) {
2630     if (Arg.getType()->isPointerTy()) {
2631       IRPosition ArgPos = IRPosition::argument(Arg);
2632       // Every argument with pointer type might be marked nonnull.
2633       checkAndRegisterAA<AANonNullArgument>(ArgPos, *this, Whitelist);
2634 
2635       // Every argument with pointer type might be marked dereferenceable.
2636       checkAndRegisterAA<AADereferenceableArgument>(ArgPos, *this, Whitelist);
2637 
2638       // Every argument with pointer type might be marked align.
2639       checkAndRegisterAA<AAAlignArgument>(ArgPos, *this, Whitelist);
2640     }
2641   }
2642 
2643   // Walk all instructions to find more attribute opportunities and also
2644   // interesting instructions that might be queried by abstract attributes
2645   // during their initialization or update.
2646   auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&F];
2647   auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&F];
2648 
2649   for (Instruction &I : instructions(&F)) {
2650     bool IsInterestingOpcode = false;
2651 
2652     // To allow easy access to all instructions in a function with a given
2653     // opcode we store them in the InfoCache. As not all opcodes are interesting
2654     // to concrete attributes we only cache the ones that are as identified in
2655     // the following switch.
2656     // Note: There are no concrete attributes now so this is initially empty.
2657     switch (I.getOpcode()) {
2658     default:
2659       assert((!ImmutableCallSite(&I)) && (!isa<CallBase>(&I)) &&
2660              "New call site/base instruction type needs to be known int the "
2661              "attributor.");
2662       break;
2663     case Instruction::Call:
2664     case Instruction::CallBr:
2665     case Instruction::Invoke:
2666     case Instruction::CleanupRet:
2667     case Instruction::CatchSwitch:
2668     case Instruction::Resume:
2669     case Instruction::Ret:
2670       IsInterestingOpcode = true;
2671     }
2672     if (IsInterestingOpcode)
2673       InstOpcodeMap[I.getOpcode()].push_back(&I);
2674     if (I.mayReadOrWriteMemory())
2675       ReadOrWriteInsts.push_back(&I);
2676 
2677     CallSite CS(&I);
2678     if (CS && CS.getCalledFunction()) {
2679       for (int i = 0, e = CS.getCalledFunction()->arg_size(); i < e; i++) {
2680         if (!CS.getArgument(i)->getType()->isPointerTy())
2681           continue;
2682         IRPosition CSArgPos = IRPosition::callsite_argument(CS, i);
2683 
2684         // Call site argument attribute "non-null".
2685         checkAndRegisterAA<AANonNullCallSiteArgument>(CSArgPos, *this,
2686                                                       Whitelist);
2687 
2688         // Call site argument attribute "dereferenceable".
2689         checkAndRegisterAA<AADereferenceableCallSiteArgument>(CSArgPos, *this,
2690                                                               Whitelist);
2691 
2692         // Call site argument attribute "align".
2693         checkAndRegisterAA<AAAlignCallSiteArgument>(CSArgPos, *this, Whitelist);
2694       }
2695     }
2696   }
2697 }
2698 
2699 /// Helpers to ease debugging through output streams and print calls.
2700 ///
2701 ///{
2702 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
2703   return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
2704 }
2705 
2706 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
2707   switch (AP) {
2708   case IRPosition::IRP_INVALID:
2709     return OS << "inv";
2710   case IRPosition::IRP_FLOAT:
2711     return OS << "flt";
2712   case IRPosition::IRP_RETURNED:
2713     return OS << "fn_ret";
2714   case IRPosition::IRP_CALL_SITE_RETURNED:
2715     return OS << "cs_ret";
2716   case IRPosition::IRP_FUNCTION:
2717     return OS << "fn";
2718   case IRPosition::IRP_CALL_SITE:
2719     return OS << "cs";
2720   case IRPosition::IRP_ARGUMENT:
2721     return OS << "arg";
2722   case IRPosition::IRP_CALL_SITE_ARGUMENT:
2723     return OS << "cs_arg";
2724   }
2725   llvm_unreachable("Unknown attribute position!");
2726 }
2727 
2728 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
2729   const Value &AV = Pos.getAssociatedValue();
2730   return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
2731             << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}";
2732 }
2733 
2734 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerState &S) {
2735   return OS << "(" << S.getKnown() << "-" << S.getAssumed() << ")"
2736             << static_cast<const AbstractState &>(S);
2737 }
2738 
2739 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
2740   return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
2741 }
2742 
2743 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
2744   AA.print(OS);
2745   return OS;
2746 }
2747 
2748 void AbstractAttribute::print(raw_ostream &OS) const {
2749   OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState()
2750      << "]";
2751 }
2752 ///}
2753 
2754 /// ----------------------------------------------------------------------------
2755 ///                       Pass (Manager) Boilerplate
2756 /// ----------------------------------------------------------------------------
2757 
2758 static bool runAttributorOnModule(Module &M) {
2759   if (DisableAttributor)
2760     return false;
2761 
2762   LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << M.size()
2763                     << " functions.\n");
2764 
2765   // Create an Attributor and initially empty information cache that is filled
2766   // while we identify default attribute opportunities.
2767   InformationCache InfoCache(M.getDataLayout());
2768   Attributor A(InfoCache);
2769 
2770   for (Function &F : M) {
2771     // TODO: Not all attributes require an exact definition. Find a way to
2772     //       enable deduction for some but not all attributes in case the
2773     //       definition might be changed at runtime, see also
2774     //       http://lists.llvm.org/pipermail/llvm-dev/2018-February/121275.html.
2775     // TODO: We could always determine abstract attributes and if sufficient
2776     //       information was found we could duplicate the functions that do not
2777     //       have an exact definition.
2778     if (!F.hasExactDefinition()) {
2779       NumFnWithoutExactDefinition++;
2780       continue;
2781     }
2782 
2783     // For now we ignore naked and optnone functions.
2784     if (F.hasFnAttribute(Attribute::Naked) ||
2785         F.hasFnAttribute(Attribute::OptimizeNone))
2786       continue;
2787 
2788     NumFnWithExactDefinition++;
2789 
2790     // Populate the Attributor with abstract attribute opportunities in the
2791     // function and the information cache with IR information.
2792     A.identifyDefaultAbstractAttributes(F);
2793   }
2794 
2795   return A.run() == ChangeStatus::CHANGED;
2796 }
2797 
2798 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
2799   if (runAttributorOnModule(M)) {
2800     // FIXME: Think about passes we will preserve and add them here.
2801     return PreservedAnalyses::none();
2802   }
2803   return PreservedAnalyses::all();
2804 }
2805 
2806 namespace {
2807 
2808 struct AttributorLegacyPass : public ModulePass {
2809   static char ID;
2810 
2811   AttributorLegacyPass() : ModulePass(ID) {
2812     initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
2813   }
2814 
2815   bool runOnModule(Module &M) override {
2816     if (skipModule(M))
2817       return false;
2818     return runAttributorOnModule(M);
2819   }
2820 
2821   void getAnalysisUsage(AnalysisUsage &AU) const override {
2822     // FIXME: Think about passes we will preserve and add them here.
2823     AU.setPreservesCFG();
2824   }
2825 };
2826 
2827 } // end anonymous namespace
2828 
2829 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
2830 
2831 char AttributorLegacyPass::ID = 0;
2832 
2833 const char AAReturnedValues::ID = 0;
2834 const char AANoUnwind::ID = 0;
2835 const char AANoSync::ID = 0;
2836 const char AANoFree::ID = 0;
2837 const char AANonNull::ID = 0;
2838 const char AANoRecurse::ID = 0;
2839 const char AAWillReturn::ID = 0;
2840 const char AANoAlias::ID = 0;
2841 const char AANoReturn::ID = 0;
2842 const char AAIsDead::ID = 0;
2843 const char AADereferenceable::ID = 0;
2844 const char AAAlign::ID = 0;
2845 
2846 // Macro magic to create the static generator function for attributes that
2847 // follow the naming scheme.
2848 
2849 #define SWITCH_PK_INV(CLASS, PK, POS_NAME)                                     \
2850   case IRPosition::PK:                                                         \
2851     llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
2852 
2853 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX)                               \
2854   case IRPosition::PK:                                                         \
2855     AA = new CLASS##SUFFIX(IRP);                                               \
2856     break;
2857 
2858 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                 \
2859   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
2860     CLASS *AA = nullptr;                                                       \
2861     switch (IRP.getPositionKind()) {                                           \
2862       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
2863       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
2864       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
2865       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
2866       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
2867       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
2868       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
2869       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
2870     }                                                                          \
2871     AA->initialize(A);                                                         \
2872     return *AA;                                                                \
2873   }
2874 
2875 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                    \
2876   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
2877     CLASS *AA = nullptr;                                                       \
2878     switch (IRP.getPositionKind()) {                                           \
2879       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
2880       SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function")                           \
2881       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
2882       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
2883       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
2884       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
2885       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
2886       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
2887     }                                                                          \
2888     AA->initialize(A);                                                         \
2889     return *AA;                                                                \
2890   }
2891 
2892 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind)
2893 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync)
2894 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree)
2895 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse)
2896 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn)
2897 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn)
2898 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead)
2899 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues)
2900 
2901 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull)
2902 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias)
2903 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable)
2904 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign)
2905 
2906 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
2907 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
2908 #undef SWITCH_PK_CREATE
2909 #undef SWITCH_PK_INV
2910 
2911 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
2912                       "Deduce and propagate attributes", false, false)
2913 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
2914                     "Deduce and propagate attributes", false, false)
2915