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                                             Align 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                                              Align Alignment,
310                                              unsigned AddrSpace) const {
311   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
312 }
313 
314 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
315                                               Align 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   case ISD::FNEG:
553     // Use the backend' estimation. If fneg is not free each element will cost
554     // one additional instruction.
555     return TLI->isFNegFree(SLT) ? 0 : NElts;
556   default:
557     break;
558   }
559 
560   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
561                                        Opd2Info,
562                                        Opd1PropInfo, Opd2PropInfo);
563 }
564 
565 // Return true if there's a potential benefit from using v2f16 instructions for
566 // an intrinsic, even if it requires nontrivial legalization.
567 static bool intrinsicHasPackedVectorBenefit(Intrinsic::ID ID) {
568   switch (ID) {
569   case Intrinsic::fma: // TODO: fmuladd
570   // There's a small benefit to using vector ops in the legalized code.
571   case Intrinsic::round:
572     return true;
573   default:
574     return false;
575   }
576 }
577 
578 int GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
579                                       TTI::TargetCostKind CostKind) {
580   if (ICA.getID() == Intrinsic::fabs)
581     return 0;
582 
583   if (!intrinsicHasPackedVectorBenefit(ICA.getID()))
584     return BaseT::getIntrinsicInstrCost(ICA, CostKind);
585 
586   Type *RetTy = ICA.getReturnType();
587   EVT OrigTy = TLI->getValueType(DL, RetTy);
588   if (!OrigTy.isSimple()) {
589     return BaseT::getIntrinsicInstrCost(ICA, CostKind);
590   }
591 
592   // Legalize the type.
593   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
594 
595   unsigned NElts = LT.second.isVector() ?
596     LT.second.getVectorNumElements() : 1;
597 
598   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
599 
600   if (SLT == MVT::f64)
601     return LT.first * NElts * get64BitInstrCost();
602 
603   if (ST->has16BitInsts() && SLT == MVT::f16)
604     NElts = (NElts + 1) / 2;
605 
606   // TODO: Get more refined intrinsic costs?
607   unsigned InstRate = getQuarterRateInstrCost();
608   if (ICA.getID() == Intrinsic::fma) {
609     InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost()
610                                    : getQuarterRateInstrCost();
611   }
612 
613   return LT.first * NElts * InstRate;
614 }
615 
616 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode,
617                                     TTI::TargetCostKind CostKind) {
618   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency)
619     return Opcode == Instruction::PHI ? 0 : 1;
620 
621   // XXX - For some reason this isn't called for switch.
622   switch (Opcode) {
623   case Instruction::Br:
624   case Instruction::Ret:
625     return 10;
626   default:
627     return BaseT::getCFInstrCost(Opcode, CostKind);
628   }
629 }
630 
631 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
632                                            bool IsPairwise,
633                                            TTI::TargetCostKind CostKind) {
634   EVT OrigTy = TLI->getValueType(DL, Ty);
635 
636   // Computes cost on targets that have packed math instructions(which support
637   // 16-bit types only).
638   if (IsPairwise ||
639       !ST->hasVOP3PInsts() ||
640       OrigTy.getScalarSizeInBits() != 16)
641     return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise, CostKind);
642 
643   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
644   return LT.first * getFullRateInstrCost();
645 }
646 
647 int GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
648                                        bool IsPairwise, bool IsUnsigned,
649                                        TTI::TargetCostKind CostKind) {
650   EVT OrigTy = TLI->getValueType(DL, Ty);
651 
652   // Computes cost on targets that have packed math instructions(which support
653   // 16-bit types only).
654   if (IsPairwise ||
655       !ST->hasVOP3PInsts() ||
656       OrigTy.getScalarSizeInBits() != 16)
657     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned,
658                                          CostKind);
659 
660   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
661   return LT.first * getHalfRateInstrCost();
662 }
663 
664 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
665                                       unsigned Index) {
666   switch (Opcode) {
667   case Instruction::ExtractElement:
668   case Instruction::InsertElement: {
669     unsigned EltSize
670       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
671     if (EltSize < 32) {
672       if (EltSize == 16 && Index == 0 && ST->has16BitInsts())
673         return 0;
674       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
675     }
676 
677     // Extracts are just reads of a subregister, so are free. Inserts are
678     // considered free because we don't want to have any cost for scalarizing
679     // operations, and we don't have to copy into a different register class.
680 
681     // Dynamic indexing isn't free and is best avoided.
682     return Index == ~0u ? 2 : 0;
683   }
684   default:
685     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
686   }
687 }
688 
689 static bool isArgPassedInSGPR(const Argument *A) {
690   const Function *F = A->getParent();
691 
692   // Arguments to compute shaders are never a source of divergence.
693   CallingConv::ID CC = F->getCallingConv();
694   switch (CC) {
695   case CallingConv::AMDGPU_KERNEL:
696   case CallingConv::SPIR_KERNEL:
697     return true;
698   case CallingConv::AMDGPU_VS:
699   case CallingConv::AMDGPU_LS:
700   case CallingConv::AMDGPU_HS:
701   case CallingConv::AMDGPU_ES:
702   case CallingConv::AMDGPU_GS:
703   case CallingConv::AMDGPU_PS:
704   case CallingConv::AMDGPU_CS:
705     // For non-compute shaders, SGPR inputs are marked with either inreg or byval.
706     // Everything else is in VGPRs.
707     return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg) ||
708            F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::ByVal);
709   default:
710     // TODO: Should calls support inreg for SGPR inputs?
711     return false;
712   }
713 }
714 
715 /// Analyze if the results of inline asm are divergent. If \p Indices is empty,
716 /// this is analyzing the collective result of all output registers. Otherwise,
717 /// this is only querying a specific result index if this returns multiple
718 /// registers in a struct.
719 bool GCNTTIImpl::isInlineAsmSourceOfDivergence(
720   const CallInst *CI, ArrayRef<unsigned> Indices) const {
721   // TODO: Handle complex extract indices
722   if (Indices.size() > 1)
723     return true;
724 
725   const DataLayout &DL = CI->getModule()->getDataLayout();
726   const SIRegisterInfo *TRI = ST->getRegisterInfo();
727   TargetLowering::AsmOperandInfoVector TargetConstraints =
728       TLI->ParseConstraints(DL, ST->getRegisterInfo(), *CI);
729 
730   const int TargetOutputIdx = Indices.empty() ? -1 : Indices[0];
731 
732   int OutputIdx = 0;
733   for (auto &TC : TargetConstraints) {
734     if (TC.Type != InlineAsm::isOutput)
735       continue;
736 
737     // Skip outputs we don't care about.
738     if (TargetOutputIdx != -1 && TargetOutputIdx != OutputIdx++)
739       continue;
740 
741     TLI->ComputeConstraintToUse(TC, SDValue());
742 
743     Register AssignedReg;
744     const TargetRegisterClass *RC;
745     std::tie(AssignedReg, RC) = TLI->getRegForInlineAsmConstraint(
746       TRI, TC.ConstraintCode, TC.ConstraintVT);
747     if (AssignedReg) {
748       // FIXME: This is a workaround for getRegForInlineAsmConstraint
749       // returning VS_32
750       RC = TRI->getPhysRegClass(AssignedReg);
751     }
752 
753     // For AGPR constraints null is returned on subtargets without AGPRs, so
754     // assume divergent for null.
755     if (!RC || !TRI->isSGPRClass(RC))
756       return true;
757   }
758 
759   return false;
760 }
761 
762 /// \returns true if the new GPU divergence analysis is enabled.
763 bool GCNTTIImpl::useGPUDivergenceAnalysis() const {
764   return !UseLegacyDA;
765 }
766 
767 /// \returns true if the result of the value could potentially be
768 /// different across workitems in a wavefront.
769 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const {
770   if (const Argument *A = dyn_cast<Argument>(V))
771     return !isArgPassedInSGPR(A);
772 
773   // Loads from the private and flat address spaces are divergent, because
774   // threads can execute the load instruction with the same inputs and get
775   // different results.
776   //
777   // All other loads are not divergent, because if threads issue loads with the
778   // same arguments, they will always get the same result.
779   if (const LoadInst *Load = dyn_cast<LoadInst>(V))
780     return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
781            Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS;
782 
783   // Atomics are divergent because they are executed sequentially: when an
784   // atomic operation refers to the same address in each thread, then each
785   // thread after the first sees the value written by the previous thread as
786   // original value.
787   if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V))
788     return true;
789 
790   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V))
791     return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID());
792 
793   // Assume all function calls are a source of divergence.
794   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
795     if (CI->isInlineAsm())
796       return isInlineAsmSourceOfDivergence(CI);
797     return true;
798   }
799 
800   // Assume all function calls are a source of divergence.
801   if (isa<InvokeInst>(V))
802     return true;
803 
804   return false;
805 }
806 
807 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const {
808   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
809     switch (Intrinsic->getIntrinsicID()) {
810     default:
811       return false;
812     case Intrinsic::amdgcn_readfirstlane:
813     case Intrinsic::amdgcn_readlane:
814     case Intrinsic::amdgcn_icmp:
815     case Intrinsic::amdgcn_fcmp:
816     case Intrinsic::amdgcn_ballot:
817     case Intrinsic::amdgcn_if_break:
818       return true;
819     }
820   }
821 
822   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
823     if (CI->isInlineAsm())
824       return !isInlineAsmSourceOfDivergence(CI);
825     return false;
826   }
827 
828   const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V);
829   if (!ExtValue)
830     return false;
831 
832   const CallInst *CI = dyn_cast<CallInst>(ExtValue->getOperand(0));
833   if (!CI)
834     return false;
835 
836   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(CI)) {
837     switch (Intrinsic->getIntrinsicID()) {
838     default:
839       return false;
840     case Intrinsic::amdgcn_if:
841     case Intrinsic::amdgcn_else: {
842       ArrayRef<unsigned> Indices = ExtValue->getIndices();
843       return Indices.size() == 1 && Indices[0] == 1;
844     }
845     }
846   }
847 
848   // If we have inline asm returning mixed SGPR and VGPR results, we inferred
849   // divergent for the overall struct return. We need to override it in the
850   // case we're extracting an SGPR component here.
851   if (CI->isInlineAsm())
852     return !isInlineAsmSourceOfDivergence(CI, ExtValue->getIndices());
853 
854   return false;
855 }
856 
857 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
858                                             Intrinsic::ID IID) const {
859   switch (IID) {
860   case Intrinsic::amdgcn_atomic_inc:
861   case Intrinsic::amdgcn_atomic_dec:
862   case Intrinsic::amdgcn_ds_fadd:
863   case Intrinsic::amdgcn_ds_fmin:
864   case Intrinsic::amdgcn_ds_fmax:
865   case Intrinsic::amdgcn_is_shared:
866   case Intrinsic::amdgcn_is_private:
867     OpIndexes.push_back(0);
868     return true;
869   default:
870     return false;
871   }
872 }
873 
874 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
875                                                     Value *OldV,
876                                                     Value *NewV) const {
877   auto IntrID = II->getIntrinsicID();
878   switch (IntrID) {
879   case Intrinsic::amdgcn_atomic_inc:
880   case Intrinsic::amdgcn_atomic_dec:
881   case Intrinsic::amdgcn_ds_fadd:
882   case Intrinsic::amdgcn_ds_fmin:
883   case Intrinsic::amdgcn_ds_fmax: {
884     const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4));
885     if (!IsVolatile->isZero())
886       return nullptr;
887     Module *M = II->getParent()->getParent()->getParent();
888     Type *DestTy = II->getType();
889     Type *SrcTy = NewV->getType();
890     Function *NewDecl =
891         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
892     II->setArgOperand(0, NewV);
893     II->setCalledFunction(NewDecl);
894     return II;
895   }
896   case Intrinsic::amdgcn_is_shared:
897   case Intrinsic::amdgcn_is_private: {
898     unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ?
899       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
900     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
901     LLVMContext &Ctx = NewV->getType()->getContext();
902     ConstantInt *NewVal = (TrueAS == NewAS) ?
903       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
904     return NewVal;
905   }
906   case Intrinsic::ptrmask: {
907     unsigned OldAS = OldV->getType()->getPointerAddressSpace();
908     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
909     Value *MaskOp = II->getArgOperand(1);
910     Type *MaskTy = MaskOp->getType();
911 
912     bool DoTruncate = false;
913     if (!getTLI()->isNoopAddrSpaceCast(OldAS, NewAS)) {
914       // All valid 64-bit to 32-bit casts work by chopping off the high
915       // bits. Any masking only clearing the low bits will also apply in the new
916       // address space.
917       if (DL.getPointerSizeInBits(OldAS) != 64 ||
918           DL.getPointerSizeInBits(NewAS) != 32)
919         return nullptr;
920 
921       // TODO: Do we need to thread more context in here?
922       KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II);
923       if (Known.countMinLeadingOnes() < 32)
924         return nullptr;
925 
926       DoTruncate = true;
927     }
928 
929     IRBuilder<> B(II);
930     if (DoTruncate) {
931       MaskTy = B.getInt32Ty();
932       MaskOp = B.CreateTrunc(MaskOp, MaskTy);
933     }
934 
935     return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy},
936                              {NewV, MaskOp});
937   }
938   default:
939     return nullptr;
940   }
941 }
942 
943 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *VT,
944                                     int Index, VectorType *SubTp) {
945   if (ST->hasVOP3PInsts()) {
946     if (cast<FixedVectorType>(VT)->getNumElements() == 2 &&
947         DL.getTypeSizeInBits(VT->getElementType()) == 16) {
948       // With op_sel VOP3P instructions freely can access the low half or high
949       // half of a register, so any swizzle is free.
950 
951       switch (Kind) {
952       case TTI::SK_Broadcast:
953       case TTI::SK_Reverse:
954       case TTI::SK_PermuteSingleSrc:
955         return 0;
956       default:
957         break;
958       }
959     }
960   }
961 
962   return BaseT::getShuffleCost(Kind, VT, Index, SubTp);
963 }
964 
965 bool GCNTTIImpl::areInlineCompatible(const Function *Caller,
966                                      const Function *Callee) const {
967   const TargetMachine &TM = getTLI()->getTargetMachine();
968   const GCNSubtarget *CallerST
969     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller));
970   const GCNSubtarget *CalleeST
971     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee));
972 
973   const FeatureBitset &CallerBits = CallerST->getFeatureBits();
974   const FeatureBitset &CalleeBits = CalleeST->getFeatureBits();
975 
976   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
977   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
978   if ((RealCallerBits & RealCalleeBits) != RealCalleeBits)
979     return false;
980 
981   // FIXME: dx10_clamp can just take the caller setting, but there seems to be
982   // no way to support merge for backend defined attributes.
983   AMDGPU::SIModeRegisterDefaults CallerMode(*Caller);
984   AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee);
985   return CallerMode.isInlineCompatible(CalleeMode);
986 }
987 
988 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
989                                          TTI::UnrollingPreferences &UP) {
990   CommonTTI.getUnrollingPreferences(L, SE, UP);
991 }
992 
993 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
994   return 4 * 128; // XXX - 4 channels. Should these count as vector instead?
995 }
996 
997 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const {
998   return getHardwareNumberOfRegisters(Vec);
999 }
1000 
1001 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const {
1002   return 32;
1003 }
1004 
1005 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const {
1006   return 32;
1007 }
1008 
1009 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
1010   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
1011       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS)
1012     return 128;
1013   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1014       AddrSpace == AMDGPUAS::REGION_ADDRESS)
1015     return 64;
1016   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
1017     return 32;
1018 
1019   if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS ||
1020       AddrSpace == AMDGPUAS::PARAM_I_ADDRESS ||
1021       (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 &&
1022       AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15)))
1023     return 128;
1024   llvm_unreachable("unhandled address space");
1025 }
1026 
1027 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
1028                                              Align Alignment,
1029                                              unsigned AddrSpace) const {
1030   // We allow vectorization of flat stores, even though we may need to decompose
1031   // them later if they may access private memory. We don't have enough context
1032   // here, and legalization can handle it.
1033   return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS);
1034 }
1035 
1036 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1037                                               Align Alignment,
1038                                               unsigned AddrSpace) const {
1039   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
1040 }
1041 
1042 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1043                                                Align Alignment,
1044                                                unsigned AddrSpace) const {
1045   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
1046 }
1047 
1048 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) {
1049   // Disable unrolling if the loop is not vectorized.
1050   // TODO: Enable this again.
1051   if (VF == 1)
1052     return 1;
1053 
1054   return 8;
1055 }
1056 
1057 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode,
1058                                      TTI::TargetCostKind CostKind) {
1059   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency)
1060     return Opcode == Instruction::PHI ? 0 : 1;
1061 
1062   // XXX - For some reason this isn't called for switch.
1063   switch (Opcode) {
1064   case Instruction::Br:
1065   case Instruction::Ret:
1066     return 10;
1067   default:
1068     return BaseT::getCFInstrCost(Opcode, CostKind);
1069   }
1070 }
1071 
1072 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
1073                                     unsigned Index) {
1074   switch (Opcode) {
1075   case Instruction::ExtractElement:
1076   case Instruction::InsertElement: {
1077     unsigned EltSize
1078       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
1079     if (EltSize < 32) {
1080       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
1081     }
1082 
1083     // Extracts are just reads of a subregister, so are free. Inserts are
1084     // considered free because we don't want to have any cost for scalarizing
1085     // operations, and we don't have to copy into a different register class.
1086 
1087     // Dynamic indexing isn't free and is best avoided.
1088     return Index == ~0u ? 2 : 0;
1089   }
1090   default:
1091     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
1092   }
1093 }
1094 
1095 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1096                                           TTI::UnrollingPreferences &UP) {
1097   CommonTTI.getUnrollingPreferences(L, SE, UP);
1098 }
1099