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