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