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