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