OSDN Git Service

[Attributor] Deducing existing nounwind attribute.
[android-x86/external-llvm.git] / include / llvm / Transforms / IPO / Attributor.h
1 //===- Attributor.h --- Module-wide attribute deduction ---------*- C++ -*-===//
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 // Attributor: An inter procedural (abstract) "attribute" deduction framework.
10 //
11 // The Attributor framework is an inter procedural abstract analysis (fixpoint
12 // iteration analysis). The goal is to allow easy deduction of new attributes as
13 // well as information exchange between abstract attributes in-flight.
14 //
15 // The Attributor class is the driver and the link between the various abstract
16 // attributes. The Attributor will iterate until a fixpoint state is reached by
17 // all abstract attributes in-flight, or until it will enforce a pessimistic fix
18 // point because an iteration limit is reached.
19 //
20 // Abstract attributes, derived from the AbstractAttribute class, actually
21 // describe properties of the code. They can correspond to actual LLVM-IR
22 // attributes, or they can be more general, ultimately unrelated to LLVM-IR
23 // attributes. The latter is useful when an abstract attributes provides
24 // information to other abstract attributes in-flight but we might not want to
25 // manifest the information. The Attributor allows to query in-flight abstract
26 // attributes through the `Attributor::getAAFor` method (see the method
27 // description for an example). If the method is used by an abstract attribute
28 // P, and it results in an abstract attribute Q, the Attributor will
29 // automatically capture a potential dependence from Q to P. This dependence
30 // will cause P to be reevaluated whenever Q changes in the future.
31 //
32 // The Attributor will only reevaluated abstract attributes that might have
33 // changed since the last iteration. That means that the Attribute will not
34 // revisit all instructions/blocks/functions in the module but only query
35 // an update from a subset of the abstract attributes.
36 //
37 // The update method `AbstractAttribute::updateImpl` is implemented by the
38 // specific "abstract attribute" subclasses. The method is invoked whenever the
39 // currently assumed state (see the AbstractState class) might not be valid
40 // anymore. This can, for example, happen if the state was dependent on another
41 // abstract attribute that changed. In every invocation, the update method has
42 // to adjust the internal state of an abstract attribute to a point that is
43 // justifiable by the underlying IR and the current state of abstract attributes
44 // in-flight. Since the IR is given and assumed to be valid, the information
45 // derived from it can be assumed to hold. However, information derived from
46 // other abstract attributes is conditional on various things. If the justifying
47 // state changed, the `updateImpl` has to revisit the situation and potentially
48 // find another justification or limit the optimistic assumes made.
49 //
50 // Change is the key in this framework. Until a state of no-change, thus a
51 // fixpoint, is reached, the Attributor will query the abstract attributes
52 // in-flight to re-evaluate their state. If the (current) state is too
53 // optimistic, hence it cannot be justified anymore through other abstract
54 // attributes or the state of the IR, the state of the abstract attribute will
55 // have to change. Generally, we assume abstract attribute state to be a finite
56 // height lattice and the update function to be monotone. However, these
57 // conditions are not enforced because the iteration limit will guarantee
58 // termination. If an optimistic fixpoint is reached, or a pessimistic fix
59 // point is enforced after a timeout, the abstract attributes are tasked to
60 // manifest their result in the IR for passes to come.
61 //
62 // Attribute manifestation is not mandatory. If desired, there is support to
63 // generate a single LLVM-IR attribute already in the AbstractAttribute base
64 // class. In the simplest case, a subclass overloads
65 // `AbstractAttribute::getManifestPosition()` and
66 // `AbstractAttribute::getAttrKind()` to return the appropriate values. The
67 // Attributor manifestation framework will then create and place a new attribute
68 // if it is allowed to do so (based on the abstract state). Other use cases can
69 // be achieved by overloading other abstract attribute methods.
70 //
71 //
72 // The "mechanics" of adding a new "abstract attribute":
73 // - Define a class (transitively) inheriting from AbstractAttribute and one
74 //   (which could be the same) that (transitively) inherits from AbstractState.
75 //   For the latter, consider the already available BooleanState and
76 //   IntegerState if they fit your needs, e.g., you require only a bit-encoding.
77 // - Implement all pure methods. Also use overloading if the attribute is not
78 //   conforming with the "default" behavior: A (set of) LLVM-IR attribute(s) for
79 //   an argument, call site argument, function return value, or function. See
80 //   the class and method descriptions for more information on the two
81 //   "Abstract" classes and their respective methods.
82 // - Register opportunities for the new abstract attribute in the
83 //   `Attributor::identifyDefaultAbstractAttributes` method if it should be
84 //   counted as a 'default' attribute.
85 // - Add sufficient tests.
86 // - Add a Statistics object for bookkeeping. If it is a simple (set of)
87 //   attribute(s) manifested through the Attributor manifestation framework, see
88 //   the bookkeeping function in Attributor.cpp.
89 // - If instructions with a certain opcode are interesting to the attribute, add
90 //   that opcode to the switch in `Attributor::identifyAbstractAttributes`. This
91 //   will make it possible to query all those instructions through the
92 //   `InformationCache::getOpcodeInstMapForFunction` interface and eliminate the
93 //   need to traverse the IR repeatedly.
94 //
95 //===----------------------------------------------------------------------===//
96
97 #ifndef LLVM_TRANSFORMS_IPO_ATTRIBUTOR_H
98 #define LLVM_TRANSFORMS_IPO_ATTRIBUTOR_H
99
100 #include "llvm/Analysis/LazyCallGraph.h"
101 #include "llvm/IR/CallSite.h"
102 #include "llvm/IR/PassManager.h"
103
104 namespace llvm {
105
106 struct AbstractAttribute;
107 struct InformationCache;
108
109 class Function;
110
111 /// Simple enum class that forces the status to be spelled out explicitly.
112 ///
113 ///{
114 enum class ChangeStatus {
115   CHANGED,
116   UNCHANGED,
117 };
118
119 ChangeStatus operator|(ChangeStatus l, ChangeStatus r);
120 ChangeStatus operator&(ChangeStatus l, ChangeStatus r);
121 ///}
122
123 /// The fixpoint analysis framework that orchestrates the attribute deduction.
124 ///
125 /// The Attributor provides a general abstract analysis framework (guided
126 /// fixpoint iteration) as well as helper functions for the deduction of
127 /// (LLVM-IR) attributes. However, also other code properties can be deduced,
128 /// propagated, and ultimately manifested through the Attributor framework. This
129 /// is particularly useful if these properties interact with attributes and a
130 /// co-scheduled deduction allows to improve the solution. Even if not, thus if
131 /// attributes/properties are completely isolated, they should use the
132 /// Attributor framework to reduce the number of fixpoint iteration frameworks
133 /// in the code base. Note that the Attributor design makes sure that isolated
134 /// attributes are not impacted, in any way, by others derived at the same time
135 /// if there is no cross-reasoning performed.
136 ///
137 /// The public facing interface of the Attributor is kept simple and basically
138 /// allows abstract attributes to one thing, query abstract attributes
139 /// in-flight. There are two reasons to do this:
140 ///    a) The optimistic state of one abstract attribute can justify an
141 ///       optimistic state of another, allowing to framework to end up with an
142 ///       optimistic (=best possible) fixpoint instead of one based solely on
143 ///       information in the IR.
144 ///    b) This avoids reimplementing various kinds of lookups, e.g., to check
145 ///       for existing IR attributes, in favor of a single lookups interface
146 ///       provided by an abstract attribute subclass.
147 ///
148 /// NOTE: The mechanics of adding a new "concrete" abstract attribute are
149 ///       described in the file comment.
150 struct Attributor {
151   ~Attributor() { DeleteContainerPointers(AllAbstractAttributes); }
152
153   /// Run the analyses until a fixpoint is reached or enforced (timeout).
154   ///
155   /// The attributes registered with this Attributor can be used after as long
156   /// as the Attributor is not destroyed (it owns the attributes now).
157   ///
158   /// \Returns CHANGED if the IR was changed, otherwise UNCHANGED.
159   ChangeStatus run();
160
161   /// Lookup an abstract attribute of type \p AAType anchored at value \p V and
162   /// argument number \p ArgNo. If no attribute is found and \p V is a call base
163   /// instruction, the called function is tried as a value next. Thus, the
164   /// returned abstract attribute might be anchored at the callee of \p V.
165   ///
166   /// This method is the only (supported) way an abstract attribute can retrieve
167   /// information from another abstract attribute. As an example, take an
168   /// abstract attribute that determines the memory access behavior for a
169   /// argument (readnone, readonly, ...). It should use `getAAFor` to get the
170   /// most optimistic information for other abstract attributes in-flight, e.g.
171   /// the one reasoning about the "captured" state for the argument or the one
172   /// reasoning on the memory access behavior of the function as a whole.
173   template <typename AAType>
174   const AAType *getAAFor(AbstractAttribute &QueryingAA, const Value &V,
175                          int ArgNo = -1) {
176     static_assert(std::is_base_of<AbstractAttribute, AAType>::value,
177                   "Cannot query an attribute with a type not derived from "
178                   "'AbstractAttribute'!");
179     assert(AAType::ID != Attribute::None &&
180            "Cannot lookup generic abstract attributes!");
181
182     // Determine the argument number automatically for llvm::Arguments.
183     if (auto *Arg = dyn_cast<Argument>(&V))
184       ArgNo = Arg->getArgNo();
185
186     // If a function was given together with an argument number, perform the
187     // lookup for the actual argument instead. Don't do it for variadic
188     // arguments.
189     if (ArgNo >= 0 && isa<Function>(&V) &&
190         cast<Function>(&V)->arg_size() > (size_t)ArgNo)
191       return getAAFor<AAType>(
192           QueryingAA, *(cast<Function>(&V)->arg_begin() + ArgNo), ArgNo);
193
194     // Lookup the abstract attribute of type AAType. If found, return it after
195     // registering a dependence of QueryingAA on the one returned attribute.
196     const auto &KindToAbstractAttributeMap = AAMap.lookup({&V, ArgNo});
197     if (AAType *AA = static_cast<AAType *>(
198             KindToAbstractAttributeMap.lookup(AAType::ID))) {
199       QueryMap[AA].insert(&QueryingAA);
200       return AA;
201     }
202
203     // If no abstract attribute was found and we look for a call site argument,
204     // defer to the actual argument instead.
205     ImmutableCallSite ICS(&V);
206     if (ICS && ICS.getCalledValue())
207       return getAAFor<AAType>(QueryingAA, *ICS.getCalledValue(), ArgNo);
208
209     // No matching attribute found
210     return nullptr;
211   }
212
213   /// Introduce a new abstract attribute into the fixpoint analysis.
214   ///
215   /// Note that ownership of the attribute is given to the Attributor. It will
216   /// invoke delete for the Attributor on destruction of the Attributor.
217   ///
218   /// Attributes are identified by
219   ///  (1) their anchored value (see AA.getAnchoredValue()),
220   ///  (2) their argument number (\p ArgNo, or Argument::getArgNo()), and
221   ///  (3) their default attribute kind (see AAType::ID).
222   template <typename AAType> AAType &registerAA(AAType &AA, int ArgNo = -1) {
223     static_assert(std::is_base_of<AbstractAttribute, AAType>::value,
224                   "Cannot register an attribute with a type not derived from "
225                   "'AbstractAttribute'!");
226
227     // Determine the anchor value and the argument number which are used to
228     // lookup the attribute together with AAType::ID.
229     Value &AnchoredVal = AA.getAnchoredValue();
230     if (auto *Arg = dyn_cast<Argument>(&AnchoredVal))
231       ArgNo = Arg->getArgNo();
232
233     // Put the attribute in the lookup map structure and the container we use to
234     // keep track of all attributes.
235     AAMap[{&AnchoredVal, ArgNo}][AAType::ID] = &AA;
236     AllAbstractAttributes.push_back(&AA);
237     return AA;
238   }
239
240   /// Determine opportunities to derive 'default' attributes in \p F and create
241   /// abstract attribute objects for them.
242   ///
243   /// \param F The function that is checked for attribute opportunities.
244   /// \param InfoCache A cache for information queryable by the new attributes.
245   /// \param Whitelist If not null, a set limiting the attribute opportunities.
246   ///
247   /// Note that abstract attribute instances are generally created even if the
248   /// IR already contains the information they would deduce. The most important
249   /// reason for this is the single interface, the one of the abstract attribute
250   /// instance, which can be queried without the need to look at the IR in
251   /// various places.
252   void identifyDefaultAbstractAttributes(
253       Function &F, InformationCache &InfoCache,
254       DenseSet</* Attribute::AttrKind */ unsigned> *Whitelist = nullptr);
255
256 private:
257   /// The set of all abstract attributes.
258   ///{
259   using AAVector = SmallVector<AbstractAttribute *, 64>;
260   AAVector AllAbstractAttributes;
261   ///}
262
263   /// A nested map to lookup abstract attributes based on the anchored value and
264   /// an argument positions (or -1) on the outer level, and attribute kinds
265   /// (Attribute::AttrKind) on the inner level.
266   ///{
267   using KindToAbstractAttributeMap = DenseMap<unsigned, AbstractAttribute *>;
268   DenseMap<std::pair<const Value *, int>, KindToAbstractAttributeMap> AAMap;
269   ///}
270
271   /// A map from abstract attributes to the ones that queried them through calls
272   /// to the getAAFor<...>(...) method.
273   ///{
274   using QueryMapTy =
275       DenseMap<AbstractAttribute *, SetVector<AbstractAttribute *>>;
276   QueryMapTy QueryMap;
277   ///}
278 };
279
280 /// Data structure to hold cached (LLVM-IR) information.
281 ///
282 /// All attributes are given an InformationCache object at creation time to
283 /// avoid inspection of the IR by all of them individually. This default
284 /// InformationCache will hold information required by 'default' attributes,
285 /// thus the ones deduced when Attributor::identifyDefaultAbstractAttributes(..)
286 /// is called.
287 ///
288 /// If custom abstract attributes, registered manually through
289 /// Attributor::registerAA(...), need more information, especially if it is not
290 /// reusable, it is advised to inherit from the InformationCache and cast the
291 /// instance down in the abstract attributes.
292 struct InformationCache {
293   /// A map type from opcodes to instructions with this opcode.
294   using OpcodeInstMapTy = DenseMap<unsigned, SmallVector<Instruction *, 32>>;
295
296   /// Return the map that relates "interesting" opcodes with all instructions
297   /// with that opcode in \p F.
298   OpcodeInstMapTy &getOpcodeInstMapForFunction(Function &F) {
299     return FuncInstOpcodeMap[&F];
300   }
301
302   /// A vector type to hold instructions.
303   using InstructionVectorTy = std::vector<Instruction *>;
304
305   /// Return the instructions in \p F that may read or write memory.
306   InstructionVectorTy &getReadOrWriteInstsForFunction(Function &F) {
307     return FuncRWInstsMap[&F];
308   }
309
310 private:
311   /// A map type from functions to opcode to instruction maps.
312   using FuncInstOpcodeMapTy = DenseMap<Function *, OpcodeInstMapTy>;
313
314   /// A map type from functions to their read or write instructions.
315   using FuncRWInstsMapTy = DenseMap<Function *, InstructionVectorTy>;
316
317   /// A nested map that remembers all instructions in a function with a certain
318   /// instruction opcode (Instruction::getOpcode()).
319   FuncInstOpcodeMapTy FuncInstOpcodeMap;
320
321   /// A map from functions to their instructions that may read or write memory.
322   FuncRWInstsMapTy FuncRWInstsMap;
323
324   /// Give the Attributor access to the members so
325   /// Attributor::identifyDefaultAbstractAttributes(...) can initialize them.
326   friend struct Attributor;
327 };
328
329 /// An interface to query the internal state of an abstract attribute.
330 ///
331 /// The abstract state is a minimal interface that allows the Attributor to
332 /// communicate with the abstract attributes about their internal state without
333 /// enforcing or exposing implementation details, e.g., the (existence of an)
334 /// underlying lattice.
335 ///
336 /// It is sufficient to be able to query if a state is (1) valid or invalid, (2)
337 /// at a fixpoint, and to indicate to the state that (3) an optimistic fixpoint
338 /// was reached or (4) a pessimistic fixpoint was enforced.
339 ///
340 /// All methods need to be implemented by the subclass. For the common use case,
341 /// a single boolean state or a bit-encoded state, the BooleanState and
342 /// IntegerState classes are already provided. An abstract attribute can inherit
343 /// from them to get the abstract state interface and additional methods to
344 /// directly modify the state based if needed. See the class comments for help.
345 struct AbstractState {
346   virtual ~AbstractState() {}
347
348   /// Return if this abstract state is in a valid state. If false, no
349   /// information provided should be used.
350   virtual bool isValidState() const = 0;
351
352   /// Return if this abstract state is fixed, thus does not need to be updated
353   /// if information changes as it cannot change itself.
354   virtual bool isAtFixpoint() const = 0;
355
356   /// Indicate that the abstract state should converge to the optimistic state.
357   ///
358   /// This will usually make the optimistically assumed state the known to be
359   /// true state.
360   virtual void indicateOptimisticFixpoint() = 0;
361
362   /// Indicate that the abstract state should converge to the pessimistic state.
363   ///
364   /// This will usually revert the optimistically assumed state to the known to
365   /// be true state.
366   virtual void indicatePessimisticFixpoint() = 0;
367 };
368
369 /// Simple state with integers encoding.
370 ///
371 /// The interface ensures that the assumed bits are always a subset of the known
372 /// bits. Users can only add known bits and, except through adding known bits,
373 /// they can only remove assumed bits. This should guarantee monotoniticy and
374 /// thereby the existence of a fixpoint (if used corretly). The fixpoint is
375 /// reached when the assumed and known state/bits are equal. Users can
376 /// force/inidicate a fixpoint. If an optimistic one is indicated, the known
377 /// state will catch up with the assumed one, for a pessimistic fixpoint it is
378 /// the other way around.
379 struct IntegerState : public AbstractState {
380   /// Undrlying integer type, we assume 32 bits to be enough.
381   using base_t = uint32_t;
382
383   /// Initialize the (best) state.
384   IntegerState(base_t BestState = ~0) : Assumed(BestState) {}
385
386   /// Return the worst possible representable state.
387   static constexpr base_t getWorstState() { return 0; }
388
389   /// See AbstractState::isValidState()
390   /// NOTE: For now we simply pretend that the worst possible state is invalid.
391   bool isValidState() const override { return Assumed != getWorstState(); }
392
393   /// See AbstractState::isAtFixpoint()
394   bool isAtFixpoint() const override { return Assumed == Known; }
395
396   /// See AbstractState::indicateOptimisticFixpoint(...)
397   void indicateOptimisticFixpoint() override { Known = Assumed; }
398
399   /// See AbstractState::indicatePessimisticFixpoint(...)
400   void indicatePessimisticFixpoint() override { Assumed = Known; }
401
402   /// Return the known state encoding
403   base_t getKnown() const { return Known; }
404
405   /// Return the assumed state encoding.
406   base_t getAssumed() const { return Assumed; }
407
408   /// Return true if the bits set in \p BitsEncoding are "known bits".
409   bool isKnown(base_t BitsEncoding) const {
410     return (Known & BitsEncoding) == BitsEncoding;
411   }
412
413   /// Return true if the bits set in \p BitsEncoding are "assumed bits".
414   bool isAssumed(base_t BitsEncoding) const {
415     return (Assumed & BitsEncoding) == BitsEncoding;
416   }
417
418   /// Add the bits in \p BitsEncoding to the "known bits".
419   IntegerState &addKnownBits(base_t Bits) {
420     // Make sure we never miss any "known bits".
421     Assumed |= Bits;
422     Known |= Bits;
423     return *this;
424   }
425
426   /// Remove the bits in \p BitsEncoding from the "assumed bits" if not known.
427   IntegerState &removeAssumedBits(base_t BitsEncoding) {
428     // Make sure we never loose any "known bits".
429     Assumed = (Assumed & ~BitsEncoding) | Known;
430     return *this;
431   }
432
433   /// Keep only "assumed bits" also set in \p BitsEncoding but all known ones.
434   IntegerState &intersectAssumedBits(base_t BitsEncoding) {
435     // Make sure we never loose any "known bits".
436     Assumed = (Assumed & BitsEncoding) | Known;
437     return *this;
438   }
439
440 private:
441   /// The known state encoding in an integer of type base_t.
442   base_t Known = getWorstState();
443
444   /// The assumed state encoding in an integer of type base_t.
445   base_t Assumed;
446 };
447
448 /// Simple wrapper for a single bit (boolean) state.
449 struct BooleanState : public IntegerState {
450   BooleanState() : IntegerState(1){};
451 };
452
453 /// Base struct for all "concrete attribute" deductions.
454 ///
455 /// The abstract attribute is a minimal interface that allows the Attributor to
456 /// orchestrate the abstract/fixpoint analysis. The design allows to hide away
457 /// implementation choices made for the subclasses but also to structure their
458 /// implementation and simplify the use of other abstract attributes in-flight.
459 ///
460 /// To allow easy creation of new attributes, most methods have default
461 /// implementations. The ones that do not are generally straight forward, except
462 /// `AbstractAttribute::updateImpl` which is the location of most reasoning
463 /// associated with the abstract attribute. The update is invoked by the
464 /// Attributor in case the situation used to justify the current optimistic
465 /// state might have changed. The Attributor determines this automatically
466 /// by monitoring the `Attributor::getAAFor` calls made by abstract attributes.
467 ///
468 /// The `updateImpl` method should inspect the IR and other abstract attributes
469 /// in-flight to justify the best possible (=optimistic) state. The actual
470 /// implementation is, similar to the underlying abstract state encoding, not
471 /// exposed. In the most common case, the `updateImpl` will go through a list of
472 /// reasons why its optimistic state is valid given the current information. If
473 /// any combination of them holds and is sufficient to justify the current
474 /// optimistic state, the method shall return UNCHAGED. If not, the optimistic
475 /// state is adjusted to the situation and the method shall return CHANGED.
476 ///
477 /// If the manifestation of the "concrete attribute" deduced by the subclass
478 /// differs from the "default" behavior, which is a (set of) LLVM-IR
479 /// attribute(s) for an argument, call site argument, function return value, or
480 /// function, the `AbstractAttribute::manifest` method should be overloaded.
481 ///
482 /// NOTE: If the state obtained via getState() is INVALID, thus if
483 ///       AbstractAttribute::getState().isValidState() returns false, no
484 ///       information provided by the methods of this class should be used.
485 /// NOTE: The Attributor currently has certain limitations to what we can do.
486 ///       As a general rule of thumb, "concrete" abstract attributes should *for
487 ///       now* only perform "backward" information propagation. That means
488 ///       optimistic information obtained through abstract attributes should
489 ///       only be used at positions that precede the origin of the information
490 ///       with regards to the program flow. More practically, information can
491 ///       *now* be propagated from instructions to their enclosing function, but
492 ///       *not* from call sites to the called function. The mechanisms to allow
493 ///       both directions will be added in the future.
494 /// NOTE: The mechanics of adding a new "concrete" abstract attribute are
495 ///       described in the file comment.
496 struct AbstractAttribute {
497
498   /// The positions attributes can be manifested in.
499   enum ManifestPosition {
500     MP_ARGUMENT,           ///< An attribute for a function argument.
501     MP_CALL_SITE_ARGUMENT, ///< An attribute for a call site argument.
502     MP_FUNCTION,           ///< An attribute for a function as a whole.
503     MP_RETURNED,           ///< An attribute for the function return value.
504   };
505
506   /// An abstract attribute associated with \p AssociatedVal and anchored at
507   /// \p AnchoredVal.
508   ///
509   /// \param AssociatedVal The value this abstract attribute is associated with.
510   /// \param AnchoredVal The value this abstract attributes is anchored at.
511   /// \param InfoCache Cached information accessible to the abstract attribute.
512   AbstractAttribute(Value *AssociatedVal, Value &AnchoredVal,
513                     InformationCache &InfoCache)
514       : AssociatedVal(AssociatedVal), AnchoredVal(AnchoredVal),
515         InfoCache(InfoCache) {}
516
517   /// An abstract attribute associated with and anchored at \p V.
518   AbstractAttribute(Value &V, InformationCache &InfoCache)
519       : AbstractAttribute(&V, V, InfoCache) {}
520
521   /// Virtual destructor.
522   virtual ~AbstractAttribute() {}
523
524   /// Initialize the state with the information in the Attributor \p A.
525   ///
526   /// This function is called by the Attributor once all abstract attributes
527   /// have been identified. It can and shall be used for task like:
528   ///  - identify existing knowledge in the IR and use it for the "known state"
529   ///  - perform any work that is not going to change over time, e.g., determine
530   ///    a subset of the IR, or attributes in-flight, that have to be looked at
531   ///    in the `updateImpl` method.
532   virtual void initialize(Attributor &A) {}
533
534   /// Return the internal abstract state for inspection.
535   virtual const AbstractState &getState() const = 0;
536
537   /// Return the value this abstract attribute is anchored with.
538   ///
539   /// The anchored value might not be the associated value if the latter is not
540   /// sufficient to determine where arguments will be manifested. This is mostly
541   /// the case for call site arguments as the value is not sufficient to
542   /// pinpoint them. Instead, we can use the call site as an anchor.
543   ///
544   ///{
545   Value &getAnchoredValue() { return AnchoredVal; }
546   const Value &getAnchoredValue() const { return AnchoredVal; }
547   ///}
548
549   /// Return the llvm::Function surrounding the anchored value.
550   ///
551   ///{
552   Function &getAnchorScope();
553   const Function &getAnchorScope() const;
554   ///}
555
556   /// Return the value this abstract attribute is associated with.
557   ///
558   /// The abstract state usually represents this value.
559   ///
560   ///{
561   virtual Value *getAssociatedValue() { return AssociatedVal; }
562   virtual const Value *getAssociatedValue() const { return AssociatedVal; }
563   ///}
564
565   /// Return the position this abstract state is manifested in.
566   virtual ManifestPosition getManifestPosition() const = 0;
567
568   /// Return the kind that identifies the abstract attribute implementation.
569   virtual Attribute::AttrKind getAttrKind() const = 0;
570
571   /// Return the deduced attributes in \p Attrs.
572   virtual void getDeducedAttributes(SmallVectorImpl<Attribute> &Attrs) const {
573     LLVMContext &Ctx = AnchoredVal.getContext();
574     Attrs.emplace_back(Attribute::get(Ctx, getAttrKind()));
575   }
576
577   /// Helper functions, for debug purposes only.
578   ///{
579   virtual void print(raw_ostream &OS) const;
580   void dump() const { print(dbgs()); }
581
582   /// This function should return the "summarized" assumed state as string.
583   virtual const std::string getAsStr() const = 0;
584   ///}
585
586   /// Allow the Attributor access to the protected methods.
587   friend struct Attributor;
588
589 protected:
590   /// Hook for the Attributor to trigger an update of the internal state.
591   ///
592   /// If this attribute is already fixed, this method will return UNCHANGED,
593   /// otherwise it delegates to `AbstractAttribute::updateImpl`.
594   ///
595   /// \Return CHANGED if the internal state changed, otherwise UNCHANGED.
596   ChangeStatus update(Attributor &A);
597
598   /// Hook for the Attributor to trigger the manifestation of the information
599   /// represented by the abstract attribute in the LLVM-IR.
600   ///
601   /// \Return CHANGED if the IR was altered, otherwise UNCHANGED.
602   virtual ChangeStatus manifest(Attributor &A);
603
604   /// Return the internal abstract state for careful modification.
605   virtual AbstractState &getState() = 0;
606
607   /// The actual update/transfer function which has to be implemented by the
608   /// derived classes.
609   ///
610   /// If it is called, the environment has changed and we have to determine if
611   /// the current information is still valid or adjust it otherwise.
612   ///
613   /// \Return CHANGED if the internal state changed, otherwise UNCHANGED.
614   virtual ChangeStatus updateImpl(Attributor &A) = 0;
615
616   /// The value this abstract attribute is associated with.
617   Value *AssociatedVal;
618
619   /// The value this abstract attribute is anchored at.
620   Value &AnchoredVal;
621
622   /// The information cache accessible to this abstract attribute.
623   InformationCache &InfoCache;
624 };
625
626 /// Forward declarations of output streams for debug purposes.
627 ///
628 ///{
629 raw_ostream &operator<<(raw_ostream &OS, const AbstractAttribute &AA);
630 raw_ostream &operator<<(raw_ostream &OS, ChangeStatus S);
631 raw_ostream &operator<<(raw_ostream &OS, AbstractAttribute::ManifestPosition);
632 raw_ostream &operator<<(raw_ostream &OS, const AbstractState &State);
633 ///}
634
635 struct AttributorPass : public PassInfoMixin<AttributorPass> {
636   PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
637 };
638
639 Pass *createAttributorLegacyPass();
640
641 /// ----------------------------------------------------------------------------
642 ///                       Abstract Attribute Classes
643 /// ----------------------------------------------------------------------------
644
645 struct AANoUnwind : public AbstractAttribute {
646     /// An abstract interface for all nosync attributes.
647     AANoUnwind(Value &V, InformationCache &InfoCache)
648         : AbstractAttribute(V, InfoCache) {}
649
650     /// See AbstractAttribute::getAttrKind()/
651     virtual Attribute::AttrKind getAttrKind() const override { return ID; }
652
653     static constexpr Attribute::AttrKind ID = Attribute::NoUnwind;
654
655     /// Returns true if nounwind is assumed.
656     virtual bool isAssumedNoUnwind() const = 0;
657
658     /// Returns true if nounwind is known.
659     virtual bool isKnownNoUnwind() const = 0;
660 };
661
662 } // end namespace llvm
663
664 #endif // LLVM_TRANSFORMS_IPO_FUNCTIONATTRS_H