]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/TargetTransformInfo.h
Merge lldb trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/IR/Operator.h"
29 #include "llvm/IR/PassManager.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/DataTypes.h"
32 #include <functional>
33
34 namespace llvm {
35
36 class Function;
37 class GlobalValue;
38 class Loop;
39 class ScalarEvolution;
40 class SCEV;
41 class Type;
42 class User;
43 class Value;
44
45 /// \brief Information about a load/store intrinsic defined by the target.
46 struct MemIntrinsicInfo {
47   /// This is the pointer that the intrinsic is loading from or storing to.
48   /// If this is non-null, then analysis/optimization passes can assume that
49   /// this intrinsic is functionally equivalent to a load/store from this
50   /// pointer.
51   Value *PtrVal = nullptr;
52
53   // Ordering for atomic operations.
54   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
55
56   // Same Id is set by the target for corresponding load/store intrinsics.
57   unsigned short MatchingId = 0;
58
59   bool ReadMem = false;
60   bool WriteMem = false;
61   bool IsVolatile = false;
62
63   bool isUnordered() const {
64     return (Ordering == AtomicOrdering::NotAtomic ||
65             Ordering == AtomicOrdering::Unordered) && !IsVolatile;
66   }
67 };
68
69 /// \brief This pass provides access to the codegen interfaces that are needed
70 /// for IR-level transformations.
71 class TargetTransformInfo {
72 public:
73   /// \brief Construct a TTI object using a type implementing the \c Concept
74   /// API below.
75   ///
76   /// This is used by targets to construct a TTI wrapping their target-specific
77   /// implementaion that encodes appropriate costs for their target.
78   template <typename T> TargetTransformInfo(T Impl);
79
80   /// \brief Construct a baseline TTI object using a minimal implementation of
81   /// the \c Concept API below.
82   ///
83   /// The TTI implementation will reflect the information in the DataLayout
84   /// provided if non-null.
85   explicit TargetTransformInfo(const DataLayout &DL);
86
87   // Provide move semantics.
88   TargetTransformInfo(TargetTransformInfo &&Arg);
89   TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
90
91   // We need to define the destructor out-of-line to define our sub-classes
92   // out-of-line.
93   ~TargetTransformInfo();
94
95   /// \brief Handle the invalidation of this information.
96   ///
97   /// When used as a result of \c TargetIRAnalysis this method will be called
98   /// when the function this was computed for changes. When it returns false,
99   /// the information is preserved across those changes.
100   bool invalidate(Function &, const PreservedAnalyses &,
101                   FunctionAnalysisManager::Invalidator &) {
102     // FIXME: We should probably in some way ensure that the subtarget
103     // information for a function hasn't changed.
104     return false;
105   }
106
107   /// \name Generic Target Information
108   /// @{
109
110   /// \brief Underlying constants for 'cost' values in this interface.
111   ///
112   /// Many APIs in this interface return a cost. This enum defines the
113   /// fundamental values that should be used to interpret (and produce) those
114   /// costs. The costs are returned as an int rather than a member of this
115   /// enumeration because it is expected that the cost of one IR instruction
116   /// may have a multiplicative factor to it or otherwise won't fit directly
117   /// into the enum. Moreover, it is common to sum or average costs which works
118   /// better as simple integral values. Thus this enum only provides constants.
119   /// Also note that the returned costs are signed integers to make it natural
120   /// to add, subtract, and test with zero (a common boundary condition). It is
121   /// not expected that 2^32 is a realistic cost to be modeling at any point.
122   ///
123   /// Note that these costs should usually reflect the intersection of code-size
124   /// cost and execution cost. A free instruction is typically one that folds
125   /// into another instruction. For example, reg-to-reg moves can often be
126   /// skipped by renaming the registers in the CPU, but they still are encoded
127   /// and thus wouldn't be considered 'free' here.
128   enum TargetCostConstants {
129     TCC_Free = 0,     ///< Expected to fold away in lowering.
130     TCC_Basic = 1,    ///< The cost of a typical 'add' instruction.
131     TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
132   };
133
134   /// \brief Estimate the cost of a specific operation when lowered.
135   ///
136   /// Note that this is designed to work on an arbitrary synthetic opcode, and
137   /// thus work for hypothetical queries before an instruction has even been
138   /// formed. However, this does *not* work for GEPs, and must not be called
139   /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
140   /// analyzing a GEP's cost required more information.
141   ///
142   /// Typically only the result type is required, and the operand type can be
143   /// omitted. However, if the opcode is one of the cast instructions, the
144   /// operand type is required.
145   ///
146   /// The returned cost is defined in terms of \c TargetCostConstants, see its
147   /// comments for a detailed explanation of the cost values.
148   int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy = nullptr) const;
149
150   /// \brief Estimate the cost of a GEP operation when lowered.
151   ///
152   /// The contract for this function is the same as \c getOperationCost except
153   /// that it supports an interface that provides extra information specific to
154   /// the GEP operation.
155   int getGEPCost(Type *PointeeType, const Value *Ptr,
156                  ArrayRef<const Value *> Operands) const;
157
158   /// \brief Estimate the cost of a function call when lowered.
159   ///
160   /// The contract for this is the same as \c getOperationCost except that it
161   /// supports an interface that provides extra information specific to call
162   /// instructions.
163   ///
164   /// This is the most basic query for estimating call cost: it only knows the
165   /// function type and (potentially) the number of arguments at the call site.
166   /// The latter is only interesting for varargs function types.
167   int getCallCost(FunctionType *FTy, int NumArgs = -1) const;
168
169   /// \brief Estimate the cost of calling a specific function when lowered.
170   ///
171   /// This overload adds the ability to reason about the particular function
172   /// being called in the event it is a library call with special lowering.
173   int getCallCost(const Function *F, int NumArgs = -1) const;
174
175   /// \brief Estimate the cost of calling a specific function when lowered.
176   ///
177   /// This overload allows specifying a set of candidate argument values.
178   int getCallCost(const Function *F, ArrayRef<const Value *> Arguments) const;
179
180   /// \returns A value by which our inlining threshold should be multiplied.
181   /// This is primarily used to bump up the inlining threshold wholesale on
182   /// targets where calls are unusually expensive.
183   ///
184   /// TODO: This is a rather blunt instrument.  Perhaps altering the costs of
185   /// individual classes of instructions would be better.
186   unsigned getInliningThresholdMultiplier() const;
187
188   /// \brief Estimate the cost of an intrinsic when lowered.
189   ///
190   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
191   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
192                        ArrayRef<Type *> ParamTys) const;
193
194   /// \brief Estimate the cost of an intrinsic when lowered.
195   ///
196   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
197   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
198                        ArrayRef<const Value *> Arguments) const;
199
200   /// \brief Estimate the cost of a given IR user when lowered.
201   ///
202   /// This can estimate the cost of either a ConstantExpr or Instruction when
203   /// lowered. It has two primary advantages over the \c getOperationCost and
204   /// \c getGEPCost above, and one significant disadvantage: it can only be
205   /// used when the IR construct has already been formed.
206   ///
207   /// The advantages are that it can inspect the SSA use graph to reason more
208   /// accurately about the cost. For example, all-constant-GEPs can often be
209   /// folded into a load or other instruction, but if they are used in some
210   /// other context they may not be folded. This routine can distinguish such
211   /// cases.
212   ///
213   /// The returned cost is defined in terms of \c TargetCostConstants, see its
214   /// comments for a detailed explanation of the cost values.
215   int getUserCost(const User *U) const;
216
217   /// \brief Return true if branch divergence exists.
218   ///
219   /// Branch divergence has a significantly negative impact on GPU performance
220   /// when threads in the same wavefront take different paths due to conditional
221   /// branches.
222   bool hasBranchDivergence() const;
223
224   /// \brief Returns whether V is a source of divergence.
225   ///
226   /// This function provides the target-dependent information for
227   /// the target-independent DivergenceAnalysis. DivergenceAnalysis first
228   /// builds the dependency graph, and then runs the reachability algorithm
229   /// starting with the sources of divergence.
230   bool isSourceOfDivergence(const Value *V) const;
231
232   /// Returns the address space ID for a target's 'flat' address space. Note
233   /// this is not necessarily the same as addrspace(0), which LLVM sometimes
234   /// refers to as the generic address space. The flat address space is a
235   /// generic address space that can be used access multiple segments of memory
236   /// with different address spaces. Access of a memory location through a
237   /// pointer with this address space is expected to be legal but slower
238   /// compared to the same memory location accessed through a pointer with a
239   /// different address space.
240   //
241   /// This is for for targets with different pointer representations which can
242   /// be converted with the addrspacecast instruction. If a pointer is converted
243   /// to this address space, optimizations should attempt to replace the access
244   /// with the source address space.
245   ///
246   /// \returns ~0u if the target does not have such a flat address space to
247   /// optimize away.
248   unsigned getFlatAddressSpace() const;
249
250   /// \brief Test whether calls to a function lower to actual program function
251   /// calls.
252   ///
253   /// The idea is to test whether the program is likely to require a 'call'
254   /// instruction or equivalent in order to call the given function.
255   ///
256   /// FIXME: It's not clear that this is a good or useful query API. Client's
257   /// should probably move to simpler cost metrics using the above.
258   /// Alternatively, we could split the cost interface into distinct code-size
259   /// and execution-speed costs. This would allow modelling the core of this
260   /// query more accurately as a call is a single small instruction, but
261   /// incurs significant execution cost.
262   bool isLoweredToCall(const Function *F) const;
263
264   /// Parameters that control the generic loop unrolling transformation.
265   struct UnrollingPreferences {
266     /// The cost threshold for the unrolled loop. Should be relative to the
267     /// getUserCost values returned by this API, and the expectation is that
268     /// the unrolled loop's instructions when run through that interface should
269     /// not exceed this cost. However, this is only an estimate. Also, specific
270     /// loops may be unrolled even with a cost above this threshold if deemed
271     /// profitable. Set this to UINT_MAX to disable the loop body cost
272     /// restriction.
273     unsigned Threshold;
274     /// If complete unrolling will reduce the cost of the loop, we will boost
275     /// the Threshold by a certain percent to allow more aggressive complete
276     /// unrolling. This value provides the maximum boost percentage that we
277     /// can apply to Threshold (The value should be no less than 100).
278     /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
279     ///                                    MaxPercentThresholdBoost / 100)
280     /// E.g. if complete unrolling reduces the loop execution time by 50%
281     /// then we boost the threshold by the factor of 2x. If unrolling is not
282     /// expected to reduce the running time, then we do not increase the
283     /// threshold.
284     unsigned MaxPercentThresholdBoost;
285     /// The cost threshold for the unrolled loop when optimizing for size (set
286     /// to UINT_MAX to disable).
287     unsigned OptSizeThreshold;
288     /// The cost threshold for the unrolled loop, like Threshold, but used
289     /// for partial/runtime unrolling (set to UINT_MAX to disable).
290     unsigned PartialThreshold;
291     /// The cost threshold for the unrolled loop when optimizing for size, like
292     /// OptSizeThreshold, but used for partial/runtime unrolling (set to
293     /// UINT_MAX to disable).
294     unsigned PartialOptSizeThreshold;
295     /// A forced unrolling factor (the number of concatenated bodies of the
296     /// original loop in the unrolled loop body). When set to 0, the unrolling
297     /// transformation will select an unrolling factor based on the current cost
298     /// threshold and other factors.
299     unsigned Count;
300     /// A forced peeling factor (the number of bodied of the original loop
301     /// that should be peeled off before the loop body). When set to 0, the
302     /// unrolling transformation will select a peeling factor based on profile
303     /// information and other factors.
304     unsigned PeelCount;
305     /// Default unroll count for loops with run-time trip count.
306     unsigned DefaultUnrollRuntimeCount;
307     // Set the maximum unrolling factor. The unrolling factor may be selected
308     // using the appropriate cost threshold, but may not exceed this number
309     // (set to UINT_MAX to disable). This does not apply in cases where the
310     // loop is being fully unrolled.
311     unsigned MaxCount;
312     /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
313     /// applies even if full unrolling is selected. This allows a target to fall
314     /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
315     unsigned FullUnrollMaxCount;
316     // Represents number of instructions optimized when "back edge"
317     // becomes "fall through" in unrolled loop.
318     // For now we count a conditional branch on a backedge and a comparison
319     // feeding it.
320     unsigned BEInsns;
321     /// Allow partial unrolling (unrolling of loops to expand the size of the
322     /// loop body, not only to eliminate small constant-trip-count loops).
323     bool Partial;
324     /// Allow runtime unrolling (unrolling of loops to expand the size of the
325     /// loop body even when the number of loop iterations is not known at
326     /// compile time).
327     bool Runtime;
328     /// Allow generation of a loop remainder (extra iterations after unroll).
329     bool AllowRemainder;
330     /// Allow emitting expensive instructions (such as divisions) when computing
331     /// the trip count of a loop for runtime unrolling.
332     bool AllowExpensiveTripCount;
333     /// Apply loop unroll on any kind of loop
334     /// (mainly to loops that fail runtime unrolling).
335     bool Force;
336     /// Allow using trip count upper bound to unroll loops.
337     bool UpperBound;
338     /// Allow peeling off loop iterations for loops with low dynamic tripcount.
339     bool AllowPeeling;
340   };
341
342   /// \brief Get target-customized preferences for the generic loop unrolling
343   /// transformation. The caller will initialize UP with the current
344   /// target-independent defaults.
345   void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) const;
346
347   /// @}
348
349   /// \name Scalar Target Information
350   /// @{
351
352   /// \brief Flags indicating the kind of support for population count.
353   ///
354   /// Compared to the SW implementation, HW support is supposed to
355   /// significantly boost the performance when the population is dense, and it
356   /// may or may not degrade performance if the population is sparse. A HW
357   /// support is considered as "Fast" if it can outperform, or is on a par
358   /// with, SW implementation when the population is sparse; otherwise, it is
359   /// considered as "Slow".
360   enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
361
362   /// \brief Return true if the specified immediate is legal add immediate, that
363   /// is the target has add instructions which can add a register with the
364   /// immediate without having to materialize the immediate into a register.
365   bool isLegalAddImmediate(int64_t Imm) const;
366
367   /// \brief Return true if the specified immediate is legal icmp immediate,
368   /// that is the target has icmp instructions which can compare a register
369   /// against the immediate without having to materialize the immediate into a
370   /// register.
371   bool isLegalICmpImmediate(int64_t Imm) const;
372
373   /// \brief Return true if the addressing mode represented by AM is legal for
374   /// this target, for a load/store of the specified type.
375   /// The type may be VoidTy, in which case only return true if the addressing
376   /// mode is legal for a load/store of any legal type.
377   /// TODO: Handle pre/postinc as well.
378   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
379                              bool HasBaseReg, int64_t Scale,
380                              unsigned AddrSpace = 0) const;
381
382   /// \brief Return true if the target supports masked load/store
383   /// AVX2 and AVX-512 targets allow masks for consecutive load and store
384   bool isLegalMaskedStore(Type *DataType) const;
385   bool isLegalMaskedLoad(Type *DataType) const;
386
387   /// \brief Return true if the target supports masked gather/scatter
388   /// AVX-512 fully supports gather and scatter for vectors with 32 and 64
389   /// bits scalar type.
390   bool isLegalMaskedScatter(Type *DataType) const;
391   bool isLegalMaskedGather(Type *DataType) const;
392
393   /// \brief Return the cost of the scaling factor used in the addressing
394   /// mode represented by AM for this target, for a load/store
395   /// of the specified type.
396   /// If the AM is supported, the return value must be >= 0.
397   /// If the AM is not supported, it returns a negative value.
398   /// TODO: Handle pre/postinc as well.
399   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
400                            bool HasBaseReg, int64_t Scale,
401                            unsigned AddrSpace = 0) const;
402
403   /// \brief Return true if target supports the load / store
404   /// instruction with the given Offset on the form reg + Offset. It
405   /// may be that Offset is too big for a certain type (register
406   /// class).
407   bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) const;
408   
409   /// \brief Return true if it's free to truncate a value of type Ty1 to type
410   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
411   /// by referencing its sub-register AX.
412   bool isTruncateFree(Type *Ty1, Type *Ty2) const;
413
414   /// \brief Return true if it is profitable to hoist instruction in the
415   /// then/else to before if.
416   bool isProfitableToHoist(Instruction *I) const;
417
418   /// \brief Return true if this type is legal.
419   bool isTypeLegal(Type *Ty) const;
420
421   /// \brief Returns the target's jmp_buf alignment in bytes.
422   unsigned getJumpBufAlignment() const;
423
424   /// \brief Returns the target's jmp_buf size in bytes.
425   unsigned getJumpBufSize() const;
426
427   /// \brief Return true if switches should be turned into lookup tables for the
428   /// target.
429   bool shouldBuildLookupTables() const;
430
431   /// \brief Return true if switches should be turned into lookup tables
432   /// containing this constant value for the target.
433   bool shouldBuildLookupTablesForConstant(Constant *C) const;
434
435   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
436
437   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
438                                             unsigned VF) const;
439
440   /// If target has efficient vector element load/store instructions, it can
441   /// return true here so that insertion/extraction costs are not added to
442   /// the scalarization cost of a load/store.
443   bool supportsEfficientVectorElementLoadStore() const;
444
445   /// \brief Don't restrict interleaved unrolling to small loops.
446   bool enableAggressiveInterleaving(bool LoopHasReductions) const;
447
448   /// \brief Enable matching of interleaved access groups.
449   bool enableInterleavedAccessVectorization() const;
450
451   /// \brief Indicate that it is potentially unsafe to automatically vectorize
452   /// floating-point operations because the semantics of vector and scalar
453   /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
454   /// does not support IEEE-754 denormal numbers, while depending on the
455   /// platform, scalar floating-point math does.
456   /// This applies to floating-point math operations and calls, not memory
457   /// operations, shuffles, or casts.
458   bool isFPVectorizationPotentiallyUnsafe() const;
459
460   /// \brief Determine if the target supports unaligned memory accesses.
461   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
462                                       unsigned BitWidth, unsigned AddressSpace = 0,
463                                       unsigned Alignment = 1,
464                                       bool *Fast = nullptr) const;
465
466   /// \brief Return hardware support for population count.
467   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
468
469   /// \brief Return true if the hardware has a fast square-root instruction.
470   bool haveFastSqrt(Type *Ty) const;
471
472   /// \brief Return the expected cost of supporting the floating point operation
473   /// of the specified type.
474   int getFPOpCost(Type *Ty) const;
475
476   /// \brief Return the expected cost of materializing for the given integer
477   /// immediate of the specified type.
478   int getIntImmCost(const APInt &Imm, Type *Ty) const;
479
480   /// \brief Return the expected cost of materialization for the given integer
481   /// immediate of the specified type for a given instruction. The cost can be
482   /// zero if the immediate can be folded into the specified instruction.
483   int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
484                     Type *Ty) const;
485   int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
486                     Type *Ty) const;
487
488   /// \brief Return the expected cost for the given integer when optimising
489   /// for size. This is different than the other integer immediate cost
490   /// functions in that it is subtarget agnostic. This is useful when you e.g.
491   /// target one ISA such as Aarch32 but smaller encodings could be possible
492   /// with another such as Thumb. This return value is used as a penalty when
493   /// the total costs for a constant is calculated (the bigger the cost, the
494   /// more beneficial constant hoisting is).
495   int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
496                             Type *Ty) const;
497   /// @}
498
499   /// \name Vector Target Information
500   /// @{
501
502   /// \brief The various kinds of shuffle patterns for vector queries.
503   enum ShuffleKind {
504     SK_Broadcast,       ///< Broadcast element 0 to all other elements.
505     SK_Reverse,         ///< Reverse the order of the vector.
506     SK_Alternate,       ///< Choose alternate elements from vector.
507     SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
508     SK_ExtractSubvector,///< ExtractSubvector Index indicates start offset.
509     SK_PermuteTwoSrc,   ///< Merge elements from two source vectors into one
510                         ///< with any shuffle mask.
511     SK_PermuteSingleSrc ///< Shuffle elements of single source vector with any
512                         ///< shuffle mask.
513   };
514
515   /// \brief Additional information about an operand's possible values.
516   enum OperandValueKind {
517     OK_AnyValue,               // Operand can have any value.
518     OK_UniformValue,           // Operand is uniform (splat of a value).
519     OK_UniformConstantValue,   // Operand is uniform constant.
520     OK_NonUniformConstantValue // Operand is a non uniform constant value.
521   };
522
523   /// \brief Additional properties of an operand's values.
524   enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
525
526   /// \return The number of scalar or vector registers that the target has.
527   /// If 'Vectors' is true, it returns the number of vector registers. If it is
528   /// set to false, it returns the number of scalar registers.
529   unsigned getNumberOfRegisters(bool Vector) const;
530
531   /// \return The width of the largest scalar or vector register type.
532   unsigned getRegisterBitWidth(bool Vector) const;
533
534   /// \return True if it should be considered for address type promotion.
535   /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
536   /// profitable without finding other extensions fed by the same input.
537   bool shouldConsiderAddressTypePromotion(
538       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
539
540   /// \return The size of a cache line in bytes.
541   unsigned getCacheLineSize() const;
542
543   /// \return How much before a load we should place the prefetch instruction.
544   /// This is currently measured in number of instructions.
545   unsigned getPrefetchDistance() const;
546
547   /// \return Some HW prefetchers can handle accesses up to a certain constant
548   /// stride.  This is the minimum stride in bytes where it makes sense to start
549   /// adding SW prefetches.  The default is 1, i.e. prefetch with any stride.
550   unsigned getMinPrefetchStride() const;
551
552   /// \return The maximum number of iterations to prefetch ahead.  If the
553   /// required number of iterations is more than this number, no prefetching is
554   /// performed.
555   unsigned getMaxPrefetchIterationsAhead() const;
556
557   /// \return The maximum interleave factor that any transform should try to
558   /// perform for this target. This number depends on the level of parallelism
559   /// and the number of execution units in the CPU.
560   unsigned getMaxInterleaveFactor(unsigned VF) const;
561
562   /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
563   /// \p Args is an optional argument which holds the instruction operands  
564   /// values so the TTI can analyize those values searching for special 
565   /// cases\optimizations based on those values.
566   int getArithmeticInstrCost(
567       unsigned Opcode, Type *Ty, OperandValueKind Opd1Info = OK_AnyValue,
568       OperandValueKind Opd2Info = OK_AnyValue,
569       OperandValueProperties Opd1PropInfo = OP_None,
570       OperandValueProperties Opd2PropInfo = OP_None,
571       ArrayRef<const Value *> Args = ArrayRef<const Value *>()) const;
572
573   /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
574   /// The index and subtype parameters are used by the subvector insertion and
575   /// extraction shuffle kinds.
576   int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
577                      Type *SubTp = nullptr) const;
578
579   /// \return The expected cost of cast instructions, such as bitcast, trunc,
580   /// zext, etc. If there is an existing instruction that holds Opcode, it
581   /// may be passed in the 'I' parameter.
582   int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
583                        const Instruction *I = nullptr) const;
584
585   /// \return The expected cost of a sign- or zero-extended vector extract. Use
586   /// -1 to indicate that there is no information about the index value.
587   int getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
588                                unsigned Index = -1) const;
589
590   /// \return The expected cost of control-flow related instructions such as
591   /// Phi, Ret, Br.
592   int getCFInstrCost(unsigned Opcode) const;
593
594   /// \returns The expected cost of compare and select instructions. If there
595   /// is an existing instruction that holds Opcode, it may be passed in the
596   /// 'I' parameter.
597   int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
598                  Type *CondTy = nullptr, const Instruction *I = nullptr) const;
599
600   /// \return The expected cost of vector Insert and Extract.
601   /// Use -1 to indicate that there is no information on the index value.
602   int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index = -1) const;
603
604   /// \return The cost of Load and Store instructions.
605   int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
606                       unsigned AddressSpace, const Instruction *I = nullptr) const;
607
608   /// \return The cost of masked Load and Store instructions.
609   int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
610                             unsigned AddressSpace) const;
611
612   /// \return The cost of Gather or Scatter operation
613   /// \p Opcode - is a type of memory access Load or Store
614   /// \p DataTy - a vector type of the data to be loaded or stored
615   /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
616   /// \p VariableMask - true when the memory access is predicated with a mask
617   ///                   that is not a compile-time constant
618   /// \p Alignment - alignment of single element
619   int getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
620                              bool VariableMask, unsigned Alignment) const;
621
622   /// \return The cost of the interleaved memory operation.
623   /// \p Opcode is the memory operation code
624   /// \p VecTy is the vector type of the interleaved access.
625   /// \p Factor is the interleave factor
626   /// \p Indices is the indices for interleaved load members (as interleaved
627   ///    load allows gaps)
628   /// \p Alignment is the alignment of the memory operation
629   /// \p AddressSpace is address space of the pointer.
630   int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
631                                  ArrayRef<unsigned> Indices, unsigned Alignment,
632                                  unsigned AddressSpace) const;
633
634   /// \brief Calculate the cost of performing a vector reduction.
635   ///
636   /// This is the cost of reducing the vector value of type \p Ty to a scalar
637   /// value using the operation denoted by \p Opcode. The form of the reduction
638   /// can either be a pairwise reduction or a reduction that splits the vector
639   /// at every reduction level.
640   ///
641   /// Pairwise:
642   ///  (v0, v1, v2, v3)
643   ///  ((v0+v1), (v2, v3), undef, undef)
644   /// Split:
645   ///  (v0, v1, v2, v3)
646   ///  ((v0+v2), (v1+v3), undef, undef)
647   int getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwiseForm) const;
648
649   /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
650   /// Three cases are handled: 1. scalar instruction 2. vector instruction
651   /// 3. scalar instruction which is to be vectorized with VF.
652   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
653                             ArrayRef<Value *> Args, FastMathFlags FMF,
654                             unsigned VF = 1) const;
655
656   /// \returns The cost of Intrinsic instructions. Types analysis only.
657   /// If ScalarizationCostPassed is UINT_MAX, the cost of scalarizing the
658   /// arguments and the return value will be computed based on types.
659   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
660                             ArrayRef<Type *> Tys, FastMathFlags FMF,
661                             unsigned ScalarizationCostPassed = UINT_MAX) const;
662
663   /// \returns The cost of Call instructions.
664   int getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) const;
665
666   /// \returns The number of pieces into which the provided type must be
667   /// split during legalization. Zero is returned when the answer is unknown.
668   unsigned getNumberOfParts(Type *Tp) const;
669
670   /// \returns The cost of the address computation. For most targets this can be
671   /// merged into the instruction indexing mode. Some targets might want to
672   /// distinguish between address computation for memory operations on vector
673   /// types and scalar types. Such targets should override this function.
674   /// The 'SE' parameter holds pointer for the scalar evolution object which
675   /// is used in order to get the Ptr step value in case of constant stride.
676   /// The 'Ptr' parameter holds SCEV of the access pointer.
677   int getAddressComputationCost(Type *Ty, ScalarEvolution *SE = nullptr,
678                                 const SCEV *Ptr = nullptr) const;
679
680   /// \returns The cost, if any, of keeping values of the given types alive
681   /// over a callsite.
682   ///
683   /// Some types may require the use of register classes that do not have
684   /// any callee-saved registers, so would require a spill and fill.
685   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
686
687   /// \returns True if the intrinsic is a supported memory intrinsic.  Info
688   /// will contain additional information - whether the intrinsic may write
689   /// or read to memory, volatility and the pointer.  Info is undefined
690   /// if false is returned.
691   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
692
693   /// \returns A value which is the result of the given memory intrinsic.  New
694   /// instructions may be created to extract the result from the given intrinsic
695   /// memory operation.  Returns nullptr if the target cannot create a result
696   /// from the given intrinsic.
697   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
698                                            Type *ExpectedType) const;
699
700   /// \returns True if the two functions have compatible attributes for inlining
701   /// purposes.
702   bool areInlineCompatible(const Function *Caller,
703                            const Function *Callee) const;
704
705   /// \returns The bitwidth of the largest vector type that should be used to
706   /// load/store in the given address space.
707   unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
708
709   /// \returns True if the load instruction is legal to vectorize.
710   bool isLegalToVectorizeLoad(LoadInst *LI) const;
711
712   /// \returns True if the store instruction is legal to vectorize.
713   bool isLegalToVectorizeStore(StoreInst *SI) const;
714
715   /// \returns True if it is legal to vectorize the given load chain.
716   bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
717                                    unsigned Alignment,
718                                    unsigned AddrSpace) const;
719
720   /// \returns True if it is legal to vectorize the given store chain.
721   bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
722                                     unsigned Alignment,
723                                     unsigned AddrSpace) const;
724
725   /// \returns The new vector factor value if the target doesn't support \p
726   /// SizeInBytes loads or has a better vector factor.
727   unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
728                                unsigned ChainSizeInBytes,
729                                VectorType *VecTy) const;
730
731   /// \returns The new vector factor value if the target doesn't support \p
732   /// SizeInBytes stores or has a better vector factor.
733   unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
734                                 unsigned ChainSizeInBytes,
735                                 VectorType *VecTy) const;
736
737   /// @}
738
739 private:
740   /// \brief The abstract base class used to type erase specific TTI
741   /// implementations.
742   class Concept;
743
744   /// \brief The template model for the base class which wraps a concrete
745   /// implementation in a type erased interface.
746   template <typename T> class Model;
747
748   std::unique_ptr<Concept> TTIImpl;
749 };
750
751 class TargetTransformInfo::Concept {
752 public:
753   virtual ~Concept() = 0;
754   virtual const DataLayout &getDataLayout() const = 0;
755   virtual int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) = 0;
756   virtual int getGEPCost(Type *PointeeType, const Value *Ptr,
757                          ArrayRef<const Value *> Operands) = 0;
758   virtual int getCallCost(FunctionType *FTy, int NumArgs) = 0;
759   virtual int getCallCost(const Function *F, int NumArgs) = 0;
760   virtual int getCallCost(const Function *F,
761                           ArrayRef<const Value *> Arguments) = 0;
762   virtual unsigned getInliningThresholdMultiplier() = 0;
763   virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
764                                ArrayRef<Type *> ParamTys) = 0;
765   virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
766                                ArrayRef<const Value *> Arguments) = 0;
767   virtual int getUserCost(const User *U) = 0;
768   virtual bool hasBranchDivergence() = 0;
769   virtual bool isSourceOfDivergence(const Value *V) = 0;
770   virtual unsigned getFlatAddressSpace() = 0;
771   virtual bool isLoweredToCall(const Function *F) = 0;
772   virtual void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) = 0;
773   virtual bool isLegalAddImmediate(int64_t Imm) = 0;
774   virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
775   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
776                                      int64_t BaseOffset, bool HasBaseReg,
777                                      int64_t Scale,
778                                      unsigned AddrSpace) = 0;
779   virtual bool isLegalMaskedStore(Type *DataType) = 0;
780   virtual bool isLegalMaskedLoad(Type *DataType) = 0;
781   virtual bool isLegalMaskedScatter(Type *DataType) = 0;
782   virtual bool isLegalMaskedGather(Type *DataType) = 0;
783   virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
784                                    int64_t BaseOffset, bool HasBaseReg,
785                                    int64_t Scale, unsigned AddrSpace) = 0;
786   virtual bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) = 0;
787   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
788   virtual bool isProfitableToHoist(Instruction *I) = 0;
789   virtual bool isTypeLegal(Type *Ty) = 0;
790   virtual unsigned getJumpBufAlignment() = 0;
791   virtual unsigned getJumpBufSize() = 0;
792   virtual bool shouldBuildLookupTables() = 0;
793   virtual bool shouldBuildLookupTablesForConstant(Constant *C) = 0;
794   virtual unsigned
795   getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) = 0;
796   virtual unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
797                                                     unsigned VF) = 0;
798   virtual bool supportsEfficientVectorElementLoadStore() = 0;
799   virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
800   virtual bool enableInterleavedAccessVectorization() = 0;
801   virtual bool isFPVectorizationPotentiallyUnsafe() = 0;
802   virtual bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
803                                               unsigned BitWidth,
804                                               unsigned AddressSpace,
805                                               unsigned Alignment,
806                                               bool *Fast) = 0;
807   virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
808   virtual bool haveFastSqrt(Type *Ty) = 0;
809   virtual int getFPOpCost(Type *Ty) = 0;
810   virtual int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
811                                     Type *Ty) = 0;
812   virtual int getIntImmCost(const APInt &Imm, Type *Ty) = 0;
813   virtual int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
814                             Type *Ty) = 0;
815   virtual int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
816                             Type *Ty) = 0;
817   virtual unsigned getNumberOfRegisters(bool Vector) = 0;
818   virtual unsigned getRegisterBitWidth(bool Vector) = 0;
819   virtual bool shouldConsiderAddressTypePromotion(
820       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) = 0;
821   virtual unsigned getCacheLineSize() = 0;
822   virtual unsigned getPrefetchDistance() = 0;
823   virtual unsigned getMinPrefetchStride() = 0;
824   virtual unsigned getMaxPrefetchIterationsAhead() = 0;
825   virtual unsigned getMaxInterleaveFactor(unsigned VF) = 0;
826   virtual unsigned
827   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
828                          OperandValueKind Opd2Info,
829                          OperandValueProperties Opd1PropInfo,
830                          OperandValueProperties Opd2PropInfo,
831                          ArrayRef<const Value *> Args) = 0;
832   virtual int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
833                              Type *SubTp) = 0;
834   virtual int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
835                                const Instruction *I) = 0;
836   virtual int getExtractWithExtendCost(unsigned Opcode, Type *Dst,
837                                        VectorType *VecTy, unsigned Index) = 0;
838   virtual int getCFInstrCost(unsigned Opcode) = 0;
839   virtual int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
840                                 Type *CondTy, const Instruction *I) = 0;
841   virtual int getVectorInstrCost(unsigned Opcode, Type *Val,
842                                  unsigned Index) = 0;
843   virtual int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
844                               unsigned AddressSpace, const Instruction *I) = 0;
845   virtual int getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
846                                     unsigned Alignment,
847                                     unsigned AddressSpace) = 0;
848   virtual int getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
849                                      Value *Ptr, bool VariableMask,
850                                      unsigned Alignment) = 0;
851   virtual int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
852                                          unsigned Factor,
853                                          ArrayRef<unsigned> Indices,
854                                          unsigned Alignment,
855                                          unsigned AddressSpace) = 0;
856   virtual int getReductionCost(unsigned Opcode, Type *Ty,
857                                bool IsPairwiseForm) = 0;
858   virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
859                       ArrayRef<Type *> Tys, FastMathFlags FMF,
860                       unsigned ScalarizationCostPassed) = 0;
861   virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
862          ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) = 0;
863   virtual int getCallInstrCost(Function *F, Type *RetTy,
864                                ArrayRef<Type *> Tys) = 0;
865   virtual unsigned getNumberOfParts(Type *Tp) = 0;
866   virtual int getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
867                                         const SCEV *Ptr) = 0;
868   virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
869   virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
870                                   MemIntrinsicInfo &Info) = 0;
871   virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
872                                                    Type *ExpectedType) = 0;
873   virtual bool areInlineCompatible(const Function *Caller,
874                                    const Function *Callee) const = 0;
875   virtual unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const = 0;
876   virtual bool isLegalToVectorizeLoad(LoadInst *LI) const = 0;
877   virtual bool isLegalToVectorizeStore(StoreInst *SI) const = 0;
878   virtual bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
879                                            unsigned Alignment,
880                                            unsigned AddrSpace) const = 0;
881   virtual bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
882                                             unsigned Alignment,
883                                             unsigned AddrSpace) const = 0;
884   virtual unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
885                                        unsigned ChainSizeInBytes,
886                                        VectorType *VecTy) const = 0;
887   virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
888                                         unsigned ChainSizeInBytes,
889                                         VectorType *VecTy) const = 0;
890 };
891
892 template <typename T>
893 class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
894   T Impl;
895
896 public:
897   Model(T Impl) : Impl(std::move(Impl)) {}
898   ~Model() override {}
899
900   const DataLayout &getDataLayout() const override {
901     return Impl.getDataLayout();
902   }
903
904   int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) override {
905     return Impl.getOperationCost(Opcode, Ty, OpTy);
906   }
907   int getGEPCost(Type *PointeeType, const Value *Ptr,
908                  ArrayRef<const Value *> Operands) override {
909     return Impl.getGEPCost(PointeeType, Ptr, Operands);
910   }
911   int getCallCost(FunctionType *FTy, int NumArgs) override {
912     return Impl.getCallCost(FTy, NumArgs);
913   }
914   int getCallCost(const Function *F, int NumArgs) override {
915     return Impl.getCallCost(F, NumArgs);
916   }
917   int getCallCost(const Function *F,
918                   ArrayRef<const Value *> Arguments) override {
919     return Impl.getCallCost(F, Arguments);
920   }
921   unsigned getInliningThresholdMultiplier() override {
922     return Impl.getInliningThresholdMultiplier();
923   }
924   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
925                        ArrayRef<Type *> ParamTys) override {
926     return Impl.getIntrinsicCost(IID, RetTy, ParamTys);
927   }
928   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
929                        ArrayRef<const Value *> Arguments) override {
930     return Impl.getIntrinsicCost(IID, RetTy, Arguments);
931   }
932   int getUserCost(const User *U) override { return Impl.getUserCost(U); }
933   bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
934   bool isSourceOfDivergence(const Value *V) override {
935     return Impl.isSourceOfDivergence(V);
936   }
937
938   unsigned getFlatAddressSpace() override {
939     return Impl.getFlatAddressSpace();
940   }
941
942   bool isLoweredToCall(const Function *F) override {
943     return Impl.isLoweredToCall(F);
944   }
945   void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) override {
946     return Impl.getUnrollingPreferences(L, UP);
947   }
948   bool isLegalAddImmediate(int64_t Imm) override {
949     return Impl.isLegalAddImmediate(Imm);
950   }
951   bool isLegalICmpImmediate(int64_t Imm) override {
952     return Impl.isLegalICmpImmediate(Imm);
953   }
954   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
955                              bool HasBaseReg, int64_t Scale,
956                              unsigned AddrSpace) override {
957     return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
958                                       Scale, AddrSpace);
959   }
960   bool isLegalMaskedStore(Type *DataType) override {
961     return Impl.isLegalMaskedStore(DataType);
962   }
963   bool isLegalMaskedLoad(Type *DataType) override {
964     return Impl.isLegalMaskedLoad(DataType);
965   }
966   bool isLegalMaskedScatter(Type *DataType) override {
967     return Impl.isLegalMaskedScatter(DataType);
968   }
969   bool isLegalMaskedGather(Type *DataType) override {
970     return Impl.isLegalMaskedGather(DataType);
971   }
972   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
973                            bool HasBaseReg, int64_t Scale,
974                            unsigned AddrSpace) override {
975     return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg,
976                                      Scale, AddrSpace);
977   }
978   bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) override {
979     return Impl.isFoldableMemAccessOffset(I, Offset);
980   }
981   bool isTruncateFree(Type *Ty1, Type *Ty2) override {
982     return Impl.isTruncateFree(Ty1, Ty2);
983   }
984   bool isProfitableToHoist(Instruction *I) override {
985     return Impl.isProfitableToHoist(I);
986   }
987   bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
988   unsigned getJumpBufAlignment() override { return Impl.getJumpBufAlignment(); }
989   unsigned getJumpBufSize() override { return Impl.getJumpBufSize(); }
990   bool shouldBuildLookupTables() override {
991     return Impl.shouldBuildLookupTables();
992   }
993   bool shouldBuildLookupTablesForConstant(Constant *C) override {
994     return Impl.shouldBuildLookupTablesForConstant(C);
995   }
996   unsigned getScalarizationOverhead(Type *Ty, bool Insert,
997                                     bool Extract) override {
998     return Impl.getScalarizationOverhead(Ty, Insert, Extract);
999   }
1000   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
1001                                             unsigned VF) override {
1002     return Impl.getOperandsScalarizationOverhead(Args, VF);
1003   }
1004
1005   bool supportsEfficientVectorElementLoadStore() override {
1006     return Impl.supportsEfficientVectorElementLoadStore();
1007   }
1008
1009   bool enableAggressiveInterleaving(bool LoopHasReductions) override {
1010     return Impl.enableAggressiveInterleaving(LoopHasReductions);
1011   }
1012   bool enableInterleavedAccessVectorization() override {
1013     return Impl.enableInterleavedAccessVectorization();
1014   }
1015   bool isFPVectorizationPotentiallyUnsafe() override {
1016     return Impl.isFPVectorizationPotentiallyUnsafe();
1017   }
1018   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
1019                                       unsigned BitWidth, unsigned AddressSpace,
1020                                       unsigned Alignment, bool *Fast) override {
1021     return Impl.allowsMisalignedMemoryAccesses(Context, BitWidth, AddressSpace,
1022                                                Alignment, Fast);
1023   }
1024   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
1025     return Impl.getPopcntSupport(IntTyWidthInBit);
1026   }
1027   bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
1028
1029   int getFPOpCost(Type *Ty) override { return Impl.getFPOpCost(Ty); }
1030
1031   int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1032                             Type *Ty) override {
1033     return Impl.getIntImmCodeSizeCost(Opc, Idx, Imm, Ty);
1034   }
1035   int getIntImmCost(const APInt &Imm, Type *Ty) override {
1036     return Impl.getIntImmCost(Imm, Ty);
1037   }
1038   int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1039                     Type *Ty) override {
1040     return Impl.getIntImmCost(Opc, Idx, Imm, Ty);
1041   }
1042   int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
1043                     Type *Ty) override {
1044     return Impl.getIntImmCost(IID, Idx, Imm, Ty);
1045   }
1046   unsigned getNumberOfRegisters(bool Vector) override {
1047     return Impl.getNumberOfRegisters(Vector);
1048   }
1049   unsigned getRegisterBitWidth(bool Vector) override {
1050     return Impl.getRegisterBitWidth(Vector);
1051   }
1052   bool shouldConsiderAddressTypePromotion(
1053       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) override {
1054     return Impl.shouldConsiderAddressTypePromotion(
1055         I, AllowPromotionWithoutCommonHeader);
1056   }
1057   unsigned getCacheLineSize() override {
1058     return Impl.getCacheLineSize();
1059   }
1060   unsigned getPrefetchDistance() override { return Impl.getPrefetchDistance(); }
1061   unsigned getMinPrefetchStride() override {
1062     return Impl.getMinPrefetchStride();
1063   }
1064   unsigned getMaxPrefetchIterationsAhead() override {
1065     return Impl.getMaxPrefetchIterationsAhead();
1066   }
1067   unsigned getMaxInterleaveFactor(unsigned VF) override {
1068     return Impl.getMaxInterleaveFactor(VF);
1069   }
1070   unsigned
1071   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
1072                          OperandValueKind Opd2Info,
1073                          OperandValueProperties Opd1PropInfo,
1074                          OperandValueProperties Opd2PropInfo,
1075                          ArrayRef<const Value *> Args) override {
1076     return Impl.getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
1077                                        Opd1PropInfo, Opd2PropInfo, Args);
1078   }
1079   int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
1080                      Type *SubTp) override {
1081     return Impl.getShuffleCost(Kind, Tp, Index, SubTp);
1082   }
1083   int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1084                        const Instruction *I) override {
1085     return Impl.getCastInstrCost(Opcode, Dst, Src, I);
1086   }
1087   int getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
1088                                unsigned Index) override {
1089     return Impl.getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
1090   }
1091   int getCFInstrCost(unsigned Opcode) override {
1092     return Impl.getCFInstrCost(Opcode);
1093   }
1094   int getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
1095                          const Instruction *I) override {
1096     return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
1097   }
1098   int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) override {
1099     return Impl.getVectorInstrCost(Opcode, Val, Index);
1100   }
1101   int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1102                       unsigned AddressSpace, const Instruction *I) override {
1103     return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
1104   }
1105   int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1106                             unsigned AddressSpace) override {
1107     return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
1108   }
1109   int getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1110                              Value *Ptr, bool VariableMask,
1111                              unsigned Alignment) override {
1112     return Impl.getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1113                                        Alignment);
1114   }
1115   int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
1116                                  ArrayRef<unsigned> Indices, unsigned Alignment,
1117                                  unsigned AddressSpace) override {
1118     return Impl.getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1119                                            Alignment, AddressSpace);
1120   }
1121   int getReductionCost(unsigned Opcode, Type *Ty,
1122                        bool IsPairwiseForm) override {
1123     return Impl.getReductionCost(Opcode, Ty, IsPairwiseForm);
1124   }
1125   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef<Type *> Tys,
1126                FastMathFlags FMF, unsigned ScalarizationCostPassed) override {
1127     return Impl.getIntrinsicInstrCost(ID, RetTy, Tys, FMF,
1128                                       ScalarizationCostPassed);
1129   }
1130   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1131        ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) override {
1132     return Impl.getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF);
1133   }
1134   int getCallInstrCost(Function *F, Type *RetTy,
1135                        ArrayRef<Type *> Tys) override {
1136     return Impl.getCallInstrCost(F, RetTy, Tys);
1137   }
1138   unsigned getNumberOfParts(Type *Tp) override {
1139     return Impl.getNumberOfParts(Tp);
1140   }
1141   int getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
1142                                 const SCEV *Ptr) override {
1143     return Impl.getAddressComputationCost(Ty, SE, Ptr);
1144   }
1145   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
1146     return Impl.getCostOfKeepingLiveOverCall(Tys);
1147   }
1148   bool getTgtMemIntrinsic(IntrinsicInst *Inst,
1149                           MemIntrinsicInfo &Info) override {
1150     return Impl.getTgtMemIntrinsic(Inst, Info);
1151   }
1152   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1153                                            Type *ExpectedType) override {
1154     return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
1155   }
1156   bool areInlineCompatible(const Function *Caller,
1157                            const Function *Callee) const override {
1158     return Impl.areInlineCompatible(Caller, Callee);
1159   }
1160   unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const override {
1161     return Impl.getLoadStoreVecRegBitWidth(AddrSpace);
1162   }
1163   bool isLegalToVectorizeLoad(LoadInst *LI) const override {
1164     return Impl.isLegalToVectorizeLoad(LI);
1165   }
1166   bool isLegalToVectorizeStore(StoreInst *SI) const override {
1167     return Impl.isLegalToVectorizeStore(SI);
1168   }
1169   bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1170                                    unsigned Alignment,
1171                                    unsigned AddrSpace) const override {
1172     return Impl.isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
1173                                             AddrSpace);
1174   }
1175   bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1176                                     unsigned Alignment,
1177                                     unsigned AddrSpace) const override {
1178     return Impl.isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
1179                                              AddrSpace);
1180   }
1181   unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1182                                unsigned ChainSizeInBytes,
1183                                VectorType *VecTy) const override {
1184     return Impl.getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
1185   }
1186   unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1187                                 unsigned ChainSizeInBytes,
1188                                 VectorType *VecTy) const override {
1189     return Impl.getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
1190   }
1191 };
1192
1193 template <typename T>
1194 TargetTransformInfo::TargetTransformInfo(T Impl)
1195     : TTIImpl(new Model<T>(Impl)) {}
1196
1197 /// \brief Analysis pass providing the \c TargetTransformInfo.
1198 ///
1199 /// The core idea of the TargetIRAnalysis is to expose an interface through
1200 /// which LLVM targets can analyze and provide information about the middle
1201 /// end's target-independent IR. This supports use cases such as target-aware
1202 /// cost modeling of IR constructs.
1203 ///
1204 /// This is a function analysis because much of the cost modeling for targets
1205 /// is done in a subtarget specific way and LLVM supports compiling different
1206 /// functions targeting different subtargets in order to support runtime
1207 /// dispatch according to the observed subtarget.
1208 class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
1209 public:
1210   typedef TargetTransformInfo Result;
1211
1212   /// \brief Default construct a target IR analysis.
1213   ///
1214   /// This will use the module's datalayout to construct a baseline
1215   /// conservative TTI result.
1216   TargetIRAnalysis();
1217
1218   /// \brief Construct an IR analysis pass around a target-provide callback.
1219   ///
1220   /// The callback will be called with a particular function for which the TTI
1221   /// is needed and must return a TTI object for that function.
1222   TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
1223
1224   // Value semantics. We spell out the constructors for MSVC.
1225   TargetIRAnalysis(const TargetIRAnalysis &Arg)
1226       : TTICallback(Arg.TTICallback) {}
1227   TargetIRAnalysis(TargetIRAnalysis &&Arg)
1228       : TTICallback(std::move(Arg.TTICallback)) {}
1229   TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
1230     TTICallback = RHS.TTICallback;
1231     return *this;
1232   }
1233   TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
1234     TTICallback = std::move(RHS.TTICallback);
1235     return *this;
1236   }
1237
1238   Result run(const Function &F, FunctionAnalysisManager &);
1239
1240 private:
1241   friend AnalysisInfoMixin<TargetIRAnalysis>;
1242   static AnalysisKey Key;
1243
1244   /// \brief The callback used to produce a result.
1245   ///
1246   /// We use a completely opaque callback so that targets can provide whatever
1247   /// mechanism they desire for constructing the TTI for a given function.
1248   ///
1249   /// FIXME: Should we really use std::function? It's relatively inefficient.
1250   /// It might be possible to arrange for even stateful callbacks to outlive
1251   /// the analysis and thus use a function_ref which would be lighter weight.
1252   /// This may also be less error prone as the callback is likely to reference
1253   /// the external TargetMachine, and that reference needs to never dangle.
1254   std::function<Result(const Function &)> TTICallback;
1255
1256   /// \brief Helper function used as the callback in the default constructor.
1257   static Result getDefaultTTI(const Function &F);
1258 };
1259
1260 /// \brief Wrapper pass for TargetTransformInfo.
1261 ///
1262 /// This pass can be constructed from a TTI object which it stores internally
1263 /// and is queried by passes.
1264 class TargetTransformInfoWrapperPass : public ImmutablePass {
1265   TargetIRAnalysis TIRA;
1266   Optional<TargetTransformInfo> TTI;
1267
1268   virtual void anchor();
1269
1270 public:
1271   static char ID;
1272
1273   /// \brief We must provide a default constructor for the pass but it should
1274   /// never be used.
1275   ///
1276   /// Use the constructor below or call one of the creation routines.
1277   TargetTransformInfoWrapperPass();
1278
1279   explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
1280
1281   TargetTransformInfo &getTTI(const Function &F);
1282 };
1283
1284 /// \brief Create an analysis pass wrapper around a TTI object.
1285 ///
1286 /// This analysis pass just holds the TTI instance and makes it available to
1287 /// clients.
1288 ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
1289
1290 } // End llvm namespace
1291
1292 #endif