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/MachineValueType.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include <algorithm>
49 #include <cassert>
50 #include <limits>
51 #include <utility>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "AMDGPUtti"
56 
57 static cl::opt<unsigned> UnrollThresholdPrivate(
58   "amdgpu-unroll-threshold-private",
59   cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"),
60   cl::init(2700), cl::Hidden);
61 
62 static cl::opt<unsigned> UnrollThresholdLocal(
63   "amdgpu-unroll-threshold-local",
64   cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"),
65   cl::init(1000), cl::Hidden);
66 
67 static cl::opt<unsigned> UnrollThresholdIf(
68   "amdgpu-unroll-threshold-if",
69   cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"),
70   cl::init(150), cl::Hidden);
71 
72 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond,
73                               unsigned Depth = 0) {
74   const Instruction *I = dyn_cast<Instruction>(Cond);
75   if (!I)
76     return false;
77 
78   for (const Value *V : I->operand_values()) {
79     if (!L->contains(I))
80       continue;
81     if (const PHINode *PHI = dyn_cast<PHINode>(V)) {
82       if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) {
83                   return SubLoop->contains(PHI); }))
84         return true;
85     } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1))
86       return true;
87   }
88   return false;
89 }
90 
91 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
92                                             TTI::UnrollingPreferences &UP) {
93   const Function &F = *L->getHeader()->getParent();
94   UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300);
95   UP.MaxCount = std::numeric_limits<unsigned>::max();
96   UP.Partial = true;
97 
98   // TODO: Do we want runtime unrolling?
99 
100   // Maximum alloca size than can fit registers. Reserve 16 registers.
101   const unsigned MaxAlloca = (256 - 16) * 4;
102   unsigned ThresholdPrivate = UnrollThresholdPrivate;
103   unsigned ThresholdLocal = UnrollThresholdLocal;
104   unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal);
105   for (const BasicBlock *BB : L->getBlocks()) {
106     const DataLayout &DL = BB->getModule()->getDataLayout();
107     unsigned LocalGEPsSeen = 0;
108 
109     if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) {
110                return SubLoop->contains(BB); }))
111         continue; // Block belongs to an inner loop.
112 
113     for (const Instruction &I : *BB) {
114       // Unroll a loop which contains an "if" statement whose condition
115       // defined by a PHI belonging to the loop. This may help to eliminate
116       // if region and potentially even PHI itself, saving on both divergence
117       // and registers used for the PHI.
118       // Add a small bonus for each of such "if" statements.
119       if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) {
120         if (UP.Threshold < MaxBoost && Br->isConditional()) {
121           BasicBlock *Succ0 = Br->getSuccessor(0);
122           BasicBlock *Succ1 = Br->getSuccessor(1);
123           if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) ||
124               (L->contains(Succ1) && L->isLoopExiting(Succ1)))
125             continue;
126           if (dependsOnLocalPhi(L, Br->getCondition())) {
127             UP.Threshold += UnrollThresholdIf;
128             LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold
129                               << " for loop:\n"
130                               << *L << " due to " << *Br << '\n');
131             if (UP.Threshold >= MaxBoost)
132               return;
133           }
134         }
135         continue;
136       }
137 
138       const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I);
139       if (!GEP)
140         continue;
141 
142       unsigned AS = GEP->getAddressSpace();
143       unsigned Threshold = 0;
144       if (AS == AMDGPUAS::PRIVATE_ADDRESS)
145         Threshold = ThresholdPrivate;
146       else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS)
147         Threshold = ThresholdLocal;
148       else
149         continue;
150 
151       if (UP.Threshold >= Threshold)
152         continue;
153 
154       if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
155         const Value *Ptr = GEP->getPointerOperand();
156         const AllocaInst *Alloca =
157             dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr, DL));
158         if (!Alloca || !Alloca->isStaticAlloca())
159           continue;
160         Type *Ty = Alloca->getAllocatedType();
161         unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0;
162         if (AllocaSize > MaxAlloca)
163           continue;
164       } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
165                  AS == AMDGPUAS::REGION_ADDRESS) {
166         LocalGEPsSeen++;
167         // Inhibit unroll for local memory if we have seen addressing not to
168         // a variable, most likely we will be unable to combine it.
169         // Do not unroll too deep inner loops for local memory to give a chance
170         // to unroll an outer loop for a more important reason.
171         if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 ||
172             (!isa<GlobalVariable>(GEP->getPointerOperand()) &&
173              !isa<Argument>(GEP->getPointerOperand())))
174           continue;
175       }
176 
177       // Check if GEP depends on a value defined by this loop itself.
178       bool HasLoopDef = false;
179       for (const Value *Op : GEP->operands()) {
180         const Instruction *Inst = dyn_cast<Instruction>(Op);
181         if (!Inst || L->isLoopInvariant(Op))
182           continue;
183 
184         if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) {
185              return SubLoop->contains(Inst); }))
186           continue;
187         HasLoopDef = true;
188         break;
189       }
190       if (!HasLoopDef)
191         continue;
192 
193       // We want to do whatever we can to limit the number of alloca
194       // instructions that make it through to the code generator.  allocas
195       // require us to use indirect addressing, which is slow and prone to
196       // compiler bugs.  If this loop does an address calculation on an
197       // alloca ptr, then we want to use a higher than normal loop unroll
198       // threshold. This will give SROA a better chance to eliminate these
199       // allocas.
200       //
201       // We also want to have more unrolling for local memory to let ds
202       // instructions with different offsets combine.
203       //
204       // Don't use the maximum allowed value here as it will make some
205       // programs way too big.
206       UP.Threshold = Threshold;
207       LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold
208                         << " for loop:\n"
209                         << *L << " due to " << *GEP << '\n');
210       if (UP.Threshold >= MaxBoost)
211         return;
212     }
213   }
214 }
215 
216 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
217   // The concept of vector registers doesn't really exist. Some packed vector
218   // operations operate on the normal 32-bit registers.
219   return 256;
220 }
221 
222 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const {
223   // This is really the number of registers to fill when vectorizing /
224   // interleaving loops, so we lie to avoid trying to use all registers.
225   return getHardwareNumberOfRegisters(Vec) >> 3;
226 }
227 
228 unsigned GCNTTIImpl::getRegisterBitWidth(bool Vector) const {
229   return 32;
230 }
231 
232 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const {
233   return 32;
234 }
235 
236 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize,
237                                             unsigned ChainSizeInBytes,
238                                             VectorType *VecTy) const {
239   unsigned VecRegBitWidth = VF * LoadSize;
240   if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32)
241     // TODO: Support element-size less than 32bit?
242     return 128 / LoadSize;
243 
244   return VF;
245 }
246 
247 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize,
248                                              unsigned ChainSizeInBytes,
249                                              VectorType *VecTy) const {
250   unsigned VecRegBitWidth = VF * StoreSize;
251   if (VecRegBitWidth > 128)
252     return 128 / StoreSize;
253 
254   return VF;
255 }
256 
257 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
258   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
259       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
260       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
261       AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) {
262     return 512;
263   }
264 
265   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS ||
266       AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
267       AddrSpace == AMDGPUAS::REGION_ADDRESS)
268     return 128;
269 
270   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
271     return 8 * ST->getMaxPrivateElementSize();
272 
273   llvm_unreachable("unhandled address space");
274 }
275 
276 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
277                                                unsigned Alignment,
278                                                unsigned AddrSpace) const {
279   // We allow vectorization of flat stores, even though we may need to decompose
280   // them later if they may access private memory. We don't have enough context
281   // here, and legalization can handle it.
282   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
283     return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) &&
284       ChainSizeInBytes <= ST->getMaxPrivateElementSize();
285   }
286   return true;
287 }
288 
289 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
290                                                 unsigned Alignment,
291                                                 unsigned AddrSpace) const {
292   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
293 }
294 
295 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
296                                                  unsigned Alignment,
297                                                  unsigned AddrSpace) const {
298   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
299 }
300 
301 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) {
302   // Disable unrolling if the loop is not vectorized.
303   // TODO: Enable this again.
304   if (VF == 1)
305     return 1;
306 
307   return 8;
308 }
309 
310 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
311                                        MemIntrinsicInfo &Info) const {
312   switch (Inst->getIntrinsicID()) {
313   case Intrinsic::amdgcn_atomic_inc:
314   case Intrinsic::amdgcn_atomic_dec:
315   case Intrinsic::amdgcn_ds_ordered_add:
316   case Intrinsic::amdgcn_ds_ordered_swap:
317   case Intrinsic::amdgcn_ds_fadd:
318   case Intrinsic::amdgcn_ds_fmin:
319   case Intrinsic::amdgcn_ds_fmax: {
320     auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2));
321     auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4));
322     if (!Ordering || !Volatile)
323       return false; // Invalid.
324 
325     unsigned OrderingVal = Ordering->getZExtValue();
326     if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent))
327       return false;
328 
329     Info.PtrVal = Inst->getArgOperand(0);
330     Info.Ordering = static_cast<AtomicOrdering>(OrderingVal);
331     Info.ReadMem = true;
332     Info.WriteMem = true;
333     Info.IsVolatile = !Volatile->isNullValue();
334     return true;
335   }
336   default:
337     return false;
338   }
339 }
340 
341 int GCNTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
342                                        TTI::OperandValueKind Opd1Info,
343                                        TTI::OperandValueKind Opd2Info,
344                                        TTI::OperandValueProperties Opd1PropInfo,
345                                        TTI::OperandValueProperties Opd2PropInfo,
346                                        ArrayRef<const Value *> Args,
347                                        const Instruction *CxtI) {
348   EVT OrigTy = TLI->getValueType(DL, Ty);
349   if (!OrigTy.isSimple()) {
350     return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
351                                          Opd1PropInfo, Opd2PropInfo);
352   }
353 
354   // Legalize the type.
355   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
356   int ISD = TLI->InstructionOpcodeToISD(Opcode);
357 
358   // Because we don't have any legal vector operations, but the legal types, we
359   // need to account for split vectors.
360   unsigned NElts = LT.second.isVector() ?
361     LT.second.getVectorNumElements() : 1;
362 
363   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
364 
365   switch (ISD) {
366   case ISD::SHL:
367   case ISD::SRL:
368   case ISD::SRA:
369     if (SLT == MVT::i64)
370       return get64BitInstrCost() * LT.first * NElts;
371 
372     // i32
373     return getFullRateInstrCost() * LT.first * NElts;
374   case ISD::ADD:
375   case ISD::SUB:
376   case ISD::AND:
377   case ISD::OR:
378   case ISD::XOR:
379     if (SLT == MVT::i64){
380       // and, or and xor are typically split into 2 VALU instructions.
381       return 2 * getFullRateInstrCost() * LT.first * NElts;
382     }
383 
384     return LT.first * NElts * getFullRateInstrCost();
385   case ISD::MUL: {
386     const int QuarterRateCost = getQuarterRateInstrCost();
387     if (SLT == MVT::i64) {
388       const int FullRateCost = getFullRateInstrCost();
389       return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts;
390     }
391 
392     // i32
393     return QuarterRateCost * NElts * LT.first;
394   }
395   case ISD::FADD:
396   case ISD::FSUB:
397   case ISD::FMUL:
398     if (SLT == MVT::f64)
399       return LT.first * NElts * get64BitInstrCost();
400 
401     if (SLT == MVT::f32 || SLT == MVT::f16)
402       return LT.first * NElts * getFullRateInstrCost();
403     break;
404   case ISD::FDIV:
405   case ISD::FREM:
406     // FIXME: frem should be handled separately. The fdiv in it is most of it,
407     // but the current lowering is also not entirely correct.
408     if (SLT == MVT::f64) {
409       int Cost = 4 * get64BitInstrCost() + 7 * getQuarterRateInstrCost();
410       // Add cost of workaround.
411       if (!ST->hasUsableDivScaleConditionOutput())
412         Cost += 3 * getFullRateInstrCost();
413 
414       return LT.first * Cost * NElts;
415     }
416 
417     if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) {
418       // TODO: This is more complicated, unsafe flags etc.
419       if ((SLT == MVT::f32 && !HasFP32Denormals) ||
420           (SLT == MVT::f16 && ST->has16BitInsts())) {
421         return LT.first * getQuarterRateInstrCost() * NElts;
422       }
423     }
424 
425     if (SLT == MVT::f16 && ST->has16BitInsts()) {
426       // 2 x v_cvt_f32_f16
427       // f32 rcp
428       // f32 fmul
429       // v_cvt_f16_f32
430       // f16 div_fixup
431       int Cost = 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost();
432       return LT.first * Cost * NElts;
433     }
434 
435     if (SLT == MVT::f32 || SLT == MVT::f16) {
436       int Cost = 7 * getFullRateInstrCost() + 1 * getQuarterRateInstrCost();
437 
438       if (!HasFP32Denormals) {
439         // FP mode switches.
440         Cost += 2 * getFullRateInstrCost();
441       }
442 
443       return LT.first * NElts * Cost;
444     }
445     break;
446   default:
447     break;
448   }
449 
450   return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
451                                        Opd1PropInfo, Opd2PropInfo);
452 }
453 
454 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode) {
455   // XXX - For some reason this isn't called for switch.
456   switch (Opcode) {
457   case Instruction::Br:
458   case Instruction::Ret:
459     return 10;
460   default:
461     return BaseT::getCFInstrCost(Opcode);
462   }
463 }
464 
465 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, Type *Ty,
466                                               bool IsPairwise) {
467   EVT OrigTy = TLI->getValueType(DL, Ty);
468 
469   // Computes cost on targets that have packed math instructions(which support
470   // 16-bit types only).
471   if (IsPairwise ||
472       !ST->hasVOP3PInsts() ||
473       OrigTy.getScalarSizeInBits() != 16)
474     return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise);
475 
476   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
477   return LT.first * getFullRateInstrCost();
478 }
479 
480 int GCNTTIImpl::getMinMaxReductionCost(Type *Ty, Type *CondTy,
481                                           bool IsPairwise,
482                                           bool IsUnsigned) {
483   EVT OrigTy = TLI->getValueType(DL, Ty);
484 
485   // Computes cost on targets that have packed math instructions(which support
486   // 16-bit types only).
487   if (IsPairwise ||
488       !ST->hasVOP3PInsts() ||
489       OrigTy.getScalarSizeInBits() != 16)
490     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned);
491 
492   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
493   return LT.first * getHalfRateInstrCost();
494 }
495 
496 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
497                                       unsigned Index) {
498   switch (Opcode) {
499   case Instruction::ExtractElement:
500   case Instruction::InsertElement: {
501     unsigned EltSize
502       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
503     if (EltSize < 32) {
504       if (EltSize == 16 && Index == 0 && ST->has16BitInsts())
505         return 0;
506       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
507     }
508 
509     // Extracts are just reads of a subregister, so are free. Inserts are
510     // considered free because we don't want to have any cost for scalarizing
511     // operations, and we don't have to copy into a different register class.
512 
513     // Dynamic indexing isn't free and is best avoided.
514     return Index == ~0u ? 2 : 0;
515   }
516   default:
517     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
518   }
519 }
520 
521 
522 
523 static bool isArgPassedInSGPR(const Argument *A) {
524   const Function *F = A->getParent();
525 
526   // Arguments to compute shaders are never a source of divergence.
527   CallingConv::ID CC = F->getCallingConv();
528   switch (CC) {
529   case CallingConv::AMDGPU_KERNEL:
530   case CallingConv::SPIR_KERNEL:
531     return true;
532   case CallingConv::AMDGPU_VS:
533   case CallingConv::AMDGPU_LS:
534   case CallingConv::AMDGPU_HS:
535   case CallingConv::AMDGPU_ES:
536   case CallingConv::AMDGPU_GS:
537   case CallingConv::AMDGPU_PS:
538   case CallingConv::AMDGPU_CS:
539     // For non-compute shaders, SGPR inputs are marked with either inreg or byval.
540     // Everything else is in VGPRs.
541     return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg) ||
542            F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::ByVal);
543   default:
544     // TODO: Should calls support inreg for SGPR inputs?
545     return false;
546   }
547 }
548 
549 /// \returns true if the result of the value could potentially be
550 /// different across workitems in a wavefront.
551 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const {
552   if (const Argument *A = dyn_cast<Argument>(V))
553     return !isArgPassedInSGPR(A);
554 
555   // Loads from the private and flat address spaces are divergent, because
556   // threads can execute the load instruction with the same inputs and get
557   // different results.
558   //
559   // All other loads are not divergent, because if threads issue loads with the
560   // same arguments, they will always get the same result.
561   if (const LoadInst *Load = dyn_cast<LoadInst>(V))
562     return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
563            Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS;
564 
565   // Atomics are divergent because they are executed sequentially: when an
566   // atomic operation refers to the same address in each thread, then each
567   // thread after the first sees the value written by the previous thread as
568   // original value.
569   if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V))
570     return true;
571 
572   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V))
573     return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID());
574 
575   // Assume all function calls are a source of divergence.
576   if (isa<CallInst>(V) || isa<InvokeInst>(V))
577     return true;
578 
579   return false;
580 }
581 
582 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const {
583   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
584     switch (Intrinsic->getIntrinsicID()) {
585     default:
586       return false;
587     case Intrinsic::amdgcn_readfirstlane:
588     case Intrinsic::amdgcn_readlane:
589     case Intrinsic::amdgcn_icmp:
590     case Intrinsic::amdgcn_fcmp:
591       return true;
592     }
593   }
594   return false;
595 }
596 
597 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
598                                             Intrinsic::ID IID) const {
599   switch (IID) {
600   case Intrinsic::amdgcn_atomic_inc:
601   case Intrinsic::amdgcn_atomic_dec:
602   case Intrinsic::amdgcn_ds_fadd:
603   case Intrinsic::amdgcn_ds_fmin:
604   case Intrinsic::amdgcn_ds_fmax:
605   case Intrinsic::amdgcn_is_shared:
606   case Intrinsic::amdgcn_is_private:
607     OpIndexes.push_back(0);
608     return true;
609   default:
610     return false;
611   }
612 }
613 
614 bool GCNTTIImpl::rewriteIntrinsicWithAddressSpace(
615   IntrinsicInst *II, Value *OldV, Value *NewV) const {
616   auto IntrID = II->getIntrinsicID();
617   switch (IntrID) {
618   case Intrinsic::amdgcn_atomic_inc:
619   case Intrinsic::amdgcn_atomic_dec:
620   case Intrinsic::amdgcn_ds_fadd:
621   case Intrinsic::amdgcn_ds_fmin:
622   case Intrinsic::amdgcn_ds_fmax: {
623     const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4));
624     if (!IsVolatile->isZero())
625       return false;
626     Module *M = II->getParent()->getParent()->getParent();
627     Type *DestTy = II->getType();
628     Type *SrcTy = NewV->getType();
629     Function *NewDecl =
630         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
631     II->setArgOperand(0, NewV);
632     II->setCalledFunction(NewDecl);
633     return true;
634   }
635   case Intrinsic::amdgcn_is_shared:
636   case Intrinsic::amdgcn_is_private: {
637     unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ?
638       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
639     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
640     LLVMContext &Ctx = NewV->getType()->getContext();
641     ConstantInt *NewVal = (TrueAS == NewAS) ?
642       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
643     II->replaceAllUsesWith(NewVal);
644     II->eraseFromParent();
645     return true;
646   }
647   default:
648     return false;
649   }
650 }
651 
652 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
653                                        Type *SubTp) {
654   if (ST->hasVOP3PInsts()) {
655     VectorType *VT = cast<VectorType>(Tp);
656     if (VT->getNumElements() == 2 &&
657         DL.getTypeSizeInBits(VT->getElementType()) == 16) {
658       // With op_sel VOP3P instructions freely can access the low half or high
659       // half of a register, so any swizzle is free.
660 
661       switch (Kind) {
662       case TTI::SK_Broadcast:
663       case TTI::SK_Reverse:
664       case TTI::SK_PermuteSingleSrc:
665         return 0;
666       default:
667         break;
668       }
669     }
670   }
671 
672   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
673 }
674 
675 bool GCNTTIImpl::areInlineCompatible(const Function *Caller,
676                                      const Function *Callee) const {
677   const TargetMachine &TM = getTLI()->getTargetMachine();
678   const GCNSubtarget *CallerST
679     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller));
680   const GCNSubtarget *CalleeST
681     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee));
682 
683   const FeatureBitset &CallerBits = CallerST->getFeatureBits();
684   const FeatureBitset &CalleeBits = CalleeST->getFeatureBits();
685 
686   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
687   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
688   if ((RealCallerBits & RealCalleeBits) != RealCalleeBits)
689     return false;
690 
691   // FIXME: dx10_clamp can just take the caller setting, but there seems to be
692   // no way to support merge for backend defined attributes.
693   AMDGPU::SIModeRegisterDefaults CallerMode(*Caller, *CallerST);
694   AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee, *CalleeST);
695   return CallerMode.isInlineCompatible(CalleeMode);
696 }
697 
698 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
699                                          TTI::UnrollingPreferences &UP) {
700   CommonTTI.getUnrollingPreferences(L, SE, UP);
701 }
702 
703 unsigned GCNTTIImpl::getUserCost(const User *U,
704                                  ArrayRef<const Value *> Operands) {
705   const Instruction *I = dyn_cast<Instruction>(U);
706   if (!I)
707     return BaseT::getUserCost(U, Operands);
708 
709   // Estimate different operations to be optimized out
710   switch (I->getOpcode()) {
711   case Instruction::ExtractElement: {
712     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
713     unsigned Idx = -1;
714     if (CI)
715       Idx = CI->getZExtValue();
716     return getVectorInstrCost(I->getOpcode(), I->getOperand(0)->getType(), Idx);
717   }
718   case Instruction::InsertElement: {
719     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
720     unsigned Idx = -1;
721     if (CI)
722       Idx = CI->getZExtValue();
723     return getVectorInstrCost(I->getOpcode(), I->getType(), Idx);
724   }
725   case Instruction::Call: {
726     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
727       SmallVector<Value *, 4> Args(II->arg_operands());
728       FastMathFlags FMF;
729       if (auto *FPMO = dyn_cast<FPMathOperator>(II))
730         FMF = FPMO->getFastMathFlags();
731       return getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(), Args,
732                                    FMF);
733     } else {
734       return BaseT::getUserCost(U, Operands);
735     }
736   }
737   case Instruction::ShuffleVector: {
738     const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
739     Type *Ty = Shuffle->getType();
740     Type *SrcTy = Shuffle->getOperand(0)->getType();
741 
742     // TODO: Identify and add costs for insert subvector, etc.
743     int SubIndex;
744     if (Shuffle->isExtractSubvectorMask(SubIndex))
745       return getShuffleCost(TTI::SK_ExtractSubvector, SrcTy, SubIndex, Ty);
746 
747     if (Shuffle->changesLength())
748       return BaseT::getUserCost(U, Operands);
749 
750     if (Shuffle->isIdentity())
751       return 0;
752 
753     if (Shuffle->isReverse())
754       return getShuffleCost(TTI::SK_Reverse, Ty, 0, nullptr);
755 
756     if (Shuffle->isSelect())
757       return getShuffleCost(TTI::SK_Select, Ty, 0, nullptr);
758 
759     if (Shuffle->isTranspose())
760       return getShuffleCost(TTI::SK_Transpose, Ty, 0, nullptr);
761 
762     if (Shuffle->isZeroEltSplat())
763       return getShuffleCost(TTI::SK_Broadcast, Ty, 0, nullptr);
764 
765     if (Shuffle->isSingleSource())
766       return getShuffleCost(TTI::SK_PermuteSingleSrc, Ty, 0, nullptr);
767 
768     return getShuffleCost(TTI::SK_PermuteTwoSrc, Ty, 0, nullptr);
769   }
770   case Instruction::ZExt:
771   case Instruction::SExt:
772   case Instruction::FPToUI:
773   case Instruction::FPToSI:
774   case Instruction::FPExt:
775   case Instruction::PtrToInt:
776   case Instruction::IntToPtr:
777   case Instruction::SIToFP:
778   case Instruction::UIToFP:
779   case Instruction::Trunc:
780   case Instruction::FPTrunc:
781   case Instruction::BitCast:
782   case Instruction::AddrSpaceCast: {
783     return getCastInstrCost(I->getOpcode(), I->getType(),
784                             I->getOperand(0)->getType(), I);
785   }
786   case Instruction::Add:
787   case Instruction::FAdd:
788   case Instruction::Sub:
789   case Instruction::FSub:
790   case Instruction::Mul:
791   case Instruction::FMul:
792   case Instruction::UDiv:
793   case Instruction::SDiv:
794   case Instruction::FDiv:
795   case Instruction::URem:
796   case Instruction::SRem:
797   case Instruction::FRem:
798   case Instruction::Shl:
799   case Instruction::LShr:
800   case Instruction::AShr:
801   case Instruction::And:
802   case Instruction::Or:
803   case Instruction::Xor:
804   case Instruction::FNeg: {
805     return getArithmeticInstrCost(I->getOpcode(), I->getType(),
806                                   TTI::OK_AnyValue, TTI::OK_AnyValue,
807                                   TTI::OP_None, TTI::OP_None, Operands, I);
808   }
809   default:
810     break;
811   }
812 
813   return BaseT::getUserCost(U, Operands);
814 }
815 
816 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
817   return 4 * 128; // XXX - 4 channels. Should these count as vector instead?
818 }
819 
820 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const {
821   return getHardwareNumberOfRegisters(Vec);
822 }
823 
824 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const {
825   return 32;
826 }
827 
828 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const {
829   return 32;
830 }
831 
832 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
833   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
834       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS)
835     return 128;
836   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
837       AddrSpace == AMDGPUAS::REGION_ADDRESS)
838     return 64;
839   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
840     return 32;
841 
842   if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS ||
843       AddrSpace == AMDGPUAS::PARAM_I_ADDRESS ||
844       (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 &&
845       AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15)))
846     return 128;
847   llvm_unreachable("unhandled address space");
848 }
849 
850 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
851                                              unsigned Alignment,
852                                              unsigned AddrSpace) const {
853   // We allow vectorization of flat stores, even though we may need to decompose
854   // them later if they may access private memory. We don't have enough context
855   // here, and legalization can handle it.
856   return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS);
857 }
858 
859 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
860                                               unsigned Alignment,
861                                               unsigned AddrSpace) const {
862   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
863 }
864 
865 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
866                                                unsigned Alignment,
867                                                unsigned AddrSpace) const {
868   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
869 }
870 
871 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) {
872   // Disable unrolling if the loop is not vectorized.
873   // TODO: Enable this again.
874   if (VF == 1)
875     return 1;
876 
877   return 8;
878 }
879 
880 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode) {
881   // XXX - For some reason this isn't called for switch.
882   switch (Opcode) {
883   case Instruction::Br:
884   case Instruction::Ret:
885     return 10;
886   default:
887     return BaseT::getCFInstrCost(Opcode);
888   }
889 }
890 
891 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
892                                     unsigned Index) {
893   switch (Opcode) {
894   case Instruction::ExtractElement:
895   case Instruction::InsertElement: {
896     unsigned EltSize
897       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
898     if (EltSize < 32) {
899       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
900     }
901 
902     // Extracts are just reads of a subregister, so are free. Inserts are
903     // considered free because we don't want to have any cost for scalarizing
904     // operations, and we don't have to copy into a different register class.
905 
906     // Dynamic indexing isn't free and is best avoided.
907     return Index == ~0u ? 2 : 0;
908   }
909   default:
910     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
911   }
912 }
913 
914 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
915                                           TTI::UnrollingPreferences &UP) {
916   CommonTTI.getUnrollingPreferences(L, SE, UP);
917 }
918