1 //===- TargetTransformInfo.h ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This pass exposes codegen information to IR-level passes. Every
11 /// transformation that uses codegen information is broken into three parts:
12 /// 1. The IR-level analysis pass.
13 /// 2. The IR-level transformation interface which provides the needed
14 ///    information.
15 /// 3. Codegen-level implementation which uses target-specific hooks.
16 ///
17 /// This file defines #2, which is the interface that IR-level transformations
18 /// use for querying the codegen.
19 ///
20 //===----------------------------------------------------------------------===//
21 
22 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
23 #define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
24 
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/DataTypes.h"
30 #include <functional>
31 
32 namespace llvm {
33 
34 class Function;
35 class GlobalValue;
36 class Loop;
37 class PreservedAnalyses;
38 class Type;
39 class User;
40 class Value;
41 
42 /// \brief Information about a load/store intrinsic defined by the target.
43 struct MemIntrinsicInfo {
MemIntrinsicInfoMemIntrinsicInfo44   MemIntrinsicInfo()
45       : ReadMem(false), WriteMem(false), IsSimple(false), MatchingId(0),
46         NumMemRefs(0), PtrVal(nullptr) {}
47   bool ReadMem;
48   bool WriteMem;
49   /// True only if this memory operation is non-volatile, non-atomic, and
50   /// unordered.  (See LoadInst/StoreInst for details on each)
51   bool IsSimple;
52   // Same Id is set by the target for corresponding load/store intrinsics.
53   unsigned short MatchingId;
54   int NumMemRefs;
55   Value *PtrVal;
56 };
57 
58 /// \brief This pass provides access to the codegen interfaces that are needed
59 /// for IR-level transformations.
60 class TargetTransformInfo {
61 public:
62   /// \brief Construct a TTI object using a type implementing the \c Concept
63   /// API below.
64   ///
65   /// This is used by targets to construct a TTI wrapping their target-specific
66   /// implementaion that encodes appropriate costs for their target.
67   template <typename T> TargetTransformInfo(T Impl);
68 
69   /// \brief Construct a baseline TTI object using a minimal implementation of
70   /// the \c Concept API below.
71   ///
72   /// The TTI implementation will reflect the information in the DataLayout
73   /// provided if non-null.
74   explicit TargetTransformInfo(const DataLayout &DL);
75 
76   // Provide move semantics.
77   TargetTransformInfo(TargetTransformInfo &&Arg);
78   TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
79 
80   // We need to define the destructor out-of-line to define our sub-classes
81   // out-of-line.
82   ~TargetTransformInfo();
83 
84   /// \brief Handle the invalidation of this information.
85   ///
86   /// When used as a result of \c TargetIRAnalysis this method will be called
87   /// when the function this was computed for changes. When it returns false,
88   /// the information is preserved across those changes.
invalidate(Function &,const PreservedAnalyses &)89   bool invalidate(Function &, const PreservedAnalyses &) {
90     // FIXME: We should probably in some way ensure that the subtarget
91     // information for a function hasn't changed.
92     return false;
93   }
94 
95   /// \name Generic Target Information
96   /// @{
97 
98   /// \brief Underlying constants for 'cost' values in this interface.
99   ///
100   /// Many APIs in this interface return a cost. This enum defines the
101   /// fundamental values that should be used to interpret (and produce) those
102   /// costs. The costs are returned as an int rather than a member of this
103   /// enumeration because it is expected that the cost of one IR instruction
104   /// may have a multiplicative factor to it or otherwise won't fit directly
105   /// into the enum. Moreover, it is common to sum or average costs which works
106   /// better as simple integral values. Thus this enum only provides constants.
107   /// Also note that the returned costs are signed integers to make it natural
108   /// to add, subtract, and test with zero (a common boundary condition). It is
109   /// not expected that 2^32 is a realistic cost to be modeling at any point.
110   ///
111   /// Note that these costs should usually reflect the intersection of code-size
112   /// cost and execution cost. A free instruction is typically one that folds
113   /// into another instruction. For example, reg-to-reg moves can often be
114   /// skipped by renaming the registers in the CPU, but they still are encoded
115   /// and thus wouldn't be considered 'free' here.
116   enum TargetCostConstants {
117     TCC_Free = 0,     ///< Expected to fold away in lowering.
118     TCC_Basic = 1,    ///< The cost of a typical 'add' instruction.
119     TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
120   };
121 
122   /// \brief Estimate the cost of a specific operation when lowered.
123   ///
124   /// Note that this is designed to work on an arbitrary synthetic opcode, and
125   /// thus work for hypothetical queries before an instruction has even been
126   /// formed. However, this does *not* work for GEPs, and must not be called
127   /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
128   /// analyzing a GEP's cost required more information.
129   ///
130   /// Typically only the result type is required, and the operand type can be
131   /// omitted. However, if the opcode is one of the cast instructions, the
132   /// operand type is required.
133   ///
134   /// The returned cost is defined in terms of \c TargetCostConstants, see its
135   /// comments for a detailed explanation of the cost values.
136   int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy = nullptr) const;
137 
138   /// \brief Estimate the cost of a GEP operation when lowered.
139   ///
140   /// The contract for this function is the same as \c getOperationCost except
141   /// that it supports an interface that provides extra information specific to
142   /// the GEP operation.
143   int getGEPCost(Type *PointeeType, const Value *Ptr,
144                  ArrayRef<const Value *> Operands) const;
145 
146   /// \brief Estimate the cost of a function call when lowered.
147   ///
148   /// The contract for this is the same as \c getOperationCost except that it
149   /// supports an interface that provides extra information specific to call
150   /// instructions.
151   ///
152   /// This is the most basic query for estimating call cost: it only knows the
153   /// function type and (potentially) the number of arguments at the call site.
154   /// The latter is only interesting for varargs function types.
155   int getCallCost(FunctionType *FTy, int NumArgs = -1) const;
156 
157   /// \brief Estimate the cost of calling a specific function when lowered.
158   ///
159   /// This overload adds the ability to reason about the particular function
160   /// being called in the event it is a library call with special lowering.
161   int getCallCost(const Function *F, int NumArgs = -1) const;
162 
163   /// \brief Estimate the cost of calling a specific function when lowered.
164   ///
165   /// This overload allows specifying a set of candidate argument values.
166   int getCallCost(const Function *F, ArrayRef<const Value *> Arguments) const;
167 
168   /// \brief Estimate the cost of an intrinsic when lowered.
169   ///
170   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
171   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
172                        ArrayRef<Type *> ParamTys) const;
173 
174   /// \brief Estimate the cost of an intrinsic when lowered.
175   ///
176   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
177   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
178                        ArrayRef<const Value *> Arguments) const;
179 
180   /// \brief Estimate the cost of a given IR user when lowered.
181   ///
182   /// This can estimate the cost of either a ConstantExpr or Instruction when
183   /// lowered. It has two primary advantages over the \c getOperationCost and
184   /// \c getGEPCost above, and one significant disadvantage: it can only be
185   /// used when the IR construct has already been formed.
186   ///
187   /// The advantages are that it can inspect the SSA use graph to reason more
188   /// accurately about the cost. For example, all-constant-GEPs can often be
189   /// folded into a load or other instruction, but if they are used in some
190   /// other context they may not be folded. This routine can distinguish such
191   /// cases.
192   ///
193   /// The returned cost is defined in terms of \c TargetCostConstants, see its
194   /// comments for a detailed explanation of the cost values.
195   int getUserCost(const User *U) const;
196 
197   /// \brief Return true if branch divergence exists.
198   ///
199   /// Branch divergence has a significantly negative impact on GPU performance
200   /// when threads in the same wavefront take different paths due to conditional
201   /// branches.
202   bool hasBranchDivergence() const;
203 
204   /// \brief Returns whether V is a source of divergence.
205   ///
206   /// This function provides the target-dependent information for
207   /// the target-independent DivergenceAnalysis. DivergenceAnalysis first
208   /// builds the dependency graph, and then runs the reachability algorithm
209   /// starting with the sources of divergence.
210   bool isSourceOfDivergence(const Value *V) const;
211 
212   /// \brief Test whether calls to a function lower to actual program function
213   /// calls.
214   ///
215   /// The idea is to test whether the program is likely to require a 'call'
216   /// instruction or equivalent in order to call the given function.
217   ///
218   /// FIXME: It's not clear that this is a good or useful query API. Client's
219   /// should probably move to simpler cost metrics using the above.
220   /// Alternatively, we could split the cost interface into distinct code-size
221   /// and execution-speed costs. This would allow modelling the core of this
222   /// query more accurately as a call is a single small instruction, but
223   /// incurs significant execution cost.
224   bool isLoweredToCall(const Function *F) const;
225 
226   /// Parameters that control the generic loop unrolling transformation.
227   struct UnrollingPreferences {
228     /// The cost threshold for the unrolled loop. Should be relative to the
229     /// getUserCost values returned by this API, and the expectation is that
230     /// the unrolled loop's instructions when run through that interface should
231     /// not exceed this cost. However, this is only an estimate. Also, specific
232     /// loops may be unrolled even with a cost above this threshold if deemed
233     /// profitable. Set this to UINT_MAX to disable the loop body cost
234     /// restriction.
235     unsigned Threshold;
236     /// If complete unrolling will reduce the cost of the loop below its
237     /// expected dynamic cost while rolled by this percentage, apply a discount
238     /// (below) to its unrolled cost.
239     unsigned PercentDynamicCostSavedThreshold;
240     /// The discount applied to the unrolled cost when the *dynamic* cost
241     /// savings of unrolling exceed the \c PercentDynamicCostSavedThreshold.
242     unsigned DynamicCostSavingsDiscount;
243     /// The cost threshold for the unrolled loop when optimizing for size (set
244     /// to UINT_MAX to disable).
245     unsigned OptSizeThreshold;
246     /// The cost threshold for the unrolled loop, like Threshold, but used
247     /// for partial/runtime unrolling (set to UINT_MAX to disable).
248     unsigned PartialThreshold;
249     /// The cost threshold for the unrolled loop when optimizing for size, like
250     /// OptSizeThreshold, but used for partial/runtime unrolling (set to
251     /// UINT_MAX to disable).
252     unsigned PartialOptSizeThreshold;
253     /// A forced unrolling factor (the number of concatenated bodies of the
254     /// original loop in the unrolled loop body). When set to 0, the unrolling
255     /// transformation will select an unrolling factor based on the current cost
256     /// threshold and other factors.
257     unsigned Count;
258     // Set the maximum unrolling factor. The unrolling factor may be selected
259     // using the appropriate cost threshold, but may not exceed this number
260     // (set to UINT_MAX to disable). This does not apply in cases where the
261     // loop is being fully unrolled.
262     unsigned MaxCount;
263     /// Allow partial unrolling (unrolling of loops to expand the size of the
264     /// loop body, not only to eliminate small constant-trip-count loops).
265     bool Partial;
266     /// Allow runtime unrolling (unrolling of loops to expand the size of the
267     /// loop body even when the number of loop iterations is not known at
268     /// compile time).
269     bool Runtime;
270     /// Allow emitting expensive instructions (such as divisions) when computing
271     /// the trip count of a loop for runtime unrolling.
272     bool AllowExpensiveTripCount;
273   };
274 
275   /// \brief Get target-customized preferences for the generic loop unrolling
276   /// transformation. The caller will initialize UP with the current
277   /// target-independent defaults.
278   void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) const;
279 
280   /// @}
281 
282   /// \name Scalar Target Information
283   /// @{
284 
285   /// \brief Flags indicating the kind of support for population count.
286   ///
287   /// Compared to the SW implementation, HW support is supposed to
288   /// significantly boost the performance when the population is dense, and it
289   /// may or may not degrade performance if the population is sparse. A HW
290   /// support is considered as "Fast" if it can outperform, or is on a par
291   /// with, SW implementation when the population is sparse; otherwise, it is
292   /// considered as "Slow".
293   enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
294 
295   /// \brief Return true if the specified immediate is legal add immediate, that
296   /// is the target has add instructions which can add a register with the
297   /// immediate without having to materialize the immediate into a register.
298   bool isLegalAddImmediate(int64_t Imm) const;
299 
300   /// \brief Return true if the specified immediate is legal icmp immediate,
301   /// that is the target has icmp instructions which can compare a register
302   /// against the immediate without having to materialize the immediate into a
303   /// register.
304   bool isLegalICmpImmediate(int64_t Imm) const;
305 
306   /// \brief Return true if the addressing mode represented by AM is legal for
307   /// this target, for a load/store of the specified type.
308   /// The type may be VoidTy, in which case only return true if the addressing
309   /// mode is legal for a load/store of any legal type.
310   /// TODO: Handle pre/postinc as well.
311   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
312                              bool HasBaseReg, int64_t Scale,
313                              unsigned AddrSpace = 0) const;
314 
315   /// \brief Return true if the target supports masked load/store
316   /// AVX2 and AVX-512 targets allow masks for consecutive load and store for
317   /// 32 and 64 bit elements.
318   bool isLegalMaskedStore(Type *DataType) const;
319   bool isLegalMaskedLoad(Type *DataType) const;
320 
321   /// \brief Return true if the target supports masked gather/scatter
322   /// AVX-512 fully supports gather and scatter for vectors with 32 and 64
323   /// bits scalar type.
324   bool isLegalMaskedScatter(Type *DataType) const;
325   bool isLegalMaskedGather(Type *DataType) const;
326 
327   /// \brief Return the cost of the scaling factor used in the addressing
328   /// mode represented by AM for this target, for a load/store
329   /// of the specified type.
330   /// If the AM is supported, the return value must be >= 0.
331   /// If the AM is not supported, it returns a negative value.
332   /// TODO: Handle pre/postinc as well.
333   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
334                            bool HasBaseReg, int64_t Scale,
335                            unsigned AddrSpace = 0) const;
336 
337   /// \brief Return true if it's free to truncate a value of type Ty1 to type
338   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
339   /// by referencing its sub-register AX.
340   bool isTruncateFree(Type *Ty1, Type *Ty2) const;
341 
342   /// \brief Return true if it is profitable to hoist instruction in the
343   /// then/else to before if.
344   bool isProfitableToHoist(Instruction *I) const;
345 
346   /// \brief Return true if this type is legal.
347   bool isTypeLegal(Type *Ty) const;
348 
349   /// \brief Returns the target's jmp_buf alignment in bytes.
350   unsigned getJumpBufAlignment() const;
351 
352   /// \brief Returns the target's jmp_buf size in bytes.
353   unsigned getJumpBufSize() const;
354 
355   /// \brief Return true if switches should be turned into lookup tables for the
356   /// target.
357   bool shouldBuildLookupTables() const;
358 
359   /// \brief Don't restrict interleaved unrolling to small loops.
360   bool enableAggressiveInterleaving(bool LoopHasReductions) const;
361 
362   /// \brief Enable matching of interleaved access groups.
363   bool enableInterleavedAccessVectorization() const;
364 
365   /// \brief Return hardware support for population count.
366   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
367 
368   /// \brief Return true if the hardware has a fast square-root instruction.
369   bool haveFastSqrt(Type *Ty) const;
370 
371   /// \brief Return the expected cost of supporting the floating point operation
372   /// of the specified type.
373   int getFPOpCost(Type *Ty) const;
374 
375   /// \brief Return the expected cost of materializing for the given integer
376   /// immediate of the specified type.
377   int getIntImmCost(const APInt &Imm, Type *Ty) const;
378 
379   /// \brief Return the expected cost of materialization for the given integer
380   /// immediate of the specified type for a given instruction. The cost can be
381   /// zero if the immediate can be folded into the specified instruction.
382   int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
383                     Type *Ty) const;
384   int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
385                     Type *Ty) const;
386   /// @}
387 
388   /// \name Vector Target Information
389   /// @{
390 
391   /// \brief The various kinds of shuffle patterns for vector queries.
392   enum ShuffleKind {
393     SK_Broadcast,       ///< Broadcast element 0 to all other elements.
394     SK_Reverse,         ///< Reverse the order of the vector.
395     SK_Alternate,       ///< Choose alternate elements from vector.
396     SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
397     SK_ExtractSubvector ///< ExtractSubvector Index indicates start offset.
398   };
399 
400   /// \brief Additional information about an operand's possible values.
401   enum OperandValueKind {
402     OK_AnyValue,               // Operand can have any value.
403     OK_UniformValue,           // Operand is uniform (splat of a value).
404     OK_UniformConstantValue,   // Operand is uniform constant.
405     OK_NonUniformConstantValue // Operand is a non uniform constant value.
406   };
407 
408   /// \brief Additional properties of an operand's values.
409   enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
410 
411   /// \return The number of scalar or vector registers that the target has.
412   /// If 'Vectors' is true, it returns the number of vector registers. If it is
413   /// set to false, it returns the number of scalar registers.
414   unsigned getNumberOfRegisters(bool Vector) const;
415 
416   /// \return The width of the largest scalar or vector register type.
417   unsigned getRegisterBitWidth(bool Vector) const;
418 
419   /// \return The maximum interleave factor that any transform should try to
420   /// perform for this target. This number depends on the level of parallelism
421   /// and the number of execution units in the CPU.
422   unsigned getMaxInterleaveFactor(unsigned VF) const;
423 
424   /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
425   int getArithmeticInstrCost(
426       unsigned Opcode, Type *Ty, OperandValueKind Opd1Info = OK_AnyValue,
427       OperandValueKind Opd2Info = OK_AnyValue,
428       OperandValueProperties Opd1PropInfo = OP_None,
429       OperandValueProperties Opd2PropInfo = OP_None) const;
430 
431   /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
432   /// The index and subtype parameters are used by the subvector insertion and
433   /// extraction shuffle kinds.
434   int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
435                      Type *SubTp = nullptr) const;
436 
437   /// \return The expected cost of cast instructions, such as bitcast, trunc,
438   /// zext, etc.
439   int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) const;
440 
441   /// \return The expected cost of control-flow related instructions such as
442   /// Phi, Ret, Br.
443   int getCFInstrCost(unsigned Opcode) const;
444 
445   /// \returns The expected cost of compare and select instructions.
446   int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
447                          Type *CondTy = nullptr) const;
448 
449   /// \return The expected cost of vector Insert and Extract.
450   /// Use -1 to indicate that there is no information on the index value.
451   int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index = -1) const;
452 
453   /// \return The cost of Load and Store instructions.
454   int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
455                       unsigned AddressSpace) const;
456 
457   /// \return The cost of masked Load and Store instructions.
458   int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
459                             unsigned AddressSpace) const;
460 
461   /// \return The cost of the interleaved memory operation.
462   /// \p Opcode is the memory operation code
463   /// \p VecTy is the vector type of the interleaved access.
464   /// \p Factor is the interleave factor
465   /// \p Indices is the indices for interleaved load members (as interleaved
466   ///    load allows gaps)
467   /// \p Alignment is the alignment of the memory operation
468   /// \p AddressSpace is address space of the pointer.
469   int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
470                                  ArrayRef<unsigned> Indices, unsigned Alignment,
471                                  unsigned AddressSpace) const;
472 
473   /// \brief Calculate the cost of performing a vector reduction.
474   ///
475   /// This is the cost of reducing the vector value of type \p Ty to a scalar
476   /// value using the operation denoted by \p Opcode. The form of the reduction
477   /// can either be a pairwise reduction or a reduction that splits the vector
478   /// at every reduction level.
479   ///
480   /// Pairwise:
481   ///  (v0, v1, v2, v3)
482   ///  ((v0+v1), (v2, v3), undef, undef)
483   /// Split:
484   ///  (v0, v1, v2, v3)
485   ///  ((v0+v2), (v1+v3), undef, undef)
486   int getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwiseForm) const;
487 
488   /// \returns The cost of Intrinsic instructions.
489   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
490                             ArrayRef<Type *> Tys) const;
491 
492   /// \returns The cost of Call instructions.
493   int getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) const;
494 
495   /// \returns The number of pieces into which the provided type must be
496   /// split during legalization. Zero is returned when the answer is unknown.
497   unsigned getNumberOfParts(Type *Tp) const;
498 
499   /// \returns The cost of the address computation. For most targets this can be
500   /// merged into the instruction indexing mode. Some targets might want to
501   /// distinguish between address computation for memory operations on vector
502   /// types and scalar types. Such targets should override this function.
503   /// The 'IsComplex' parameter is a hint that the address computation is likely
504   /// to involve multiple instructions and as such unlikely to be merged into
505   /// the address indexing mode.
506   int getAddressComputationCost(Type *Ty, bool IsComplex = false) const;
507 
508   /// \returns The cost, if any, of keeping values of the given types alive
509   /// over a callsite.
510   ///
511   /// Some types may require the use of register classes that do not have
512   /// any callee-saved registers, so would require a spill and fill.
513   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
514 
515   /// \returns True if the intrinsic is a supported memory intrinsic.  Info
516   /// will contain additional information - whether the intrinsic may write
517   /// or read to memory, volatility and the pointer.  Info is undefined
518   /// if false is returned.
519   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
520 
521   /// \returns A value which is the result of the given memory intrinsic.  New
522   /// instructions may be created to extract the result from the given intrinsic
523   /// memory operation.  Returns nullptr if the target cannot create a result
524   /// from the given intrinsic.
525   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
526                                            Type *ExpectedType) const;
527 
528   /// \returns True if the two functions have compatible attributes for inlining
529   /// purposes.
530   bool areInlineCompatible(const Function *Caller,
531                            const Function *Callee) const;
532 
533   /// @}
534 
535 private:
536   /// \brief The abstract base class used to type erase specific TTI
537   /// implementations.
538   class Concept;
539 
540   /// \brief The template model for the base class which wraps a concrete
541   /// implementation in a type erased interface.
542   template <typename T> class Model;
543 
544   std::unique_ptr<Concept> TTIImpl;
545 };
546 
547 class TargetTransformInfo::Concept {
548 public:
549   virtual ~Concept() = 0;
550   virtual const DataLayout &getDataLayout() const = 0;
551   virtual int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) = 0;
552   virtual int getGEPCost(Type *PointeeType, const Value *Ptr,
553                          ArrayRef<const Value *> Operands) = 0;
554   virtual int getCallCost(FunctionType *FTy, int NumArgs) = 0;
555   virtual int getCallCost(const Function *F, int NumArgs) = 0;
556   virtual int getCallCost(const Function *F,
557                           ArrayRef<const Value *> Arguments) = 0;
558   virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
559                                ArrayRef<Type *> ParamTys) = 0;
560   virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
561                                ArrayRef<const Value *> Arguments) = 0;
562   virtual int getUserCost(const User *U) = 0;
563   virtual bool hasBranchDivergence() = 0;
564   virtual bool isSourceOfDivergence(const Value *V) = 0;
565   virtual bool isLoweredToCall(const Function *F) = 0;
566   virtual void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) = 0;
567   virtual bool isLegalAddImmediate(int64_t Imm) = 0;
568   virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
569   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
570                                      int64_t BaseOffset, bool HasBaseReg,
571                                      int64_t Scale,
572                                      unsigned AddrSpace) = 0;
573   virtual bool isLegalMaskedStore(Type *DataType) = 0;
574   virtual bool isLegalMaskedLoad(Type *DataType) = 0;
575   virtual bool isLegalMaskedScatter(Type *DataType) = 0;
576   virtual bool isLegalMaskedGather(Type *DataType) = 0;
577   virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
578                                    int64_t BaseOffset, bool HasBaseReg,
579                                    int64_t Scale, unsigned AddrSpace) = 0;
580   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
581   virtual bool isProfitableToHoist(Instruction *I) = 0;
582   virtual bool isTypeLegal(Type *Ty) = 0;
583   virtual unsigned getJumpBufAlignment() = 0;
584   virtual unsigned getJumpBufSize() = 0;
585   virtual bool shouldBuildLookupTables() = 0;
586   virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
587   virtual bool enableInterleavedAccessVectorization() = 0;
588   virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
589   virtual bool haveFastSqrt(Type *Ty) = 0;
590   virtual int getFPOpCost(Type *Ty) = 0;
591   virtual int getIntImmCost(const APInt &Imm, Type *Ty) = 0;
592   virtual int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
593                             Type *Ty) = 0;
594   virtual int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
595                             Type *Ty) = 0;
596   virtual unsigned getNumberOfRegisters(bool Vector) = 0;
597   virtual unsigned getRegisterBitWidth(bool Vector) = 0;
598   virtual unsigned getMaxInterleaveFactor(unsigned VF) = 0;
599   virtual unsigned
600   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
601                          OperandValueKind Opd2Info,
602                          OperandValueProperties Opd1PropInfo,
603                          OperandValueProperties Opd2PropInfo) = 0;
604   virtual int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
605                              Type *SubTp) = 0;
606   virtual int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) = 0;
607   virtual int getCFInstrCost(unsigned Opcode) = 0;
608   virtual int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
609                                  Type *CondTy) = 0;
610   virtual int getVectorInstrCost(unsigned Opcode, Type *Val,
611                                  unsigned Index) = 0;
612   virtual int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
613                               unsigned AddressSpace) = 0;
614   virtual int getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
615                                     unsigned Alignment,
616                                     unsigned AddressSpace) = 0;
617   virtual int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
618                                          unsigned Factor,
619                                          ArrayRef<unsigned> Indices,
620                                          unsigned Alignment,
621                                          unsigned AddressSpace) = 0;
622   virtual int getReductionCost(unsigned Opcode, Type *Ty,
623                                bool IsPairwiseForm) = 0;
624   virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
625                                     ArrayRef<Type *> Tys) = 0;
626   virtual int getCallInstrCost(Function *F, Type *RetTy,
627                                ArrayRef<Type *> Tys) = 0;
628   virtual unsigned getNumberOfParts(Type *Tp) = 0;
629   virtual int getAddressComputationCost(Type *Ty, bool IsComplex) = 0;
630   virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
631   virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
632                                   MemIntrinsicInfo &Info) = 0;
633   virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
634                                                    Type *ExpectedType) = 0;
635   virtual bool areInlineCompatible(const Function *Caller,
636                                    const Function *Callee) const = 0;
637 };
638 
639 template <typename T>
640 class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
641   T Impl;
642 
643 public:
Model(T Impl)644   Model(T Impl) : Impl(std::move(Impl)) {}
~Model()645   ~Model() override {}
646 
getDataLayout()647   const DataLayout &getDataLayout() const override {
648     return Impl.getDataLayout();
649   }
650 
getOperationCost(unsigned Opcode,Type * Ty,Type * OpTy)651   int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) override {
652     return Impl.getOperationCost(Opcode, Ty, OpTy);
653   }
getGEPCost(Type * PointeeType,const Value * Ptr,ArrayRef<const Value * > Operands)654   int getGEPCost(Type *PointeeType, const Value *Ptr,
655                  ArrayRef<const Value *> Operands) override {
656     return Impl.getGEPCost(PointeeType, Ptr, Operands);
657   }
getCallCost(FunctionType * FTy,int NumArgs)658   int getCallCost(FunctionType *FTy, int NumArgs) override {
659     return Impl.getCallCost(FTy, NumArgs);
660   }
getCallCost(const Function * F,int NumArgs)661   int getCallCost(const Function *F, int NumArgs) override {
662     return Impl.getCallCost(F, NumArgs);
663   }
getCallCost(const Function * F,ArrayRef<const Value * > Arguments)664   int getCallCost(const Function *F,
665                   ArrayRef<const Value *> Arguments) override {
666     return Impl.getCallCost(F, Arguments);
667   }
getIntrinsicCost(Intrinsic::ID IID,Type * RetTy,ArrayRef<Type * > ParamTys)668   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
669                        ArrayRef<Type *> ParamTys) override {
670     return Impl.getIntrinsicCost(IID, RetTy, ParamTys);
671   }
getIntrinsicCost(Intrinsic::ID IID,Type * RetTy,ArrayRef<const Value * > Arguments)672   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
673                        ArrayRef<const Value *> Arguments) override {
674     return Impl.getIntrinsicCost(IID, RetTy, Arguments);
675   }
getUserCost(const User * U)676   int getUserCost(const User *U) override { return Impl.getUserCost(U); }
hasBranchDivergence()677   bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
isSourceOfDivergence(const Value * V)678   bool isSourceOfDivergence(const Value *V) override {
679     return Impl.isSourceOfDivergence(V);
680   }
isLoweredToCall(const Function * F)681   bool isLoweredToCall(const Function *F) override {
682     return Impl.isLoweredToCall(F);
683   }
getUnrollingPreferences(Loop * L,UnrollingPreferences & UP)684   void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) override {
685     return Impl.getUnrollingPreferences(L, UP);
686   }
isLegalAddImmediate(int64_t Imm)687   bool isLegalAddImmediate(int64_t Imm) override {
688     return Impl.isLegalAddImmediate(Imm);
689   }
isLegalICmpImmediate(int64_t Imm)690   bool isLegalICmpImmediate(int64_t Imm) override {
691     return Impl.isLegalICmpImmediate(Imm);
692   }
isLegalAddressingMode(Type * Ty,GlobalValue * BaseGV,int64_t BaseOffset,bool HasBaseReg,int64_t Scale,unsigned AddrSpace)693   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
694                              bool HasBaseReg, int64_t Scale,
695                              unsigned AddrSpace) override {
696     return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
697                                       Scale, AddrSpace);
698   }
isLegalMaskedStore(Type * DataType)699   bool isLegalMaskedStore(Type *DataType) override {
700     return Impl.isLegalMaskedStore(DataType);
701   }
isLegalMaskedLoad(Type * DataType)702   bool isLegalMaskedLoad(Type *DataType) override {
703     return Impl.isLegalMaskedLoad(DataType);
704   }
isLegalMaskedScatter(Type * DataType)705   bool isLegalMaskedScatter(Type *DataType) override {
706     return Impl.isLegalMaskedScatter(DataType);
707   }
isLegalMaskedGather(Type * DataType)708   bool isLegalMaskedGather(Type *DataType) override {
709     return Impl.isLegalMaskedGather(DataType);
710   }
getScalingFactorCost(Type * Ty,GlobalValue * BaseGV,int64_t BaseOffset,bool HasBaseReg,int64_t Scale,unsigned AddrSpace)711   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
712                            bool HasBaseReg, int64_t Scale,
713                            unsigned AddrSpace) override {
714     return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg,
715                                      Scale, AddrSpace);
716   }
isTruncateFree(Type * Ty1,Type * Ty2)717   bool isTruncateFree(Type *Ty1, Type *Ty2) override {
718     return Impl.isTruncateFree(Ty1, Ty2);
719   }
isProfitableToHoist(Instruction * I)720   bool isProfitableToHoist(Instruction *I) override {
721     return Impl.isProfitableToHoist(I);
722   }
isTypeLegal(Type * Ty)723   bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
getJumpBufAlignment()724   unsigned getJumpBufAlignment() override { return Impl.getJumpBufAlignment(); }
getJumpBufSize()725   unsigned getJumpBufSize() override { return Impl.getJumpBufSize(); }
shouldBuildLookupTables()726   bool shouldBuildLookupTables() override {
727     return Impl.shouldBuildLookupTables();
728   }
enableAggressiveInterleaving(bool LoopHasReductions)729   bool enableAggressiveInterleaving(bool LoopHasReductions) override {
730     return Impl.enableAggressiveInterleaving(LoopHasReductions);
731   }
enableInterleavedAccessVectorization()732   bool enableInterleavedAccessVectorization() override {
733     return Impl.enableInterleavedAccessVectorization();
734   }
getPopcntSupport(unsigned IntTyWidthInBit)735   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
736     return Impl.getPopcntSupport(IntTyWidthInBit);
737   }
haveFastSqrt(Type * Ty)738   bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
739 
getFPOpCost(Type * Ty)740   int getFPOpCost(Type *Ty) override { return Impl.getFPOpCost(Ty); }
741 
getIntImmCost(const APInt & Imm,Type * Ty)742   int getIntImmCost(const APInt &Imm, Type *Ty) override {
743     return Impl.getIntImmCost(Imm, Ty);
744   }
getIntImmCost(unsigned Opc,unsigned Idx,const APInt & Imm,Type * Ty)745   int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
746                     Type *Ty) override {
747     return Impl.getIntImmCost(Opc, Idx, Imm, Ty);
748   }
getIntImmCost(Intrinsic::ID IID,unsigned Idx,const APInt & Imm,Type * Ty)749   int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
750                     Type *Ty) override {
751     return Impl.getIntImmCost(IID, Idx, Imm, Ty);
752   }
getNumberOfRegisters(bool Vector)753   unsigned getNumberOfRegisters(bool Vector) override {
754     return Impl.getNumberOfRegisters(Vector);
755   }
getRegisterBitWidth(bool Vector)756   unsigned getRegisterBitWidth(bool Vector) override {
757     return Impl.getRegisterBitWidth(Vector);
758   }
getMaxInterleaveFactor(unsigned VF)759   unsigned getMaxInterleaveFactor(unsigned VF) override {
760     return Impl.getMaxInterleaveFactor(VF);
761   }
762   unsigned
getArithmeticInstrCost(unsigned Opcode,Type * Ty,OperandValueKind Opd1Info,OperandValueKind Opd2Info,OperandValueProperties Opd1PropInfo,OperandValueProperties Opd2PropInfo)763   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
764                          OperandValueKind Opd2Info,
765                          OperandValueProperties Opd1PropInfo,
766                          OperandValueProperties Opd2PropInfo) override {
767     return Impl.getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
768                                        Opd1PropInfo, Opd2PropInfo);
769   }
getShuffleCost(ShuffleKind Kind,Type * Tp,int Index,Type * SubTp)770   int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
771                      Type *SubTp) override {
772     return Impl.getShuffleCost(Kind, Tp, Index, SubTp);
773   }
getCastInstrCost(unsigned Opcode,Type * Dst,Type * Src)774   int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) override {
775     return Impl.getCastInstrCost(Opcode, Dst, Src);
776   }
getCFInstrCost(unsigned Opcode)777   int getCFInstrCost(unsigned Opcode) override {
778     return Impl.getCFInstrCost(Opcode);
779   }
getCmpSelInstrCost(unsigned Opcode,Type * ValTy,Type * CondTy)780   int getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) override {
781     return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy);
782   }
getVectorInstrCost(unsigned Opcode,Type * Val,unsigned Index)783   int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) override {
784     return Impl.getVectorInstrCost(Opcode, Val, Index);
785   }
getMemoryOpCost(unsigned Opcode,Type * Src,unsigned Alignment,unsigned AddressSpace)786   int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
787                       unsigned AddressSpace) override {
788     return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
789   }
getMaskedMemoryOpCost(unsigned Opcode,Type * Src,unsigned Alignment,unsigned AddressSpace)790   int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
791                             unsigned AddressSpace) override {
792     return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
793   }
getInterleavedMemoryOpCost(unsigned Opcode,Type * VecTy,unsigned Factor,ArrayRef<unsigned> Indices,unsigned Alignment,unsigned AddressSpace)794   int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
795                                  ArrayRef<unsigned> Indices, unsigned Alignment,
796                                  unsigned AddressSpace) override {
797     return Impl.getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
798                                            Alignment, AddressSpace);
799   }
getReductionCost(unsigned Opcode,Type * Ty,bool IsPairwiseForm)800   int getReductionCost(unsigned Opcode, Type *Ty,
801                        bool IsPairwiseForm) override {
802     return Impl.getReductionCost(Opcode, Ty, IsPairwiseForm);
803   }
getIntrinsicInstrCost(Intrinsic::ID ID,Type * RetTy,ArrayRef<Type * > Tys)804   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
805                             ArrayRef<Type *> Tys) override {
806     return Impl.getIntrinsicInstrCost(ID, RetTy, Tys);
807   }
getCallInstrCost(Function * F,Type * RetTy,ArrayRef<Type * > Tys)808   int getCallInstrCost(Function *F, Type *RetTy,
809                        ArrayRef<Type *> Tys) override {
810     return Impl.getCallInstrCost(F, RetTy, Tys);
811   }
getNumberOfParts(Type * Tp)812   unsigned getNumberOfParts(Type *Tp) override {
813     return Impl.getNumberOfParts(Tp);
814   }
getAddressComputationCost(Type * Ty,bool IsComplex)815   int getAddressComputationCost(Type *Ty, bool IsComplex) override {
816     return Impl.getAddressComputationCost(Ty, IsComplex);
817   }
getCostOfKeepingLiveOverCall(ArrayRef<Type * > Tys)818   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
819     return Impl.getCostOfKeepingLiveOverCall(Tys);
820   }
getTgtMemIntrinsic(IntrinsicInst * Inst,MemIntrinsicInfo & Info)821   bool getTgtMemIntrinsic(IntrinsicInst *Inst,
822                           MemIntrinsicInfo &Info) override {
823     return Impl.getTgtMemIntrinsic(Inst, Info);
824   }
getOrCreateResultFromMemIntrinsic(IntrinsicInst * Inst,Type * ExpectedType)825   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
826                                            Type *ExpectedType) override {
827     return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
828   }
areInlineCompatible(const Function * Caller,const Function * Callee)829   bool areInlineCompatible(const Function *Caller,
830                            const Function *Callee) const override {
831     return Impl.areInlineCompatible(Caller, Callee);
832   }
833 };
834 
835 template <typename T>
TargetTransformInfo(T Impl)836 TargetTransformInfo::TargetTransformInfo(T Impl)
837     : TTIImpl(new Model<T>(Impl)) {}
838 
839 /// \brief Analysis pass providing the \c TargetTransformInfo.
840 ///
841 /// The core idea of the TargetIRAnalysis is to expose an interface through
842 /// which LLVM targets can analyze and provide information about the middle
843 /// end's target-independent IR. This supports use cases such as target-aware
844 /// cost modeling of IR constructs.
845 ///
846 /// This is a function analysis because much of the cost modeling for targets
847 /// is done in a subtarget specific way and LLVM supports compiling different
848 /// functions targeting different subtargets in order to support runtime
849 /// dispatch according to the observed subtarget.
850 class TargetIRAnalysis {
851 public:
852   typedef TargetTransformInfo Result;
853 
854   /// \brief Opaque, unique identifier for this analysis pass.
ID()855   static void *ID() { return (void *)&PassID; }
856 
857   /// \brief Provide access to a name for this pass for debugging purposes.
name()858   static StringRef name() { return "TargetIRAnalysis"; }
859 
860   /// \brief Default construct a target IR analysis.
861   ///
862   /// This will use the module's datalayout to construct a baseline
863   /// conservative TTI result.
864   TargetIRAnalysis();
865 
866   /// \brief Construct an IR analysis pass around a target-provide callback.
867   ///
868   /// The callback will be called with a particular function for which the TTI
869   /// is needed and must return a TTI object for that function.
870   TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
871 
872   // Value semantics. We spell out the constructors for MSVC.
TargetIRAnalysis(const TargetIRAnalysis & Arg)873   TargetIRAnalysis(const TargetIRAnalysis &Arg)
874       : TTICallback(Arg.TTICallback) {}
TargetIRAnalysis(TargetIRAnalysis && Arg)875   TargetIRAnalysis(TargetIRAnalysis &&Arg)
876       : TTICallback(std::move(Arg.TTICallback)) {}
877   TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
878     TTICallback = RHS.TTICallback;
879     return *this;
880   }
881   TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
882     TTICallback = std::move(RHS.TTICallback);
883     return *this;
884   }
885 
886   Result run(const Function &F);
887 
888 private:
889   static char PassID;
890 
891   /// \brief The callback used to produce a result.
892   ///
893   /// We use a completely opaque callback so that targets can provide whatever
894   /// mechanism they desire for constructing the TTI for a given function.
895   ///
896   /// FIXME: Should we really use std::function? It's relatively inefficient.
897   /// It might be possible to arrange for even stateful callbacks to outlive
898   /// the analysis and thus use a function_ref which would be lighter weight.
899   /// This may also be less error prone as the callback is likely to reference
900   /// the external TargetMachine, and that reference needs to never dangle.
901   std::function<Result(const Function &)> TTICallback;
902 
903   /// \brief Helper function used as the callback in the default constructor.
904   static Result getDefaultTTI(const Function &F);
905 };
906 
907 /// \brief Wrapper pass for TargetTransformInfo.
908 ///
909 /// This pass can be constructed from a TTI object which it stores internally
910 /// and is queried by passes.
911 class TargetTransformInfoWrapperPass : public ImmutablePass {
912   TargetIRAnalysis TIRA;
913   Optional<TargetTransformInfo> TTI;
914 
915   virtual void anchor();
916 
917 public:
918   static char ID;
919 
920   /// \brief We must provide a default constructor for the pass but it should
921   /// never be used.
922   ///
923   /// Use the constructor below or call one of the creation routines.
924   TargetTransformInfoWrapperPass();
925 
926   explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
927 
928   TargetTransformInfo &getTTI(const Function &F);
929 };
930 
931 /// \brief Create an analysis pass wrapper around a TTI object.
932 ///
933 /// This analysis pass just holds the TTI instance and makes it available to
934 /// clients.
935 ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
936 
937 } // End llvm namespace
938 
939 #endif
940