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