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