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