1 //===- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI pass -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // \file
10 // This file implements a TargetTransformInfo analysis pass specific to the
11 // AMDGPU target machine. It uses the target's detailed information to provide
12 // more precise answers to certain TTI queries, while letting the target
13 // independent and default TTI implementations handle the rest.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "AMDGPUTargetTransformInfo.h"
18 #include "AMDGPUSubtarget.h"
19 #include "Utils/AMDGPUBaseInfo.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/CodeGen/ISDOpcodes.h"
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/PatternMatch.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/KnownBits.h"
46 #include "llvm/Support/MachineValueType.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <limits>
52 #include <utility>
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "AMDGPUtti"
57 
58 static cl::opt<unsigned> UnrollThresholdPrivate(
59   "amdgpu-unroll-threshold-private",
60   cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"),
61   cl::init(2700), cl::Hidden);
62 
63 static cl::opt<unsigned> UnrollThresholdLocal(
64   "amdgpu-unroll-threshold-local",
65   cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"),
66   cl::init(1000), cl::Hidden);
67 
68 static cl::opt<unsigned> UnrollThresholdIf(
69   "amdgpu-unroll-threshold-if",
70   cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"),
71   cl::init(150), cl::Hidden);
72 
73 static cl::opt<bool> UnrollRuntimeLocal(
74   "amdgpu-unroll-runtime-local",
75   cl::desc("Allow runtime unroll for AMDGPU if local memory used in a loop"),
76   cl::init(true), cl::Hidden);
77 
78 static cl::opt<bool> UseLegacyDA(
79   "amdgpu-use-legacy-divergence-analysis",
80   cl::desc("Enable legacy divergence analysis for AMDGPU"),
81   cl::init(false), cl::Hidden);
82 
83 static cl::opt<unsigned> UnrollMaxBlockToAnalyze(
84     "amdgpu-unroll-max-block-to-analyze",
85     cl::desc("Inner loop block size threshold to analyze in unroll for AMDGPU"),
86     cl::init(32), cl::Hidden);
87 
88 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond,
89                               unsigned Depth = 0) {
90   const Instruction *I = dyn_cast<Instruction>(Cond);
91   if (!I)
92     return false;
93 
94   for (const Value *V : I->operand_values()) {
95     if (!L->contains(I))
96       continue;
97     if (const PHINode *PHI = dyn_cast<PHINode>(V)) {
98       if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) {
99                   return SubLoop->contains(PHI); }))
100         return true;
101     } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1))
102       return true;
103   }
104   return false;
105 }
106 
107 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
108                                             TTI::UnrollingPreferences &UP) {
109   const Function &F = *L->getHeader()->getParent();
110   UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300);
111   UP.MaxCount = std::numeric_limits<unsigned>::max();
112   UP.Partial = true;
113 
114   // TODO: Do we want runtime unrolling?
115 
116   // Maximum alloca size than can fit registers. Reserve 16 registers.
117   const unsigned MaxAlloca = (256 - 16) * 4;
118   unsigned ThresholdPrivate = UnrollThresholdPrivate;
119   unsigned ThresholdLocal = UnrollThresholdLocal;
120 
121   // If this loop has the amdgpu.loop.unroll.threshold metadata we will use the
122   // provided threshold value as the default for Threshold
123   if (MDNode *LoopUnrollThreshold =
124           findOptionMDForLoop(L, "amdgpu.loop.unroll.threshold")) {
125     if (LoopUnrollThreshold->getNumOperands() == 2) {
126       ConstantInt *MetaThresholdValue = mdconst::extract_or_null<ConstantInt>(
127           LoopUnrollThreshold->getOperand(1));
128       if (MetaThresholdValue) {
129         // We will also use the supplied value for PartialThreshold for now.
130         // We may introduce additional metadata if it becomes necessary in the
131         // future.
132         UP.Threshold = MetaThresholdValue->getSExtValue();
133         UP.PartialThreshold = UP.Threshold;
134         ThresholdPrivate = std::min(ThresholdPrivate, UP.Threshold);
135         ThresholdLocal = std::min(ThresholdLocal, UP.Threshold);
136       }
137     }
138   }
139 
140   unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal);
141   for (const BasicBlock *BB : L->getBlocks()) {
142     const DataLayout &DL = BB->getModule()->getDataLayout();
143     unsigned LocalGEPsSeen = 0;
144 
145     if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) {
146                return SubLoop->contains(BB); }))
147         continue; // Block belongs to an inner loop.
148 
149     for (const Instruction &I : *BB) {
150       // Unroll a loop which contains an "if" statement whose condition
151       // defined by a PHI belonging to the loop. This may help to eliminate
152       // if region and potentially even PHI itself, saving on both divergence
153       // and registers used for the PHI.
154       // Add a small bonus for each of such "if" statements.
155       if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) {
156         if (UP.Threshold < MaxBoost && Br->isConditional()) {
157           BasicBlock *Succ0 = Br->getSuccessor(0);
158           BasicBlock *Succ1 = Br->getSuccessor(1);
159           if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) ||
160               (L->contains(Succ1) && L->isLoopExiting(Succ1)))
161             continue;
162           if (dependsOnLocalPhi(L, Br->getCondition())) {
163             UP.Threshold += UnrollThresholdIf;
164             LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold
165                               << " for loop:\n"
166                               << *L << " due to " << *Br << '\n');
167             if (UP.Threshold >= MaxBoost)
168               return;
169           }
170         }
171         continue;
172       }
173 
174       const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I);
175       if (!GEP)
176         continue;
177 
178       unsigned AS = GEP->getAddressSpace();
179       unsigned Threshold = 0;
180       if (AS == AMDGPUAS::PRIVATE_ADDRESS)
181         Threshold = ThresholdPrivate;
182       else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS)
183         Threshold = ThresholdLocal;
184       else
185         continue;
186 
187       if (UP.Threshold >= Threshold)
188         continue;
189 
190       if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
191         const Value *Ptr = GEP->getPointerOperand();
192         const AllocaInst *Alloca =
193             dyn_cast<AllocaInst>(getUnderlyingObject(Ptr));
194         if (!Alloca || !Alloca->isStaticAlloca())
195           continue;
196         Type *Ty = Alloca->getAllocatedType();
197         unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0;
198         if (AllocaSize > MaxAlloca)
199           continue;
200       } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
201                  AS == AMDGPUAS::REGION_ADDRESS) {
202         LocalGEPsSeen++;
203         // Inhibit unroll for local memory if we have seen addressing not to
204         // a variable, most likely we will be unable to combine it.
205         // Do not unroll too deep inner loops for local memory to give a chance
206         // to unroll an outer loop for a more important reason.
207         if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 ||
208             (!isa<GlobalVariable>(GEP->getPointerOperand()) &&
209              !isa<Argument>(GEP->getPointerOperand())))
210           continue;
211         LLVM_DEBUG(dbgs() << "Allow unroll runtime for loop:\n"
212                           << *L << " due to LDS use.\n");
213         UP.Runtime = UnrollRuntimeLocal;
214       }
215 
216       // Check if GEP depends on a value defined by this loop itself.
217       bool HasLoopDef = false;
218       for (const Value *Op : GEP->operands()) {
219         const Instruction *Inst = dyn_cast<Instruction>(Op);
220         if (!Inst || L->isLoopInvariant(Op))
221           continue;
222 
223         if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) {
224              return SubLoop->contains(Inst); }))
225           continue;
226         HasLoopDef = true;
227         break;
228       }
229       if (!HasLoopDef)
230         continue;
231 
232       // We want to do whatever we can to limit the number of alloca
233       // instructions that make it through to the code generator.  allocas
234       // require us to use indirect addressing, which is slow and prone to
235       // compiler bugs.  If this loop does an address calculation on an
236       // alloca ptr, then we want to use a higher than normal loop unroll
237       // threshold. This will give SROA a better chance to eliminate these
238       // allocas.
239       //
240       // We also want to have more unrolling for local memory to let ds
241       // instructions with different offsets combine.
242       //
243       // Don't use the maximum allowed value here as it will make some
244       // programs way too big.
245       UP.Threshold = Threshold;
246       LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold
247                         << " for loop:\n"
248                         << *L << " due to " << *GEP << '\n');
249       if (UP.Threshold >= MaxBoost)
250         return;
251     }
252 
253     // If we got a GEP in a small BB from inner loop then increase max trip
254     // count to analyze for better estimation cost in unroll
255     if (L->isInnermost() && BB->size() < UnrollMaxBlockToAnalyze)
256       UP.MaxIterationsCountToAnalyze = 32;
257   }
258 }
259 
260 void AMDGPUTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
261                                           TTI::PeelingPreferences &PP) {
262   BaseT::getPeelingPreferences(L, SE, PP);
263 }
264 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
265   // The concept of vector registers doesn't really exist. Some packed vector
266   // operations operate on the normal 32-bit registers.
267   return MaxVGPRs;
268 }
269 
270 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const {
271   // This is really the number of registers to fill when vectorizing /
272   // interleaving loops, so we lie to avoid trying to use all registers.
273   return getHardwareNumberOfRegisters(Vec) >> 3;
274 }
275 
276 unsigned GCNTTIImpl::getNumberOfRegisters(unsigned RCID) const {
277   const SIRegisterInfo *TRI = ST->getRegisterInfo();
278   const TargetRegisterClass *RC = TRI->getRegClass(RCID);
279   unsigned NumVGPRs = (TRI->getRegSizeInBits(*RC) + 31) / 32;
280   return getHardwareNumberOfRegisters(false) / NumVGPRs;
281 }
282 
283 unsigned GCNTTIImpl::getRegisterBitWidth(bool Vector) const {
284   return 32;
285 }
286 
287 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const {
288   return 32;
289 }
290 
291 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize,
292                                          unsigned ChainSizeInBytes,
293                                          VectorType *VecTy) const {
294   unsigned VecRegBitWidth = VF * LoadSize;
295   if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32)
296     // TODO: Support element-size less than 32bit?
297     return 128 / LoadSize;
298 
299   return VF;
300 }
301 
302 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize,
303                                              unsigned ChainSizeInBytes,
304                                              VectorType *VecTy) const {
305   unsigned VecRegBitWidth = VF * StoreSize;
306   if (VecRegBitWidth > 128)
307     return 128 / StoreSize;
308 
309   return VF;
310 }
311 
312 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
313   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
314       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
315       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
316       AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) {
317     return 512;
318   }
319 
320   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
321     return 8 * ST->getMaxPrivateElementSize();
322 
323   // Common to flat, global, local and region. Assume for unknown addrspace.
324   return 128;
325 }
326 
327 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
328                                             Align Alignment,
329                                             unsigned AddrSpace) const {
330   // We allow vectorization of flat stores, even though we may need to decompose
331   // them later if they may access private memory. We don't have enough context
332   // here, and legalization can handle it.
333   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
334     return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) &&
335       ChainSizeInBytes <= ST->getMaxPrivateElementSize();
336   }
337   return true;
338 }
339 
340 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
341                                              Align Alignment,
342                                              unsigned AddrSpace) const {
343   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
344 }
345 
346 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
347                                               Align Alignment,
348                                               unsigned AddrSpace) const {
349   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
350 }
351 
352 // FIXME: Really we would like to issue multiple 128-bit loads and stores per
353 // iteration. Should we report a larger size and let it legalize?
354 //
355 // FIXME: Should we use narrower types for local/region, or account for when
356 // unaligned access is legal?
357 //
358 // FIXME: This could use fine tuning and microbenchmarks.
359 Type *GCNTTIImpl::getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
360                                             unsigned SrcAddrSpace,
361                                             unsigned DestAddrSpace,
362                                             unsigned SrcAlign,
363                                             unsigned DestAlign) const {
364   unsigned MinAlign = std::min(SrcAlign, DestAlign);
365 
366   // A (multi-)dword access at an address == 2 (mod 4) will be decomposed by the
367   // hardware into byte accesses. If you assume all alignments are equally
368   // probable, it's more efficient on average to use short accesses for this
369   // case.
370   if (MinAlign == 2)
371     return Type::getInt16Ty(Context);
372 
373   // Not all subtargets have 128-bit DS instructions, and we currently don't
374   // form them by default.
375   if (SrcAddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
376       SrcAddrSpace == AMDGPUAS::REGION_ADDRESS ||
377       DestAddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
378       DestAddrSpace == AMDGPUAS::REGION_ADDRESS) {
379     return FixedVectorType::get(Type::getInt32Ty(Context), 2);
380   }
381 
382   // Global memory works best with 16-byte accesses. Private memory will also
383   // hit this, although they'll be decomposed.
384   return FixedVectorType::get(Type::getInt32Ty(Context), 4);
385 }
386 
387 void GCNTTIImpl::getMemcpyLoopResidualLoweringType(
388   SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
389   unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
390   unsigned SrcAlign, unsigned DestAlign) const {
391   assert(RemainingBytes < 16);
392 
393   unsigned MinAlign = std::min(SrcAlign, DestAlign);
394 
395   if (MinAlign != 2) {
396     Type *I64Ty = Type::getInt64Ty(Context);
397     while (RemainingBytes >= 8) {
398       OpsOut.push_back(I64Ty);
399       RemainingBytes -= 8;
400     }
401 
402     Type *I32Ty = Type::getInt32Ty(Context);
403     while (RemainingBytes >= 4) {
404       OpsOut.push_back(I32Ty);
405       RemainingBytes -= 4;
406     }
407   }
408 
409   Type *I16Ty = Type::getInt16Ty(Context);
410   while (RemainingBytes >= 2) {
411     OpsOut.push_back(I16Ty);
412     RemainingBytes -= 2;
413   }
414 
415   Type *I8Ty = Type::getInt8Ty(Context);
416   while (RemainingBytes) {
417     OpsOut.push_back(I8Ty);
418     --RemainingBytes;
419   }
420 }
421 
422 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) {
423   // Disable unrolling if the loop is not vectorized.
424   // TODO: Enable this again.
425   if (VF == 1)
426     return 1;
427 
428   return 8;
429 }
430 
431 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
432                                        MemIntrinsicInfo &Info) const {
433   switch (Inst->getIntrinsicID()) {
434   case Intrinsic::amdgcn_atomic_inc:
435   case Intrinsic::amdgcn_atomic_dec:
436   case Intrinsic::amdgcn_ds_ordered_add:
437   case Intrinsic::amdgcn_ds_ordered_swap:
438   case Intrinsic::amdgcn_ds_fadd:
439   case Intrinsic::amdgcn_ds_fmin:
440   case Intrinsic::amdgcn_ds_fmax: {
441     auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2));
442     auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4));
443     if (!Ordering || !Volatile)
444       return false; // Invalid.
445 
446     unsigned OrderingVal = Ordering->getZExtValue();
447     if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent))
448       return false;
449 
450     Info.PtrVal = Inst->getArgOperand(0);
451     Info.Ordering = static_cast<AtomicOrdering>(OrderingVal);
452     Info.ReadMem = true;
453     Info.WriteMem = true;
454     Info.IsVolatile = !Volatile->isNullValue();
455     return true;
456   }
457   default:
458     return false;
459   }
460 }
461 
462 int GCNTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
463                                        TTI::TargetCostKind CostKind,
464                                        TTI::OperandValueKind Opd1Info,
465                                        TTI::OperandValueKind Opd2Info,
466                                        TTI::OperandValueProperties Opd1PropInfo,
467                                        TTI::OperandValueProperties Opd2PropInfo,
468                                        ArrayRef<const Value *> Args,
469                                        const Instruction *CxtI) {
470   EVT OrigTy = TLI->getValueType(DL, Ty);
471   if (!OrigTy.isSimple()) {
472     // FIXME: We're having to query the throughput cost so that the basic
473     // implementation tries to generate legalize and scalarization costs. Maybe
474     // we could hoist the scalarization code here?
475     if (CostKind != TTI::TCK_CodeSize)
476       return BaseT::getArithmeticInstrCost(Opcode, Ty, TTI::TCK_RecipThroughput,
477                                            Opd1Info, Opd2Info, Opd1PropInfo,
478                                            Opd2PropInfo, Args, CxtI);
479     // Scalarization
480 
481     // Check if any of the operands are vector operands.
482     int ISD = TLI->InstructionOpcodeToISD(Opcode);
483     assert(ISD && "Invalid opcode");
484 
485     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
486 
487     bool IsFloat = Ty->isFPOrFPVectorTy();
488     // Assume that floating point arithmetic operations cost twice as much as
489     // integer operations.
490     unsigned OpCost = (IsFloat ? 2 : 1);
491 
492     if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
493       // The operation is legal. Assume it costs 1.
494       // TODO: Once we have extract/insert subvector cost we need to use them.
495       return LT.first * OpCost;
496     }
497 
498     if (!TLI->isOperationExpand(ISD, LT.second)) {
499       // If the operation is custom lowered, then assume that the code is twice
500       // as expensive.
501       return LT.first * 2 * OpCost;
502     }
503 
504     // Else, assume that we need to scalarize this op.
505     // TODO: If one of the types get legalized by splitting, handle this
506     // similarly to what getCastInstrCost() does.
507     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
508       unsigned Num = cast<FixedVectorType>(VTy)->getNumElements();
509       unsigned Cost = getArithmeticInstrCost(
510           Opcode, VTy->getScalarType(), CostKind, Opd1Info, Opd2Info,
511           Opd1PropInfo, Opd2PropInfo, Args, CxtI);
512       // Return the cost of multiple scalar invocation plus the cost of
513       // inserting and extracting the values.
514       return getScalarizationOverhead(VTy, Args) + Num * Cost;
515     }
516 
517     // We don't know anything about this scalar instruction.
518     return OpCost;
519   }
520 
521   // Legalize the type.
522   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
523   int ISD = TLI->InstructionOpcodeToISD(Opcode);
524 
525   // Because we don't have any legal vector operations, but the legal types, we
526   // need to account for split vectors.
527   unsigned NElts = LT.second.isVector() ?
528     LT.second.getVectorNumElements() : 1;
529 
530   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
531 
532   switch (ISD) {
533   case ISD::SHL:
534   case ISD::SRL:
535   case ISD::SRA:
536     if (SLT == MVT::i64)
537       return get64BitInstrCost(CostKind) * LT.first * NElts;
538 
539     if (ST->has16BitInsts() && SLT == MVT::i16)
540       NElts = (NElts + 1) / 2;
541 
542     // i32
543     return getFullRateInstrCost() * LT.first * NElts;
544   case ISD::ADD:
545   case ISD::SUB:
546   case ISD::AND:
547   case ISD::OR:
548   case ISD::XOR:
549     if (SLT == MVT::i64) {
550       // and, or and xor are typically split into 2 VALU instructions.
551       return 2 * getFullRateInstrCost() * LT.first * NElts;
552     }
553 
554     if (ST->has16BitInsts() && SLT == MVT::i16)
555       NElts = (NElts + 1) / 2;
556 
557     return LT.first * NElts * getFullRateInstrCost();
558   case ISD::MUL: {
559     const int QuarterRateCost = getQuarterRateInstrCost(CostKind);
560     if (SLT == MVT::i64) {
561       const int FullRateCost = getFullRateInstrCost();
562       return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts;
563     }
564 
565     if (ST->has16BitInsts() && SLT == MVT::i16)
566       NElts = (NElts + 1) / 2;
567 
568     // i32
569     return QuarterRateCost * NElts * LT.first;
570   }
571   case ISD::FMUL:
572     // Check possible fuse {fadd|fsub}(a,fmul(b,c)) and return zero cost for
573     // fmul(b,c) supposing the fadd|fsub will get estimated cost for the whole
574     // fused operation.
575     if (CxtI && CxtI->hasOneUse())
576       if (const auto *FAdd = dyn_cast<BinaryOperator>(*CxtI->user_begin())) {
577         const int OPC = TLI->InstructionOpcodeToISD(FAdd->getOpcode());
578         if (OPC == ISD::FADD || OPC == ISD::FSUB) {
579           if (ST->hasMadMacF32Insts() && SLT == MVT::f32 && !HasFP32Denormals)
580             return TargetTransformInfo::TCC_Free;
581           if (ST->has16BitInsts() && SLT == MVT::f16 && !HasFP64FP16Denormals)
582             return TargetTransformInfo::TCC_Free;
583 
584           // Estimate all types may be fused with contract/unsafe flags
585           const TargetOptions &Options = TLI->getTargetMachine().Options;
586           if (Options.AllowFPOpFusion == FPOpFusion::Fast ||
587               Options.UnsafeFPMath ||
588               (FAdd->hasAllowContract() && CxtI->hasAllowContract()))
589             return TargetTransformInfo::TCC_Free;
590         }
591       }
592     LLVM_FALLTHROUGH;
593   case ISD::FADD:
594   case ISD::FSUB:
595     if (SLT == MVT::f64)
596       return LT.first * NElts * get64BitInstrCost(CostKind);
597 
598     if (ST->has16BitInsts() && SLT == MVT::f16)
599       NElts = (NElts + 1) / 2;
600 
601     if (SLT == MVT::f32 || SLT == MVT::f16)
602       return LT.first * NElts * getFullRateInstrCost();
603     break;
604   case ISD::FDIV:
605   case ISD::FREM:
606     // FIXME: frem should be handled separately. The fdiv in it is most of it,
607     // but the current lowering is also not entirely correct.
608     if (SLT == MVT::f64) {
609       int Cost = 7 * get64BitInstrCost(CostKind) +
610                  getQuarterRateInstrCost(CostKind) +
611                  3 * getHalfRateInstrCost(CostKind);
612       // Add cost of workaround.
613       if (!ST->hasUsableDivScaleConditionOutput())
614         Cost += 3 * getFullRateInstrCost();
615 
616       return LT.first * Cost * NElts;
617     }
618 
619     if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) {
620       // TODO: This is more complicated, unsafe flags etc.
621       if ((SLT == MVT::f32 && !HasFP32Denormals) ||
622           (SLT == MVT::f16 && ST->has16BitInsts())) {
623         return LT.first * getQuarterRateInstrCost(CostKind) * NElts;
624       }
625     }
626 
627     if (SLT == MVT::f16 && ST->has16BitInsts()) {
628       // 2 x v_cvt_f32_f16
629       // f32 rcp
630       // f32 fmul
631       // v_cvt_f16_f32
632       // f16 div_fixup
633       int Cost =
634           4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost(CostKind);
635       return LT.first * Cost * NElts;
636     }
637 
638     if (SLT == MVT::f32 || SLT == MVT::f16) {
639       // 4 more v_cvt_* insts without f16 insts support
640       int Cost = (SLT == MVT::f16 ? 14 : 10) * getFullRateInstrCost() +
641                  1 * getQuarterRateInstrCost(CostKind);
642 
643       if (!HasFP32Denormals) {
644         // FP mode switches.
645         Cost += 2 * getFullRateInstrCost();
646       }
647 
648       return LT.first * NElts * Cost;
649     }
650     break;
651   case ISD::FNEG:
652     // Use the backend' estimation. If fneg is not free each element will cost
653     // one additional instruction.
654     return TLI->isFNegFree(SLT) ? 0 : NElts;
655   default:
656     break;
657   }
658 
659   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info,
660                                        Opd1PropInfo, Opd2PropInfo, Args, CxtI);
661 }
662 
663 // Return true if there's a potential benefit from using v2f16/v2i16
664 // instructions for an intrinsic, even if it requires nontrivial legalization.
665 static bool intrinsicHasPackedVectorBenefit(Intrinsic::ID ID) {
666   switch (ID) {
667   case Intrinsic::fma: // TODO: fmuladd
668   // There's a small benefit to using vector ops in the legalized code.
669   case Intrinsic::round:
670   case Intrinsic::uadd_sat:
671   case Intrinsic::usub_sat:
672   case Intrinsic::sadd_sat:
673   case Intrinsic::ssub_sat:
674     return true;
675   default:
676     return false;
677   }
678 }
679 
680 int GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
681                                       TTI::TargetCostKind CostKind) {
682   if (ICA.getID() == Intrinsic::fabs)
683     return 0;
684 
685   if (!intrinsicHasPackedVectorBenefit(ICA.getID()))
686     return BaseT::getIntrinsicInstrCost(ICA, CostKind);
687 
688   Type *RetTy = ICA.getReturnType();
689   EVT OrigTy = TLI->getValueType(DL, RetTy);
690   if (!OrigTy.isSimple()) {
691     if (CostKind != TTI::TCK_CodeSize)
692       return BaseT::getIntrinsicInstrCost(ICA, CostKind);
693 
694     // TODO: Combine these two logic paths.
695     if (ICA.isTypeBasedOnly())
696       return getTypeBasedIntrinsicInstrCost(ICA, CostKind);
697 
698     Type *RetTy = ICA.getReturnType();
699     unsigned VF = ICA.getVectorFactor();
700     unsigned RetVF =
701         (RetTy->isVectorTy() ? cast<FixedVectorType>(RetTy)->getNumElements()
702                              : 1);
703     assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type");
704     const IntrinsicInst *I = ICA.getInst();
705     const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
706     FastMathFlags FMF = ICA.getFlags();
707     // Assume that we need to scalarize this intrinsic.
708     SmallVector<Type *, 4> Types;
709     for (const Value *Op : Args) {
710       Type *OpTy = Op->getType();
711       assert(VF == 1 || !OpTy->isVectorTy());
712       Types.push_back(VF == 1 ? OpTy : FixedVectorType::get(OpTy, VF));
713     }
714 
715     if (VF > 1 && !RetTy->isVoidTy())
716       RetTy = FixedVectorType::get(RetTy, VF);
717 
718     // Compute the scalarization overhead based on Args for a vector
719     // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
720     // CostModel will pass a vector RetTy and VF is 1.
721     unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
722     if (RetVF > 1 || VF > 1) {
723       ScalarizationCost = 0;
724       if (!RetTy->isVoidTy())
725         ScalarizationCost +=
726             getScalarizationOverhead(cast<VectorType>(RetTy), true, false);
727       ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
728     }
729 
730     IntrinsicCostAttributes Attrs(ICA.getID(), RetTy, Types, FMF,
731                                   ScalarizationCost, I);
732     return getIntrinsicInstrCost(Attrs, CostKind);
733   }
734 
735   // Legalize the type.
736   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
737 
738   unsigned NElts = LT.second.isVector() ?
739     LT.second.getVectorNumElements() : 1;
740 
741   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
742 
743   if (SLT == MVT::f64)
744     return LT.first * NElts * get64BitInstrCost(CostKind);
745 
746   if (ST->has16BitInsts() && SLT == MVT::f16)
747     NElts = (NElts + 1) / 2;
748 
749   // TODO: Get more refined intrinsic costs?
750   unsigned InstRate = getQuarterRateInstrCost(CostKind);
751   if (ICA.getID() == Intrinsic::fma) {
752     InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost(CostKind)
753                                    : getQuarterRateInstrCost(CostKind);
754   }
755 
756   return LT.first * NElts * InstRate;
757 }
758 
759 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode,
760                                     TTI::TargetCostKind CostKind) {
761   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency)
762     return Opcode == Instruction::PHI ? 0 : 1;
763 
764   // XXX - For some reason this isn't called for switch.
765   switch (Opcode) {
766   case Instruction::Br:
767   case Instruction::Ret:
768     return 10;
769   default:
770     return BaseT::getCFInstrCost(Opcode, CostKind);
771   }
772 }
773 
774 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
775                                            bool IsPairwise,
776                                            TTI::TargetCostKind CostKind) {
777   EVT OrigTy = TLI->getValueType(DL, Ty);
778 
779   // Computes cost on targets that have packed math instructions(which support
780   // 16-bit types only).
781   if (IsPairwise ||
782       !ST->hasVOP3PInsts() ||
783       OrigTy.getScalarSizeInBits() != 16)
784     return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise, CostKind);
785 
786   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
787   return LT.first * getFullRateInstrCost();
788 }
789 
790 int GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
791                                        bool IsPairwise, bool IsUnsigned,
792                                        TTI::TargetCostKind CostKind) {
793   EVT OrigTy = TLI->getValueType(DL, Ty);
794 
795   // Computes cost on targets that have packed math instructions(which support
796   // 16-bit types only).
797   if (IsPairwise ||
798       !ST->hasVOP3PInsts() ||
799       OrigTy.getScalarSizeInBits() != 16)
800     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned,
801                                          CostKind);
802 
803   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
804   return LT.first * getHalfRateInstrCost(CostKind);
805 }
806 
807 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
808                                       unsigned Index) {
809   switch (Opcode) {
810   case Instruction::ExtractElement:
811   case Instruction::InsertElement: {
812     unsigned EltSize
813       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
814     if (EltSize < 32) {
815       if (EltSize == 16 && Index == 0 && ST->has16BitInsts())
816         return 0;
817       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
818     }
819 
820     // Extracts are just reads of a subregister, so are free. Inserts are
821     // considered free because we don't want to have any cost for scalarizing
822     // operations, and we don't have to copy into a different register class.
823 
824     // Dynamic indexing isn't free and is best avoided.
825     return Index == ~0u ? 2 : 0;
826   }
827   default:
828     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
829   }
830 }
831 
832 static bool isArgPassedInSGPR(const Argument *A) {
833   const Function *F = A->getParent();
834 
835   // Arguments to compute shaders are never a source of divergence.
836   CallingConv::ID CC = F->getCallingConv();
837   switch (CC) {
838   case CallingConv::AMDGPU_KERNEL:
839   case CallingConv::SPIR_KERNEL:
840     return true;
841   case CallingConv::AMDGPU_VS:
842   case CallingConv::AMDGPU_LS:
843   case CallingConv::AMDGPU_HS:
844   case CallingConv::AMDGPU_ES:
845   case CallingConv::AMDGPU_GS:
846   case CallingConv::AMDGPU_PS:
847   case CallingConv::AMDGPU_CS:
848     // For non-compute shaders, SGPR inputs are marked with either inreg.
849     // Everything else is in VGPRs.
850     return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg);
851   default:
852     // TODO: Should calls support inreg for SGPR inputs?
853     return false;
854   }
855 }
856 
857 /// Analyze if the results of inline asm are divergent. If \p Indices is empty,
858 /// this is analyzing the collective result of all output registers. Otherwise,
859 /// this is only querying a specific result index if this returns multiple
860 /// registers in a struct.
861 bool GCNTTIImpl::isInlineAsmSourceOfDivergence(
862   const CallInst *CI, ArrayRef<unsigned> Indices) const {
863   // TODO: Handle complex extract indices
864   if (Indices.size() > 1)
865     return true;
866 
867   const DataLayout &DL = CI->getModule()->getDataLayout();
868   const SIRegisterInfo *TRI = ST->getRegisterInfo();
869   TargetLowering::AsmOperandInfoVector TargetConstraints =
870       TLI->ParseConstraints(DL, ST->getRegisterInfo(), *CI);
871 
872   const int TargetOutputIdx = Indices.empty() ? -1 : Indices[0];
873 
874   int OutputIdx = 0;
875   for (auto &TC : TargetConstraints) {
876     if (TC.Type != InlineAsm::isOutput)
877       continue;
878 
879     // Skip outputs we don't care about.
880     if (TargetOutputIdx != -1 && TargetOutputIdx != OutputIdx++)
881       continue;
882 
883     TLI->ComputeConstraintToUse(TC, SDValue());
884 
885     Register AssignedReg;
886     const TargetRegisterClass *RC;
887     std::tie(AssignedReg, RC) = TLI->getRegForInlineAsmConstraint(
888       TRI, TC.ConstraintCode, TC.ConstraintVT);
889     if (AssignedReg) {
890       // FIXME: This is a workaround for getRegForInlineAsmConstraint
891       // returning VS_32
892       RC = TRI->getPhysRegClass(AssignedReg);
893     }
894 
895     // For AGPR constraints null is returned on subtargets without AGPRs, so
896     // assume divergent for null.
897     if (!RC || !TRI->isSGPRClass(RC))
898       return true;
899   }
900 
901   return false;
902 }
903 
904 /// \returns true if the new GPU divergence analysis is enabled.
905 bool GCNTTIImpl::useGPUDivergenceAnalysis() const {
906   return !UseLegacyDA;
907 }
908 
909 /// \returns true if the result of the value could potentially be
910 /// different across workitems in a wavefront.
911 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const {
912   if (const Argument *A = dyn_cast<Argument>(V))
913     return !isArgPassedInSGPR(A);
914 
915   // Loads from the private and flat address spaces are divergent, because
916   // threads can execute the load instruction with the same inputs and get
917   // different results.
918   //
919   // All other loads are not divergent, because if threads issue loads with the
920   // same arguments, they will always get the same result.
921   if (const LoadInst *Load = dyn_cast<LoadInst>(V))
922     return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
923            Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS;
924 
925   // Atomics are divergent because they are executed sequentially: when an
926   // atomic operation refers to the same address in each thread, then each
927   // thread after the first sees the value written by the previous thread as
928   // original value.
929   if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V))
930     return true;
931 
932   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V))
933     return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID());
934 
935   // Assume all function calls are a source of divergence.
936   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
937     if (CI->isInlineAsm())
938       return isInlineAsmSourceOfDivergence(CI);
939     return true;
940   }
941 
942   // Assume all function calls are a source of divergence.
943   if (isa<InvokeInst>(V))
944     return true;
945 
946   return false;
947 }
948 
949 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const {
950   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
951     switch (Intrinsic->getIntrinsicID()) {
952     default:
953       return false;
954     case Intrinsic::amdgcn_readfirstlane:
955     case Intrinsic::amdgcn_readlane:
956     case Intrinsic::amdgcn_icmp:
957     case Intrinsic::amdgcn_fcmp:
958     case Intrinsic::amdgcn_ballot:
959     case Intrinsic::amdgcn_if_break:
960       return true;
961     }
962   }
963 
964   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
965     if (CI->isInlineAsm())
966       return !isInlineAsmSourceOfDivergence(CI);
967     return false;
968   }
969 
970   const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V);
971   if (!ExtValue)
972     return false;
973 
974   const CallInst *CI = dyn_cast<CallInst>(ExtValue->getOperand(0));
975   if (!CI)
976     return false;
977 
978   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(CI)) {
979     switch (Intrinsic->getIntrinsicID()) {
980     default:
981       return false;
982     case Intrinsic::amdgcn_if:
983     case Intrinsic::amdgcn_else: {
984       ArrayRef<unsigned> Indices = ExtValue->getIndices();
985       return Indices.size() == 1 && Indices[0] == 1;
986     }
987     }
988   }
989 
990   // If we have inline asm returning mixed SGPR and VGPR results, we inferred
991   // divergent for the overall struct return. We need to override it in the
992   // case we're extracting an SGPR component here.
993   if (CI->isInlineAsm())
994     return !isInlineAsmSourceOfDivergence(CI, ExtValue->getIndices());
995 
996   return false;
997 }
998 
999 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
1000                                             Intrinsic::ID IID) const {
1001   switch (IID) {
1002   case Intrinsic::amdgcn_atomic_inc:
1003   case Intrinsic::amdgcn_atomic_dec:
1004   case Intrinsic::amdgcn_ds_fadd:
1005   case Intrinsic::amdgcn_ds_fmin:
1006   case Intrinsic::amdgcn_ds_fmax:
1007   case Intrinsic::amdgcn_is_shared:
1008   case Intrinsic::amdgcn_is_private:
1009     OpIndexes.push_back(0);
1010     return true;
1011   default:
1012     return false;
1013   }
1014 }
1015 
1016 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
1017                                                     Value *OldV,
1018                                                     Value *NewV) const {
1019   auto IntrID = II->getIntrinsicID();
1020   switch (IntrID) {
1021   case Intrinsic::amdgcn_atomic_inc:
1022   case Intrinsic::amdgcn_atomic_dec:
1023   case Intrinsic::amdgcn_ds_fadd:
1024   case Intrinsic::amdgcn_ds_fmin:
1025   case Intrinsic::amdgcn_ds_fmax: {
1026     const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4));
1027     if (!IsVolatile->isZero())
1028       return nullptr;
1029     Module *M = II->getParent()->getParent()->getParent();
1030     Type *DestTy = II->getType();
1031     Type *SrcTy = NewV->getType();
1032     Function *NewDecl =
1033         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
1034     II->setArgOperand(0, NewV);
1035     II->setCalledFunction(NewDecl);
1036     return II;
1037   }
1038   case Intrinsic::amdgcn_is_shared:
1039   case Intrinsic::amdgcn_is_private: {
1040     unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ?
1041       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
1042     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1043     LLVMContext &Ctx = NewV->getType()->getContext();
1044     ConstantInt *NewVal = (TrueAS == NewAS) ?
1045       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
1046     return NewVal;
1047   }
1048   case Intrinsic::ptrmask: {
1049     unsigned OldAS = OldV->getType()->getPointerAddressSpace();
1050     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1051     Value *MaskOp = II->getArgOperand(1);
1052     Type *MaskTy = MaskOp->getType();
1053 
1054     bool DoTruncate = false;
1055 
1056     const GCNTargetMachine &TM =
1057         static_cast<const GCNTargetMachine &>(getTLI()->getTargetMachine());
1058     if (!TM.isNoopAddrSpaceCast(OldAS, NewAS)) {
1059       // All valid 64-bit to 32-bit casts work by chopping off the high
1060       // bits. Any masking only clearing the low bits will also apply in the new
1061       // address space.
1062       if (DL.getPointerSizeInBits(OldAS) != 64 ||
1063           DL.getPointerSizeInBits(NewAS) != 32)
1064         return nullptr;
1065 
1066       // TODO: Do we need to thread more context in here?
1067       KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II);
1068       if (Known.countMinLeadingOnes() < 32)
1069         return nullptr;
1070 
1071       DoTruncate = true;
1072     }
1073 
1074     IRBuilder<> B(II);
1075     if (DoTruncate) {
1076       MaskTy = B.getInt32Ty();
1077       MaskOp = B.CreateTrunc(MaskOp, MaskTy);
1078     }
1079 
1080     return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy},
1081                              {NewV, MaskOp});
1082   }
1083   default:
1084     return nullptr;
1085   }
1086 }
1087 
1088 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *VT,
1089                                     int Index, VectorType *SubTp) {
1090   if (ST->hasVOP3PInsts()) {
1091     if (cast<FixedVectorType>(VT)->getNumElements() == 2 &&
1092         DL.getTypeSizeInBits(VT->getElementType()) == 16) {
1093       // With op_sel VOP3P instructions freely can access the low half or high
1094       // half of a register, so any swizzle is free.
1095 
1096       switch (Kind) {
1097       case TTI::SK_Broadcast:
1098       case TTI::SK_Reverse:
1099       case TTI::SK_PermuteSingleSrc:
1100         return 0;
1101       default:
1102         break;
1103       }
1104     }
1105   }
1106 
1107   return BaseT::getShuffleCost(Kind, VT, Index, SubTp);
1108 }
1109 
1110 bool GCNTTIImpl::areInlineCompatible(const Function *Caller,
1111                                      const Function *Callee) const {
1112   const TargetMachine &TM = getTLI()->getTargetMachine();
1113   const GCNSubtarget *CallerST
1114     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller));
1115   const GCNSubtarget *CalleeST
1116     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee));
1117 
1118   const FeatureBitset &CallerBits = CallerST->getFeatureBits();
1119   const FeatureBitset &CalleeBits = CalleeST->getFeatureBits();
1120 
1121   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
1122   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
1123   if ((RealCallerBits & RealCalleeBits) != RealCalleeBits)
1124     return false;
1125 
1126   // FIXME: dx10_clamp can just take the caller setting, but there seems to be
1127   // no way to support merge for backend defined attributes.
1128   AMDGPU::SIModeRegisterDefaults CallerMode(*Caller);
1129   AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee);
1130   return CallerMode.isInlineCompatible(CalleeMode);
1131 }
1132 
1133 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1134                                          TTI::UnrollingPreferences &UP) {
1135   CommonTTI.getUnrollingPreferences(L, SE, UP);
1136 }
1137 
1138 void GCNTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1139                                        TTI::PeelingPreferences &PP) {
1140   CommonTTI.getPeelingPreferences(L, SE, PP);
1141 }
1142 
1143 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
1144   return 4 * 128; // XXX - 4 channels. Should these count as vector instead?
1145 }
1146 
1147 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const {
1148   return getHardwareNumberOfRegisters(Vec);
1149 }
1150 
1151 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const {
1152   return 32;
1153 }
1154 
1155 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const {
1156   return 32;
1157 }
1158 
1159 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
1160   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
1161       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS)
1162     return 128;
1163   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1164       AddrSpace == AMDGPUAS::REGION_ADDRESS)
1165     return 64;
1166   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
1167     return 32;
1168 
1169   if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS ||
1170       AddrSpace == AMDGPUAS::PARAM_I_ADDRESS ||
1171       (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 &&
1172       AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15)))
1173     return 128;
1174   llvm_unreachable("unhandled address space");
1175 }
1176 
1177 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
1178                                              Align Alignment,
1179                                              unsigned AddrSpace) const {
1180   // We allow vectorization of flat stores, even though we may need to decompose
1181   // them later if they may access private memory. We don't have enough context
1182   // here, and legalization can handle it.
1183   return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS);
1184 }
1185 
1186 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1187                                               Align Alignment,
1188                                               unsigned AddrSpace) const {
1189   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
1190 }
1191 
1192 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1193                                                Align Alignment,
1194                                                unsigned AddrSpace) const {
1195   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
1196 }
1197 
1198 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) {
1199   // Disable unrolling if the loop is not vectorized.
1200   // TODO: Enable this again.
1201   if (VF == 1)
1202     return 1;
1203 
1204   return 8;
1205 }
1206 
1207 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode,
1208                                      TTI::TargetCostKind CostKind) {
1209   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency)
1210     return Opcode == Instruction::PHI ? 0 : 1;
1211 
1212   // XXX - For some reason this isn't called for switch.
1213   switch (Opcode) {
1214   case Instruction::Br:
1215   case Instruction::Ret:
1216     return 10;
1217   default:
1218     return BaseT::getCFInstrCost(Opcode, CostKind);
1219   }
1220 }
1221 
1222 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
1223                                     unsigned Index) {
1224   switch (Opcode) {
1225   case Instruction::ExtractElement:
1226   case Instruction::InsertElement: {
1227     unsigned EltSize
1228       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
1229     if (EltSize < 32) {
1230       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
1231     }
1232 
1233     // Extracts are just reads of a subregister, so are free. Inserts are
1234     // considered free because we don't want to have any cost for scalarizing
1235     // operations, and we don't have to copy into a different register class.
1236 
1237     // Dynamic indexing isn't free and is best avoided.
1238     return Index == ~0u ? 2 : 0;
1239   }
1240   default:
1241     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
1242   }
1243 }
1244 
1245 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1246                                           TTI::UnrollingPreferences &UP) {
1247   CommonTTI.getUnrollingPreferences(L, SE, UP);
1248 }
1249 
1250 void R600TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1251                                         TTI::PeelingPreferences &PP) {
1252   CommonTTI.getPeelingPreferences(L, SE, PP);
1253 }
1254