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