1 //===- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI pass -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // \file
11 // This file implements a TargetTransformInfo analysis pass specific to the
12 // AMDGPU target machine. It uses the target's detailed information to provide
13 // more precise answers to certain TTI queries, while letting the target
14 // independent and default TTI implementations handle the rest.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "AMDGPUTargetTransformInfo.h"
19 #include "AMDGPUSubtarget.h"
20 #include "Utils/AMDGPUBaseInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/ISDOpcodes.h"
26 #include "llvm/CodeGen/MachineValueType.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/Argument.h"
29 #include "llvm/IR/Attributes.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/PatternMatch.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/MC/SubtargetFeature.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <limits>
52 #include <utility>
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "AMDGPUtti"
57 
58 static cl::opt<unsigned> UnrollThresholdPrivate(
59   "amdgpu-unroll-threshold-private",
60   cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"),
61   cl::init(2500), cl::Hidden);
62 
63 static cl::opt<unsigned> UnrollThresholdLocal(
64   "amdgpu-unroll-threshold-local",
65   cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"),
66   cl::init(1000), cl::Hidden);
67 
68 static cl::opt<unsigned> UnrollThresholdIf(
69   "amdgpu-unroll-threshold-if",
70   cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"),
71   cl::init(150), cl::Hidden);
72 
73 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond,
74                               unsigned Depth = 0) {
75   const Instruction *I = dyn_cast<Instruction>(Cond);
76   if (!I)
77     return false;
78 
79   for (const Value *V : I->operand_values()) {
80     if (!L->contains(I))
81       continue;
82     if (const PHINode *PHI = dyn_cast<PHINode>(V)) {
83       if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) {
84                   return SubLoop->contains(PHI); }))
85         return true;
86     } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1))
87       return true;
88   }
89   return false;
90 }
91 
92 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
93                                             TTI::UnrollingPreferences &UP) {
94   UP.Threshold = 300; // Twice the default.
95   UP.MaxCount = std::numeric_limits<unsigned>::max();
96   UP.Partial = true;
97 
98   // TODO: Do we want runtime unrolling?
99 
100   // Maximum alloca size than can fit registers. Reserve 16 registers.
101   const unsigned MaxAlloca = (256 - 16) * 4;
102   unsigned ThresholdPrivate = UnrollThresholdPrivate;
103   unsigned ThresholdLocal = UnrollThresholdLocal;
104   unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal);
105   AMDGPUAS ASST = ST->getAMDGPUAS();
106   for (const BasicBlock *BB : L->getBlocks()) {
107     const DataLayout &DL = BB->getModule()->getDataLayout();
108     unsigned LocalGEPsSeen = 0;
109 
110     if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) {
111                return SubLoop->contains(BB); }))
112         continue; // Block belongs to an inner loop.
113 
114     for (const Instruction &I : *BB) {
115       // Unroll a loop which contains an "if" statement whose condition
116       // defined by a PHI belonging to the loop. This may help to eliminate
117       // if region and potentially even PHI itself, saving on both divergence
118       // and registers used for the PHI.
119       // Add a small bonus for each of such "if" statements.
120       if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) {
121         if (UP.Threshold < MaxBoost && Br->isConditional()) {
122           if (L->isLoopExiting(Br->getSuccessor(0)) ||
123               L->isLoopExiting(Br->getSuccessor(1)))
124             continue;
125           if (dependsOnLocalPhi(L, Br->getCondition())) {
126             UP.Threshold += UnrollThresholdIf;
127             DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold
128                          << " for loop:\n" << *L << " due to " << *Br << '\n');
129             if (UP.Threshold >= MaxBoost)
130               return;
131           }
132         }
133         continue;
134       }
135 
136       const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I);
137       if (!GEP)
138         continue;
139 
140       unsigned AS = GEP->getAddressSpace();
141       unsigned Threshold = 0;
142       if (AS == ASST.PRIVATE_ADDRESS)
143         Threshold = ThresholdPrivate;
144       else if (AS == ASST.LOCAL_ADDRESS)
145         Threshold = ThresholdLocal;
146       else
147         continue;
148 
149       if (UP.Threshold >= Threshold)
150         continue;
151 
152       if (AS == ASST.PRIVATE_ADDRESS) {
153         const Value *Ptr = GEP->getPointerOperand();
154         const AllocaInst *Alloca =
155             dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr, DL));
156         if (!Alloca || !Alloca->isStaticAlloca())
157           continue;
158         Type *Ty = Alloca->getAllocatedType();
159         unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0;
160         if (AllocaSize > MaxAlloca)
161           continue;
162       } else if (AS == ASST.LOCAL_ADDRESS) {
163         LocalGEPsSeen++;
164         // Inhibit unroll for local memory if we have seen addressing not to
165         // a variable, most likely we will be unable to combine it.
166         // Do not unroll too deep inner loops for local memory to give a chance
167         // to unroll an outer loop for a more important reason.
168         if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 ||
169             (!isa<GlobalVariable>(GEP->getPointerOperand()) &&
170              !isa<Argument>(GEP->getPointerOperand())))
171           continue;
172       }
173 
174       // Check if GEP depends on a value defined by this loop itself.
175       bool HasLoopDef = false;
176       for (const Value *Op : GEP->operands()) {
177         const Instruction *Inst = dyn_cast<Instruction>(Op);
178         if (!Inst || L->isLoopInvariant(Op))
179           continue;
180 
181         if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) {
182              return SubLoop->contains(Inst); }))
183           continue;
184         HasLoopDef = true;
185         break;
186       }
187       if (!HasLoopDef)
188         continue;
189 
190       // We want to do whatever we can to limit the number of alloca
191       // instructions that make it through to the code generator.  allocas
192       // require us to use indirect addressing, which is slow and prone to
193       // compiler bugs.  If this loop does an address calculation on an
194       // alloca ptr, then we want to use a higher than normal loop unroll
195       // threshold. This will give SROA a better chance to eliminate these
196       // allocas.
197       //
198       // We also want to have more unrolling for local memory to let ds
199       // instructions with different offsets combine.
200       //
201       // Don't use the maximum allowed value here as it will make some
202       // programs way too big.
203       UP.Threshold = Threshold;
204       DEBUG(dbgs() << "Set unroll threshold " << Threshold << " for loop:\n"
205                    << *L << " due to " << *GEP << '\n');
206       if (UP.Threshold >= MaxBoost)
207         return;
208     }
209   }
210 }
211 
212 unsigned AMDGPUTTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
213   // The concept of vector registers doesn't really exist. Some packed vector
214   // operations operate on the normal 32-bit registers.
215 
216   // Number of VGPRs on SI.
217   if (ST->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS)
218     return 256;
219 
220   return 4 * 128; // XXX - 4 channels. Should these count as vector instead?
221 }
222 
223 unsigned AMDGPUTTIImpl::getNumberOfRegisters(bool Vec) const {
224   // This is really the number of registers to fill when vectorizing /
225   // interleaving loops, so we lie to avoid trying to use all registers.
226   return getHardwareNumberOfRegisters(Vec) >> 3;
227 }
228 
229 unsigned AMDGPUTTIImpl::getRegisterBitWidth(bool Vector) const {
230   return 32;
231 }
232 
233 unsigned AMDGPUTTIImpl::getMinVectorRegisterBitWidth() const {
234   return 32;
235 }
236 
237 unsigned AMDGPUTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
238   AMDGPUAS AS = ST->getAMDGPUAS();
239   if (AddrSpace == AS.GLOBAL_ADDRESS ||
240       AddrSpace == AS.CONSTANT_ADDRESS ||
241       AddrSpace == AS.CONSTANT_ADDRESS_32BIT ||
242       AddrSpace == AS.FLAT_ADDRESS)
243     return 128;
244   if (AddrSpace == AS.LOCAL_ADDRESS ||
245       AddrSpace == AS.REGION_ADDRESS)
246     return 64;
247   if (AddrSpace == AS.PRIVATE_ADDRESS)
248     return 8 * ST->getMaxPrivateElementSize();
249 
250   if (ST->getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS &&
251       (AddrSpace == AS.PARAM_D_ADDRESS ||
252       AddrSpace == AS.PARAM_I_ADDRESS ||
253       (AddrSpace >= AS.CONSTANT_BUFFER_0 &&
254       AddrSpace <= AS.CONSTANT_BUFFER_15)))
255     return 128;
256   llvm_unreachable("unhandled address space");
257 }
258 
259 bool AMDGPUTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
260                                                unsigned Alignment,
261                                                unsigned AddrSpace) const {
262   // We allow vectorization of flat stores, even though we may need to decompose
263   // them later if they may access private memory. We don't have enough context
264   // here, and legalization can handle it.
265   if (AddrSpace == ST->getAMDGPUAS().PRIVATE_ADDRESS) {
266     return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) &&
267       ChainSizeInBytes <= ST->getMaxPrivateElementSize();
268   }
269   return true;
270 }
271 
272 bool AMDGPUTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
273                                                 unsigned Alignment,
274                                                 unsigned AddrSpace) const {
275   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
276 }
277 
278 bool AMDGPUTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
279                                                  unsigned Alignment,
280                                                  unsigned AddrSpace) const {
281   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
282 }
283 
284 unsigned AMDGPUTTIImpl::getMaxInterleaveFactor(unsigned VF) {
285   // Disable unrolling if the loop is not vectorized.
286   // TODO: Enable this again.
287   if (VF == 1)
288     return 1;
289 
290   return 8;
291 }
292 
293 bool AMDGPUTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
294                                        MemIntrinsicInfo &Info) const {
295   switch (Inst->getIntrinsicID()) {
296   case Intrinsic::amdgcn_atomic_inc:
297   case Intrinsic::amdgcn_atomic_dec:
298   case Intrinsic::amdgcn_ds_fadd:
299   case Intrinsic::amdgcn_ds_fmin:
300   case Intrinsic::amdgcn_ds_fmax: {
301     auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2));
302     auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4));
303     if (!Ordering || !Volatile)
304       return false; // Invalid.
305 
306     unsigned OrderingVal = Ordering->getZExtValue();
307     if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent))
308       return false;
309 
310     Info.PtrVal = Inst->getArgOperand(0);
311     Info.Ordering = static_cast<AtomicOrdering>(OrderingVal);
312     Info.ReadMem = true;
313     Info.WriteMem = true;
314     Info.IsVolatile = !Volatile->isNullValue();
315     return true;
316   }
317   default:
318     return false;
319   }
320 }
321 
322 int AMDGPUTTIImpl::getArithmeticInstrCost(
323     unsigned Opcode, Type *Ty, TTI::OperandValueKind Opd1Info,
324     TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo,
325     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args ) {
326   EVT OrigTy = TLI->getValueType(DL, Ty);
327   if (!OrigTy.isSimple()) {
328     return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
329                                          Opd1PropInfo, Opd2PropInfo);
330   }
331 
332   // Legalize the type.
333   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
334   int ISD = TLI->InstructionOpcodeToISD(Opcode);
335 
336   // Because we don't have any legal vector operations, but the legal types, we
337   // need to account for split vectors.
338   unsigned NElts = LT.second.isVector() ?
339     LT.second.getVectorNumElements() : 1;
340 
341   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
342 
343   switch (ISD) {
344   case ISD::SHL:
345   case ISD::SRL:
346   case ISD::SRA:
347     if (SLT == MVT::i64)
348       return get64BitInstrCost() * LT.first * NElts;
349 
350     // i32
351     return getFullRateInstrCost() * LT.first * NElts;
352   case ISD::ADD:
353   case ISD::SUB:
354   case ISD::AND:
355   case ISD::OR:
356   case ISD::XOR:
357     if (SLT == MVT::i64){
358       // and, or and xor are typically split into 2 VALU instructions.
359       return 2 * getFullRateInstrCost() * LT.first * NElts;
360     }
361 
362     return LT.first * NElts * getFullRateInstrCost();
363   case ISD::MUL: {
364     const int QuarterRateCost = getQuarterRateInstrCost();
365     if (SLT == MVT::i64) {
366       const int FullRateCost = getFullRateInstrCost();
367       return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts;
368     }
369 
370     // i32
371     return QuarterRateCost * NElts * LT.first;
372   }
373   case ISD::FADD:
374   case ISD::FSUB:
375   case ISD::FMUL:
376     if (SLT == MVT::f64)
377       return LT.first * NElts * get64BitInstrCost();
378 
379     if (SLT == MVT::f32 || SLT == MVT::f16)
380       return LT.first * NElts * getFullRateInstrCost();
381     break;
382   case ISD::FDIV:
383   case ISD::FREM:
384     // FIXME: frem should be handled separately. The fdiv in it is most of it,
385     // but the current lowering is also not entirely correct.
386     if (SLT == MVT::f64) {
387       int Cost = 4 * get64BitInstrCost() + 7 * getQuarterRateInstrCost();
388       // Add cost of workaround.
389       if (ST->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS)
390         Cost += 3 * getFullRateInstrCost();
391 
392       return LT.first * Cost * NElts;
393     }
394 
395     if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) {
396       // TODO: This is more complicated, unsafe flags etc.
397       if ((SLT == MVT::f32 && !ST->hasFP32Denormals()) ||
398           (SLT == MVT::f16 && ST->has16BitInsts())) {
399         return LT.first * getQuarterRateInstrCost() * NElts;
400       }
401     }
402 
403     if (SLT == MVT::f16 && ST->has16BitInsts()) {
404       // 2 x v_cvt_f32_f16
405       // f32 rcp
406       // f32 fmul
407       // v_cvt_f16_f32
408       // f16 div_fixup
409       int Cost = 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost();
410       return LT.first * Cost * NElts;
411     }
412 
413     if (SLT == MVT::f32 || SLT == MVT::f16) {
414       int Cost = 7 * getFullRateInstrCost() + 1 * getQuarterRateInstrCost();
415 
416       if (!ST->hasFP32Denormals()) {
417         // FP mode switches.
418         Cost += 2 * getFullRateInstrCost();
419       }
420 
421       return LT.first * NElts * Cost;
422     }
423     break;
424   default:
425     break;
426   }
427 
428   return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
429                                        Opd1PropInfo, Opd2PropInfo);
430 }
431 
432 unsigned AMDGPUTTIImpl::getCFInstrCost(unsigned Opcode) {
433   // XXX - For some reason this isn't called for switch.
434   switch (Opcode) {
435   case Instruction::Br:
436   case Instruction::Ret:
437     return 10;
438   default:
439     return BaseT::getCFInstrCost(Opcode);
440   }
441 }
442 
443 int AMDGPUTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
444                                       unsigned Index) {
445   switch (Opcode) {
446   case Instruction::ExtractElement:
447   case Instruction::InsertElement: {
448     unsigned EltSize
449       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
450     if (EltSize < 32) {
451       if (EltSize == 16 && Index == 0 && ST->has16BitInsts())
452         return 0;
453       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
454     }
455 
456     // Extracts are just reads of a subregister, so are free. Inserts are
457     // considered free because we don't want to have any cost for scalarizing
458     // operations, and we don't have to copy into a different register class.
459 
460     // Dynamic indexing isn't free and is best avoided.
461     return Index == ~0u ? 2 : 0;
462   }
463   default:
464     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
465   }
466 }
467 
468 
469 
470 static bool isArgPassedInSGPR(const Argument *A) {
471   const Function *F = A->getParent();
472 
473   // Arguments to compute shaders are never a source of divergence.
474   CallingConv::ID CC = F->getCallingConv();
475   switch (CC) {
476   case CallingConv::AMDGPU_KERNEL:
477   case CallingConv::SPIR_KERNEL:
478     return true;
479   case CallingConv::AMDGPU_VS:
480   case CallingConv::AMDGPU_LS:
481   case CallingConv::AMDGPU_HS:
482   case CallingConv::AMDGPU_ES:
483   case CallingConv::AMDGPU_GS:
484   case CallingConv::AMDGPU_PS:
485   case CallingConv::AMDGPU_CS:
486     // For non-compute shaders, SGPR inputs are marked with either inreg or byval.
487     // Everything else is in VGPRs.
488     return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg) ||
489            F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::ByVal);
490   default:
491     // TODO: Should calls support inreg for SGPR inputs?
492     return false;
493   }
494 }
495 
496 /// \returns true if the result of the value could potentially be
497 /// different across workitems in a wavefront.
498 bool AMDGPUTTIImpl::isSourceOfDivergence(const Value *V) const {
499   if (const Argument *A = dyn_cast<Argument>(V))
500     return !isArgPassedInSGPR(A);
501 
502   // Loads from the private address space are divergent, because threads
503   // can execute the load instruction with the same inputs and get different
504   // results.
505   //
506   // All other loads are not divergent, because if threads issue loads with the
507   // same arguments, they will always get the same result.
508   if (const LoadInst *Load = dyn_cast<LoadInst>(V))
509     return Load->getPointerAddressSpace() == ST->getAMDGPUAS().PRIVATE_ADDRESS;
510 
511   // Atomics are divergent because they are executed sequentially: when an
512   // atomic operation refers to the same address in each thread, then each
513   // thread after the first sees the value written by the previous thread as
514   // original value.
515   if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V))
516     return true;
517 
518   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V))
519     return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID());
520 
521   // Assume all function calls are a source of divergence.
522   if (isa<CallInst>(V) || isa<InvokeInst>(V))
523     return true;
524 
525   return false;
526 }
527 
528 bool AMDGPUTTIImpl::isAlwaysUniform(const Value *V) const {
529   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
530     switch (Intrinsic->getIntrinsicID()) {
531     default:
532       return false;
533     case Intrinsic::amdgcn_readfirstlane:
534     case Intrinsic::amdgcn_readlane:
535       return true;
536     }
537   }
538   return false;
539 }
540 
541 unsigned AMDGPUTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
542                                        Type *SubTp) {
543   if (ST->hasVOP3PInsts()) {
544     VectorType *VT = cast<VectorType>(Tp);
545     if (VT->getNumElements() == 2 &&
546         DL.getTypeSizeInBits(VT->getElementType()) == 16) {
547       // With op_sel VOP3P instructions freely can access the low half or high
548       // half of a register, so any swizzle is free.
549 
550       switch (Kind) {
551       case TTI::SK_Broadcast:
552       case TTI::SK_Reverse:
553       case TTI::SK_PermuteSingleSrc:
554         return 0;
555       default:
556         break;
557       }
558     }
559   }
560 
561   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
562 }
563 
564 bool AMDGPUTTIImpl::areInlineCompatible(const Function *Caller,
565                                         const Function *Callee) const {
566   const TargetMachine &TM = getTLI()->getTargetMachine();
567   const FeatureBitset &CallerBits =
568     TM.getSubtargetImpl(*Caller)->getFeatureBits();
569   const FeatureBitset &CalleeBits =
570     TM.getSubtargetImpl(*Callee)->getFeatureBits();
571 
572   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
573   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
574   return ((RealCallerBits & RealCalleeBits) == RealCalleeBits);
575 }
576