xref: /aosp_15_r20/external/llvm/lib/CodeGen/Analysis.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file defines several CodeGen-specific LLVM IR analysis utilities.
11*9880d681SAndroid Build Coastguard Worker //
12*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
13*9880d681SAndroid Build Coastguard Worker 
14*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/Analysis.h"
15*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineFunction.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineModuleInfo.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/ErrorHandling.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/MathExtras.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetLowering.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetInstrInfo.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetSubtargetInfo.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/GlobalStatus.h"
31*9880d681SAndroid Build Coastguard Worker 
32*9880d681SAndroid Build Coastguard Worker using namespace llvm;
33*9880d681SAndroid Build Coastguard Worker 
34*9880d681SAndroid Build Coastguard Worker /// Compute the linearized index of a member in a nested aggregate/struct/array
35*9880d681SAndroid Build Coastguard Worker /// by recursing and accumulating CurIndex as long as there are indices in the
36*9880d681SAndroid Build Coastguard Worker /// index list.
ComputeLinearIndex(Type * Ty,const unsigned * Indices,const unsigned * IndicesEnd,unsigned CurIndex)37*9880d681SAndroid Build Coastguard Worker unsigned llvm::ComputeLinearIndex(Type *Ty,
38*9880d681SAndroid Build Coastguard Worker                                   const unsigned *Indices,
39*9880d681SAndroid Build Coastguard Worker                                   const unsigned *IndicesEnd,
40*9880d681SAndroid Build Coastguard Worker                                   unsigned CurIndex) {
41*9880d681SAndroid Build Coastguard Worker   // Base case: We're done.
42*9880d681SAndroid Build Coastguard Worker   if (Indices && Indices == IndicesEnd)
43*9880d681SAndroid Build Coastguard Worker     return CurIndex;
44*9880d681SAndroid Build Coastguard Worker 
45*9880d681SAndroid Build Coastguard Worker   // Given a struct type, recursively traverse the elements.
46*9880d681SAndroid Build Coastguard Worker   if (StructType *STy = dyn_cast<StructType>(Ty)) {
47*9880d681SAndroid Build Coastguard Worker     for (StructType::element_iterator EB = STy->element_begin(),
48*9880d681SAndroid Build Coastguard Worker                                       EI = EB,
49*9880d681SAndroid Build Coastguard Worker                                       EE = STy->element_end();
50*9880d681SAndroid Build Coastguard Worker         EI != EE; ++EI) {
51*9880d681SAndroid Build Coastguard Worker       if (Indices && *Indices == unsigned(EI - EB))
52*9880d681SAndroid Build Coastguard Worker         return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
53*9880d681SAndroid Build Coastguard Worker       CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
54*9880d681SAndroid Build Coastguard Worker     }
55*9880d681SAndroid Build Coastguard Worker     assert(!Indices && "Unexpected out of bound");
56*9880d681SAndroid Build Coastguard Worker     return CurIndex;
57*9880d681SAndroid Build Coastguard Worker   }
58*9880d681SAndroid Build Coastguard Worker   // Given an array type, recursively traverse the elements.
59*9880d681SAndroid Build Coastguard Worker   else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
60*9880d681SAndroid Build Coastguard Worker     Type *EltTy = ATy->getElementType();
61*9880d681SAndroid Build Coastguard Worker     unsigned NumElts = ATy->getNumElements();
62*9880d681SAndroid Build Coastguard Worker     // Compute the Linear offset when jumping one element of the array
63*9880d681SAndroid Build Coastguard Worker     unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
64*9880d681SAndroid Build Coastguard Worker     if (Indices) {
65*9880d681SAndroid Build Coastguard Worker       assert(*Indices < NumElts && "Unexpected out of bound");
66*9880d681SAndroid Build Coastguard Worker       // If the indice is inside the array, compute the index to the requested
67*9880d681SAndroid Build Coastguard Worker       // elt and recurse inside the element with the end of the indices list
68*9880d681SAndroid Build Coastguard Worker       CurIndex += EltLinearOffset* *Indices;
69*9880d681SAndroid Build Coastguard Worker       return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
70*9880d681SAndroid Build Coastguard Worker     }
71*9880d681SAndroid Build Coastguard Worker     CurIndex += EltLinearOffset*NumElts;
72*9880d681SAndroid Build Coastguard Worker     return CurIndex;
73*9880d681SAndroid Build Coastguard Worker   }
74*9880d681SAndroid Build Coastguard Worker   // We haven't found the type we're looking for, so keep searching.
75*9880d681SAndroid Build Coastguard Worker   return CurIndex + 1;
76*9880d681SAndroid Build Coastguard Worker }
77*9880d681SAndroid Build Coastguard Worker 
78*9880d681SAndroid Build Coastguard Worker /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
79*9880d681SAndroid Build Coastguard Worker /// EVTs that represent all the individual underlying
80*9880d681SAndroid Build Coastguard Worker /// non-aggregate types that comprise it.
81*9880d681SAndroid Build Coastguard Worker ///
82*9880d681SAndroid Build Coastguard Worker /// If Offsets is non-null, it points to a vector to be filled in
83*9880d681SAndroid Build Coastguard Worker /// with the in-memory offsets of each of the individual values.
84*9880d681SAndroid Build Coastguard Worker ///
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<uint64_t> * Offsets,uint64_t StartingOffset)85*9880d681SAndroid Build Coastguard Worker void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
86*9880d681SAndroid Build Coastguard Worker                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
87*9880d681SAndroid Build Coastguard Worker                            SmallVectorImpl<uint64_t> *Offsets,
88*9880d681SAndroid Build Coastguard Worker                            uint64_t StartingOffset) {
89*9880d681SAndroid Build Coastguard Worker   // Given a struct type, recursively traverse the elements.
90*9880d681SAndroid Build Coastguard Worker   if (StructType *STy = dyn_cast<StructType>(Ty)) {
91*9880d681SAndroid Build Coastguard Worker     const StructLayout *SL = DL.getStructLayout(STy);
92*9880d681SAndroid Build Coastguard Worker     for (StructType::element_iterator EB = STy->element_begin(),
93*9880d681SAndroid Build Coastguard Worker                                       EI = EB,
94*9880d681SAndroid Build Coastguard Worker                                       EE = STy->element_end();
95*9880d681SAndroid Build Coastguard Worker          EI != EE; ++EI)
96*9880d681SAndroid Build Coastguard Worker       ComputeValueVTs(TLI, DL, *EI, ValueVTs, Offsets,
97*9880d681SAndroid Build Coastguard Worker                       StartingOffset + SL->getElementOffset(EI - EB));
98*9880d681SAndroid Build Coastguard Worker     return;
99*9880d681SAndroid Build Coastguard Worker   }
100*9880d681SAndroid Build Coastguard Worker   // Given an array type, recursively traverse the elements.
101*9880d681SAndroid Build Coastguard Worker   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
102*9880d681SAndroid Build Coastguard Worker     Type *EltTy = ATy->getElementType();
103*9880d681SAndroid Build Coastguard Worker     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
104*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
105*9880d681SAndroid Build Coastguard Worker       ComputeValueVTs(TLI, DL, EltTy, ValueVTs, Offsets,
106*9880d681SAndroid Build Coastguard Worker                       StartingOffset + i * EltSize);
107*9880d681SAndroid Build Coastguard Worker     return;
108*9880d681SAndroid Build Coastguard Worker   }
109*9880d681SAndroid Build Coastguard Worker   // Interpret void as zero return values.
110*9880d681SAndroid Build Coastguard Worker   if (Ty->isVoidTy())
111*9880d681SAndroid Build Coastguard Worker     return;
112*9880d681SAndroid Build Coastguard Worker   // Base case: we can get an EVT for this LLVM IR type.
113*9880d681SAndroid Build Coastguard Worker   ValueVTs.push_back(TLI.getValueType(DL, Ty));
114*9880d681SAndroid Build Coastguard Worker   if (Offsets)
115*9880d681SAndroid Build Coastguard Worker     Offsets->push_back(StartingOffset);
116*9880d681SAndroid Build Coastguard Worker }
117*9880d681SAndroid Build Coastguard Worker 
118*9880d681SAndroid Build Coastguard Worker /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
ExtractTypeInfo(Value * V)119*9880d681SAndroid Build Coastguard Worker GlobalValue *llvm::ExtractTypeInfo(Value *V) {
120*9880d681SAndroid Build Coastguard Worker   V = V->stripPointerCasts();
121*9880d681SAndroid Build Coastguard Worker   GlobalValue *GV = dyn_cast<GlobalValue>(V);
122*9880d681SAndroid Build Coastguard Worker   GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
123*9880d681SAndroid Build Coastguard Worker 
124*9880d681SAndroid Build Coastguard Worker   if (Var && Var->getName() == "llvm.eh.catch.all.value") {
125*9880d681SAndroid Build Coastguard Worker     assert(Var->hasInitializer() &&
126*9880d681SAndroid Build Coastguard Worker            "The EH catch-all value must have an initializer");
127*9880d681SAndroid Build Coastguard Worker     Value *Init = Var->getInitializer();
128*9880d681SAndroid Build Coastguard Worker     GV = dyn_cast<GlobalValue>(Init);
129*9880d681SAndroid Build Coastguard Worker     if (!GV) V = cast<ConstantPointerNull>(Init);
130*9880d681SAndroid Build Coastguard Worker   }
131*9880d681SAndroid Build Coastguard Worker 
132*9880d681SAndroid Build Coastguard Worker   assert((GV || isa<ConstantPointerNull>(V)) &&
133*9880d681SAndroid Build Coastguard Worker          "TypeInfo must be a global variable or NULL");
134*9880d681SAndroid Build Coastguard Worker   return GV;
135*9880d681SAndroid Build Coastguard Worker }
136*9880d681SAndroid Build Coastguard Worker 
137*9880d681SAndroid Build Coastguard Worker /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
138*9880d681SAndroid Build Coastguard Worker /// processed uses a memory 'm' constraint.
139*9880d681SAndroid Build Coastguard Worker bool
hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector & CInfos,const TargetLowering & TLI)140*9880d681SAndroid Build Coastguard Worker llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
141*9880d681SAndroid Build Coastguard Worker                                 const TargetLowering &TLI) {
142*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
143*9880d681SAndroid Build Coastguard Worker     InlineAsm::ConstraintInfo &CI = CInfos[i];
144*9880d681SAndroid Build Coastguard Worker     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
145*9880d681SAndroid Build Coastguard Worker       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
146*9880d681SAndroid Build Coastguard Worker       if (CType == TargetLowering::C_Memory)
147*9880d681SAndroid Build Coastguard Worker         return true;
148*9880d681SAndroid Build Coastguard Worker     }
149*9880d681SAndroid Build Coastguard Worker 
150*9880d681SAndroid Build Coastguard Worker     // Indirect operand accesses access memory.
151*9880d681SAndroid Build Coastguard Worker     if (CI.isIndirect)
152*9880d681SAndroid Build Coastguard Worker       return true;
153*9880d681SAndroid Build Coastguard Worker   }
154*9880d681SAndroid Build Coastguard Worker 
155*9880d681SAndroid Build Coastguard Worker   return false;
156*9880d681SAndroid Build Coastguard Worker }
157*9880d681SAndroid Build Coastguard Worker 
158*9880d681SAndroid Build Coastguard Worker /// getFCmpCondCode - Return the ISD condition code corresponding to
159*9880d681SAndroid Build Coastguard Worker /// the given LLVM IR floating-point condition code.  This includes
160*9880d681SAndroid Build Coastguard Worker /// consideration of global floating-point math flags.
161*9880d681SAndroid Build Coastguard Worker ///
getFCmpCondCode(FCmpInst::Predicate Pred)162*9880d681SAndroid Build Coastguard Worker ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
163*9880d681SAndroid Build Coastguard Worker   switch (Pred) {
164*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
165*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
166*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
167*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
168*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
169*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
170*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_ONE:   return ISD::SETONE;
171*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_ORD:   return ISD::SETO;
172*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UNO:   return ISD::SETUO;
173*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
174*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
175*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
176*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_ULT:   return ISD::SETULT;
177*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_ULE:   return ISD::SETULE;
178*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
179*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
180*9880d681SAndroid Build Coastguard Worker   default: llvm_unreachable("Invalid FCmp predicate opcode!");
181*9880d681SAndroid Build Coastguard Worker   }
182*9880d681SAndroid Build Coastguard Worker }
183*9880d681SAndroid Build Coastguard Worker 
getFCmpCodeWithoutNaN(ISD::CondCode CC)184*9880d681SAndroid Build Coastguard Worker ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
185*9880d681SAndroid Build Coastguard Worker   switch (CC) {
186*9880d681SAndroid Build Coastguard Worker     case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
187*9880d681SAndroid Build Coastguard Worker     case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
188*9880d681SAndroid Build Coastguard Worker     case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
189*9880d681SAndroid Build Coastguard Worker     case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
190*9880d681SAndroid Build Coastguard Worker     case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
191*9880d681SAndroid Build Coastguard Worker     case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
192*9880d681SAndroid Build Coastguard Worker     default: return CC;
193*9880d681SAndroid Build Coastguard Worker   }
194*9880d681SAndroid Build Coastguard Worker }
195*9880d681SAndroid Build Coastguard Worker 
196*9880d681SAndroid Build Coastguard Worker /// getICmpCondCode - Return the ISD condition code corresponding to
197*9880d681SAndroid Build Coastguard Worker /// the given LLVM IR integer condition code.
198*9880d681SAndroid Build Coastguard Worker ///
getICmpCondCode(ICmpInst::Predicate Pred)199*9880d681SAndroid Build Coastguard Worker ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
200*9880d681SAndroid Build Coastguard Worker   switch (Pred) {
201*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
202*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_NE:  return ISD::SETNE;
203*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SLE: return ISD::SETLE;
204*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_ULE: return ISD::SETULE;
205*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SGE: return ISD::SETGE;
206*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
207*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SLT: return ISD::SETLT;
208*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_ULT: return ISD::SETULT;
209*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SGT: return ISD::SETGT;
210*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
211*9880d681SAndroid Build Coastguard Worker   default:
212*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Invalid ICmp predicate opcode!");
213*9880d681SAndroid Build Coastguard Worker   }
214*9880d681SAndroid Build Coastguard Worker }
215*9880d681SAndroid Build Coastguard Worker 
isNoopBitcast(Type * T1,Type * T2,const TargetLoweringBase & TLI)216*9880d681SAndroid Build Coastguard Worker static bool isNoopBitcast(Type *T1, Type *T2,
217*9880d681SAndroid Build Coastguard Worker                           const TargetLoweringBase& TLI) {
218*9880d681SAndroid Build Coastguard Worker   return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
219*9880d681SAndroid Build Coastguard Worker          (isa<VectorType>(T1) && isa<VectorType>(T2) &&
220*9880d681SAndroid Build Coastguard Worker           TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
221*9880d681SAndroid Build Coastguard Worker }
222*9880d681SAndroid Build Coastguard Worker 
223*9880d681SAndroid Build Coastguard Worker /// Look through operations that will be free to find the earliest source of
224*9880d681SAndroid Build Coastguard Worker /// this value.
225*9880d681SAndroid Build Coastguard Worker ///
226*9880d681SAndroid Build Coastguard Worker /// @param ValLoc If V has aggegate type, we will be interested in a particular
227*9880d681SAndroid Build Coastguard Worker /// scalar component. This records its address; the reverse of this list gives a
228*9880d681SAndroid Build Coastguard Worker /// sequence of indices appropriate for an extractvalue to locate the important
229*9880d681SAndroid Build Coastguard Worker /// value. This value is updated during the function and on exit will indicate
230*9880d681SAndroid Build Coastguard Worker /// similar information for the Value returned.
231*9880d681SAndroid Build Coastguard Worker ///
232*9880d681SAndroid Build Coastguard Worker /// @param DataBits If this function looks through truncate instructions, this
233*9880d681SAndroid Build Coastguard Worker /// will record the smallest size attained.
getNoopInput(const Value * V,SmallVectorImpl<unsigned> & ValLoc,unsigned & DataBits,const TargetLoweringBase & TLI,const DataLayout & DL)234*9880d681SAndroid Build Coastguard Worker static const Value *getNoopInput(const Value *V,
235*9880d681SAndroid Build Coastguard Worker                                  SmallVectorImpl<unsigned> &ValLoc,
236*9880d681SAndroid Build Coastguard Worker                                  unsigned &DataBits,
237*9880d681SAndroid Build Coastguard Worker                                  const TargetLoweringBase &TLI,
238*9880d681SAndroid Build Coastguard Worker                                  const DataLayout &DL) {
239*9880d681SAndroid Build Coastguard Worker   while (true) {
240*9880d681SAndroid Build Coastguard Worker     // Try to look through V1; if V1 is not an instruction, it can't be looked
241*9880d681SAndroid Build Coastguard Worker     // through.
242*9880d681SAndroid Build Coastguard Worker     const Instruction *I = dyn_cast<Instruction>(V);
243*9880d681SAndroid Build Coastguard Worker     if (!I || I->getNumOperands() == 0) return V;
244*9880d681SAndroid Build Coastguard Worker     const Value *NoopInput = nullptr;
245*9880d681SAndroid Build Coastguard Worker 
246*9880d681SAndroid Build Coastguard Worker     Value *Op = I->getOperand(0);
247*9880d681SAndroid Build Coastguard Worker     if (isa<BitCastInst>(I)) {
248*9880d681SAndroid Build Coastguard Worker       // Look through truly no-op bitcasts.
249*9880d681SAndroid Build Coastguard Worker       if (isNoopBitcast(Op->getType(), I->getType(), TLI))
250*9880d681SAndroid Build Coastguard Worker         NoopInput = Op;
251*9880d681SAndroid Build Coastguard Worker     } else if (isa<GetElementPtrInst>(I)) {
252*9880d681SAndroid Build Coastguard Worker       // Look through getelementptr
253*9880d681SAndroid Build Coastguard Worker       if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
254*9880d681SAndroid Build Coastguard Worker         NoopInput = Op;
255*9880d681SAndroid Build Coastguard Worker     } else if (isa<IntToPtrInst>(I)) {
256*9880d681SAndroid Build Coastguard Worker       // Look through inttoptr.
257*9880d681SAndroid Build Coastguard Worker       // Make sure this isn't a truncating or extending cast.  We could
258*9880d681SAndroid Build Coastguard Worker       // support this eventually, but don't bother for now.
259*9880d681SAndroid Build Coastguard Worker       if (!isa<VectorType>(I->getType()) &&
260*9880d681SAndroid Build Coastguard Worker           DL.getPointerSizeInBits() ==
261*9880d681SAndroid Build Coastguard Worker               cast<IntegerType>(Op->getType())->getBitWidth())
262*9880d681SAndroid Build Coastguard Worker         NoopInput = Op;
263*9880d681SAndroid Build Coastguard Worker     } else if (isa<PtrToIntInst>(I)) {
264*9880d681SAndroid Build Coastguard Worker       // Look through ptrtoint.
265*9880d681SAndroid Build Coastguard Worker       // Make sure this isn't a truncating or extending cast.  We could
266*9880d681SAndroid Build Coastguard Worker       // support this eventually, but don't bother for now.
267*9880d681SAndroid Build Coastguard Worker       if (!isa<VectorType>(I->getType()) &&
268*9880d681SAndroid Build Coastguard Worker           DL.getPointerSizeInBits() ==
269*9880d681SAndroid Build Coastguard Worker               cast<IntegerType>(I->getType())->getBitWidth())
270*9880d681SAndroid Build Coastguard Worker         NoopInput = Op;
271*9880d681SAndroid Build Coastguard Worker     } else if (isa<TruncInst>(I) &&
272*9880d681SAndroid Build Coastguard Worker                TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
273*9880d681SAndroid Build Coastguard Worker       DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
274*9880d681SAndroid Build Coastguard Worker       NoopInput = Op;
275*9880d681SAndroid Build Coastguard Worker     } else if (isa<CallInst>(I)) {
276*9880d681SAndroid Build Coastguard Worker       // Look through call (skipping callee)
277*9880d681SAndroid Build Coastguard Worker       for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1;
278*9880d681SAndroid Build Coastguard Worker            i != e; ++i) {
279*9880d681SAndroid Build Coastguard Worker         unsigned attrInd = i - I->op_begin() + 1;
280*9880d681SAndroid Build Coastguard Worker         if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
281*9880d681SAndroid Build Coastguard Worker             isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
282*9880d681SAndroid Build Coastguard Worker           NoopInput = *i;
283*9880d681SAndroid Build Coastguard Worker           break;
284*9880d681SAndroid Build Coastguard Worker         }
285*9880d681SAndroid Build Coastguard Worker       }
286*9880d681SAndroid Build Coastguard Worker     } else if (isa<InvokeInst>(I)) {
287*9880d681SAndroid Build Coastguard Worker       // Look through invoke (skipping BB, BB, Callee)
288*9880d681SAndroid Build Coastguard Worker       for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3;
289*9880d681SAndroid Build Coastguard Worker            i != e; ++i) {
290*9880d681SAndroid Build Coastguard Worker         unsigned attrInd = i - I->op_begin() + 1;
291*9880d681SAndroid Build Coastguard Worker         if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
292*9880d681SAndroid Build Coastguard Worker             isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
293*9880d681SAndroid Build Coastguard Worker           NoopInput = *i;
294*9880d681SAndroid Build Coastguard Worker           break;
295*9880d681SAndroid Build Coastguard Worker         }
296*9880d681SAndroid Build Coastguard Worker       }
297*9880d681SAndroid Build Coastguard Worker     } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
298*9880d681SAndroid Build Coastguard Worker       // Value may come from either the aggregate or the scalar
299*9880d681SAndroid Build Coastguard Worker       ArrayRef<unsigned> InsertLoc = IVI->getIndices();
300*9880d681SAndroid Build Coastguard Worker       if (ValLoc.size() >= InsertLoc.size() &&
301*9880d681SAndroid Build Coastguard Worker           std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
302*9880d681SAndroid Build Coastguard Worker         // The type being inserted is a nested sub-type of the aggregate; we
303*9880d681SAndroid Build Coastguard Worker         // have to remove those initial indices to get the location we're
304*9880d681SAndroid Build Coastguard Worker         // interested in for the operand.
305*9880d681SAndroid Build Coastguard Worker         ValLoc.resize(ValLoc.size() - InsertLoc.size());
306*9880d681SAndroid Build Coastguard Worker         NoopInput = IVI->getInsertedValueOperand();
307*9880d681SAndroid Build Coastguard Worker       } else {
308*9880d681SAndroid Build Coastguard Worker         // The struct we're inserting into has the value we're interested in, no
309*9880d681SAndroid Build Coastguard Worker         // change of address.
310*9880d681SAndroid Build Coastguard Worker         NoopInput = Op;
311*9880d681SAndroid Build Coastguard Worker       }
312*9880d681SAndroid Build Coastguard Worker     } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
313*9880d681SAndroid Build Coastguard Worker       // The part we're interested in will inevitably be some sub-section of the
314*9880d681SAndroid Build Coastguard Worker       // previous aggregate. Combine the two paths to obtain the true address of
315*9880d681SAndroid Build Coastguard Worker       // our element.
316*9880d681SAndroid Build Coastguard Worker       ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
317*9880d681SAndroid Build Coastguard Worker       ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
318*9880d681SAndroid Build Coastguard Worker       NoopInput = Op;
319*9880d681SAndroid Build Coastguard Worker     }
320*9880d681SAndroid Build Coastguard Worker     // Terminate if we couldn't find anything to look through.
321*9880d681SAndroid Build Coastguard Worker     if (!NoopInput)
322*9880d681SAndroid Build Coastguard Worker       return V;
323*9880d681SAndroid Build Coastguard Worker 
324*9880d681SAndroid Build Coastguard Worker     V = NoopInput;
325*9880d681SAndroid Build Coastguard Worker   }
326*9880d681SAndroid Build Coastguard Worker }
327*9880d681SAndroid Build Coastguard Worker 
328*9880d681SAndroid Build Coastguard Worker /// Return true if this scalar return value only has bits discarded on its path
329*9880d681SAndroid Build Coastguard Worker /// from the "tail call" to the "ret". This includes the obvious noop
330*9880d681SAndroid Build Coastguard Worker /// instructions handled by getNoopInput above as well as free truncations (or
331*9880d681SAndroid Build Coastguard Worker /// extensions prior to the call).
slotOnlyDiscardsData(const Value * RetVal,const Value * CallVal,SmallVectorImpl<unsigned> & RetIndices,SmallVectorImpl<unsigned> & CallIndices,bool AllowDifferingSizes,const TargetLoweringBase & TLI,const DataLayout & DL)332*9880d681SAndroid Build Coastguard Worker static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
333*9880d681SAndroid Build Coastguard Worker                                  SmallVectorImpl<unsigned> &RetIndices,
334*9880d681SAndroid Build Coastguard Worker                                  SmallVectorImpl<unsigned> &CallIndices,
335*9880d681SAndroid Build Coastguard Worker                                  bool AllowDifferingSizes,
336*9880d681SAndroid Build Coastguard Worker                                  const TargetLoweringBase &TLI,
337*9880d681SAndroid Build Coastguard Worker                                  const DataLayout &DL) {
338*9880d681SAndroid Build Coastguard Worker 
339*9880d681SAndroid Build Coastguard Worker   // Trace the sub-value needed by the return value as far back up the graph as
340*9880d681SAndroid Build Coastguard Worker   // possible, in the hope that it will intersect with the value produced by the
341*9880d681SAndroid Build Coastguard Worker   // call. In the simple case with no "returned" attribute, the hope is actually
342*9880d681SAndroid Build Coastguard Worker   // that we end up back at the tail call instruction itself.
343*9880d681SAndroid Build Coastguard Worker   unsigned BitsRequired = UINT_MAX;
344*9880d681SAndroid Build Coastguard Worker   RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL);
345*9880d681SAndroid Build Coastguard Worker 
346*9880d681SAndroid Build Coastguard Worker   // If this slot in the value returned is undef, it doesn't matter what the
347*9880d681SAndroid Build Coastguard Worker   // call puts there, it'll be fine.
348*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(RetVal))
349*9880d681SAndroid Build Coastguard Worker     return true;
350*9880d681SAndroid Build Coastguard Worker 
351*9880d681SAndroid Build Coastguard Worker   // Now do a similar search up through the graph to find where the value
352*9880d681SAndroid Build Coastguard Worker   // actually returned by the "tail call" comes from. In the simple case without
353*9880d681SAndroid Build Coastguard Worker   // a "returned" attribute, the search will be blocked immediately and the loop
354*9880d681SAndroid Build Coastguard Worker   // a Noop.
355*9880d681SAndroid Build Coastguard Worker   unsigned BitsProvided = UINT_MAX;
356*9880d681SAndroid Build Coastguard Worker   CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL);
357*9880d681SAndroid Build Coastguard Worker 
358*9880d681SAndroid Build Coastguard Worker   // There's no hope if we can't actually trace them to (the same part of!) the
359*9880d681SAndroid Build Coastguard Worker   // same value.
360*9880d681SAndroid Build Coastguard Worker   if (CallVal != RetVal || CallIndices != RetIndices)
361*9880d681SAndroid Build Coastguard Worker     return false;
362*9880d681SAndroid Build Coastguard Worker 
363*9880d681SAndroid Build Coastguard Worker   // However, intervening truncates may have made the call non-tail. Make sure
364*9880d681SAndroid Build Coastguard Worker   // all the bits that are needed by the "ret" have been provided by the "tail
365*9880d681SAndroid Build Coastguard Worker   // call". FIXME: with sufficiently cunning bit-tracking, we could look through
366*9880d681SAndroid Build Coastguard Worker   // extensions too.
367*9880d681SAndroid Build Coastguard Worker   if (BitsProvided < BitsRequired ||
368*9880d681SAndroid Build Coastguard Worker       (!AllowDifferingSizes && BitsProvided != BitsRequired))
369*9880d681SAndroid Build Coastguard Worker     return false;
370*9880d681SAndroid Build Coastguard Worker 
371*9880d681SAndroid Build Coastguard Worker   return true;
372*9880d681SAndroid Build Coastguard Worker }
373*9880d681SAndroid Build Coastguard Worker 
374*9880d681SAndroid Build Coastguard Worker /// For an aggregate type, determine whether a given index is within bounds or
375*9880d681SAndroid Build Coastguard Worker /// not.
indexReallyValid(CompositeType * T,unsigned Idx)376*9880d681SAndroid Build Coastguard Worker static bool indexReallyValid(CompositeType *T, unsigned Idx) {
377*9880d681SAndroid Build Coastguard Worker   if (ArrayType *AT = dyn_cast<ArrayType>(T))
378*9880d681SAndroid Build Coastguard Worker     return Idx < AT->getNumElements();
379*9880d681SAndroid Build Coastguard Worker 
380*9880d681SAndroid Build Coastguard Worker   return Idx < cast<StructType>(T)->getNumElements();
381*9880d681SAndroid Build Coastguard Worker }
382*9880d681SAndroid Build Coastguard Worker 
383*9880d681SAndroid Build Coastguard Worker /// Move the given iterators to the next leaf type in depth first traversal.
384*9880d681SAndroid Build Coastguard Worker ///
385*9880d681SAndroid Build Coastguard Worker /// Performs a depth-first traversal of the type as specified by its arguments,
386*9880d681SAndroid Build Coastguard Worker /// stopping at the next leaf node (which may be a legitimate scalar type or an
387*9880d681SAndroid Build Coastguard Worker /// empty struct or array).
388*9880d681SAndroid Build Coastguard Worker ///
389*9880d681SAndroid Build Coastguard Worker /// @param SubTypes List of the partial components making up the type from
390*9880d681SAndroid Build Coastguard Worker /// outermost to innermost non-empty aggregate. The element currently
391*9880d681SAndroid Build Coastguard Worker /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
392*9880d681SAndroid Build Coastguard Worker ///
393*9880d681SAndroid Build Coastguard Worker /// @param Path Set of extractvalue indices leading from the outermost type
394*9880d681SAndroid Build Coastguard Worker /// (SubTypes[0]) to the leaf node currently represented.
395*9880d681SAndroid Build Coastguard Worker ///
396*9880d681SAndroid Build Coastguard Worker /// @returns true if a new type was found, false otherwise. Calling this
397*9880d681SAndroid Build Coastguard Worker /// function again on a finished iterator will repeatedly return
398*9880d681SAndroid Build Coastguard Worker /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
399*9880d681SAndroid Build Coastguard Worker /// aggregate or a non-aggregate
advanceToNextLeafType(SmallVectorImpl<CompositeType * > & SubTypes,SmallVectorImpl<unsigned> & Path)400*9880d681SAndroid Build Coastguard Worker static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
401*9880d681SAndroid Build Coastguard Worker                                   SmallVectorImpl<unsigned> &Path) {
402*9880d681SAndroid Build Coastguard Worker   // First march back up the tree until we can successfully increment one of the
403*9880d681SAndroid Build Coastguard Worker   // coordinates in Path.
404*9880d681SAndroid Build Coastguard Worker   while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
405*9880d681SAndroid Build Coastguard Worker     Path.pop_back();
406*9880d681SAndroid Build Coastguard Worker     SubTypes.pop_back();
407*9880d681SAndroid Build Coastguard Worker   }
408*9880d681SAndroid Build Coastguard Worker 
409*9880d681SAndroid Build Coastguard Worker   // If we reached the top, then the iterator is done.
410*9880d681SAndroid Build Coastguard Worker   if (Path.empty())
411*9880d681SAndroid Build Coastguard Worker     return false;
412*9880d681SAndroid Build Coastguard Worker 
413*9880d681SAndroid Build Coastguard Worker   // We know there's *some* valid leaf now, so march back down the tree picking
414*9880d681SAndroid Build Coastguard Worker   // out the left-most element at each node.
415*9880d681SAndroid Build Coastguard Worker   ++Path.back();
416*9880d681SAndroid Build Coastguard Worker   Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
417*9880d681SAndroid Build Coastguard Worker   while (DeeperType->isAggregateType()) {
418*9880d681SAndroid Build Coastguard Worker     CompositeType *CT = cast<CompositeType>(DeeperType);
419*9880d681SAndroid Build Coastguard Worker     if (!indexReallyValid(CT, 0))
420*9880d681SAndroid Build Coastguard Worker       return true;
421*9880d681SAndroid Build Coastguard Worker 
422*9880d681SAndroid Build Coastguard Worker     SubTypes.push_back(CT);
423*9880d681SAndroid Build Coastguard Worker     Path.push_back(0);
424*9880d681SAndroid Build Coastguard Worker 
425*9880d681SAndroid Build Coastguard Worker     DeeperType = CT->getTypeAtIndex(0U);
426*9880d681SAndroid Build Coastguard Worker   }
427*9880d681SAndroid Build Coastguard Worker 
428*9880d681SAndroid Build Coastguard Worker   return true;
429*9880d681SAndroid Build Coastguard Worker }
430*9880d681SAndroid Build Coastguard Worker 
431*9880d681SAndroid Build Coastguard Worker /// Find the first non-empty, scalar-like type in Next and setup the iterator
432*9880d681SAndroid Build Coastguard Worker /// components.
433*9880d681SAndroid Build Coastguard Worker ///
434*9880d681SAndroid Build Coastguard Worker /// Assuming Next is an aggregate of some kind, this function will traverse the
435*9880d681SAndroid Build Coastguard Worker /// tree from left to right (i.e. depth-first) looking for the first
436*9880d681SAndroid Build Coastguard Worker /// non-aggregate type which will play a role in function return.
437*9880d681SAndroid Build Coastguard Worker ///
438*9880d681SAndroid Build Coastguard Worker /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
439*9880d681SAndroid Build Coastguard Worker /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
440*9880d681SAndroid Build Coastguard Worker /// i32 in that type.
firstRealType(Type * Next,SmallVectorImpl<CompositeType * > & SubTypes,SmallVectorImpl<unsigned> & Path)441*9880d681SAndroid Build Coastguard Worker static bool firstRealType(Type *Next,
442*9880d681SAndroid Build Coastguard Worker                           SmallVectorImpl<CompositeType *> &SubTypes,
443*9880d681SAndroid Build Coastguard Worker                           SmallVectorImpl<unsigned> &Path) {
444*9880d681SAndroid Build Coastguard Worker   // First initialise the iterator components to the first "leaf" node
445*9880d681SAndroid Build Coastguard Worker   // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
446*9880d681SAndroid Build Coastguard Worker   // despite nominally being an aggregate).
447*9880d681SAndroid Build Coastguard Worker   while (Next->isAggregateType() &&
448*9880d681SAndroid Build Coastguard Worker          indexReallyValid(cast<CompositeType>(Next), 0)) {
449*9880d681SAndroid Build Coastguard Worker     SubTypes.push_back(cast<CompositeType>(Next));
450*9880d681SAndroid Build Coastguard Worker     Path.push_back(0);
451*9880d681SAndroid Build Coastguard Worker     Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
452*9880d681SAndroid Build Coastguard Worker   }
453*9880d681SAndroid Build Coastguard Worker 
454*9880d681SAndroid Build Coastguard Worker   // If there's no Path now, Next was originally scalar already (or empty
455*9880d681SAndroid Build Coastguard Worker   // leaf). We're done.
456*9880d681SAndroid Build Coastguard Worker   if (Path.empty())
457*9880d681SAndroid Build Coastguard Worker     return true;
458*9880d681SAndroid Build Coastguard Worker 
459*9880d681SAndroid Build Coastguard Worker   // Otherwise, use normal iteration to keep looking through the tree until we
460*9880d681SAndroid Build Coastguard Worker   // find a non-aggregate type.
461*9880d681SAndroid Build Coastguard Worker   while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
462*9880d681SAndroid Build Coastguard Worker     if (!advanceToNextLeafType(SubTypes, Path))
463*9880d681SAndroid Build Coastguard Worker       return false;
464*9880d681SAndroid Build Coastguard Worker   }
465*9880d681SAndroid Build Coastguard Worker 
466*9880d681SAndroid Build Coastguard Worker   return true;
467*9880d681SAndroid Build Coastguard Worker }
468*9880d681SAndroid Build Coastguard Worker 
469*9880d681SAndroid Build Coastguard Worker /// Set the iterator data-structures to the next non-empty, non-aggregate
470*9880d681SAndroid Build Coastguard Worker /// subtype.
nextRealType(SmallVectorImpl<CompositeType * > & SubTypes,SmallVectorImpl<unsigned> & Path)471*9880d681SAndroid Build Coastguard Worker static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
472*9880d681SAndroid Build Coastguard Worker                          SmallVectorImpl<unsigned> &Path) {
473*9880d681SAndroid Build Coastguard Worker   do {
474*9880d681SAndroid Build Coastguard Worker     if (!advanceToNextLeafType(SubTypes, Path))
475*9880d681SAndroid Build Coastguard Worker       return false;
476*9880d681SAndroid Build Coastguard Worker 
477*9880d681SAndroid Build Coastguard Worker     assert(!Path.empty() && "found a leaf but didn't set the path?");
478*9880d681SAndroid Build Coastguard Worker   } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
479*9880d681SAndroid Build Coastguard Worker 
480*9880d681SAndroid Build Coastguard Worker   return true;
481*9880d681SAndroid Build Coastguard Worker }
482*9880d681SAndroid Build Coastguard Worker 
483*9880d681SAndroid Build Coastguard Worker 
484*9880d681SAndroid Build Coastguard Worker /// Test if the given instruction is in a position to be optimized
485*9880d681SAndroid Build Coastguard Worker /// with a tail-call. This roughly means that it's in a block with
486*9880d681SAndroid Build Coastguard Worker /// a return and there's nothing that needs to be scheduled
487*9880d681SAndroid Build Coastguard Worker /// between it and the return.
488*9880d681SAndroid Build Coastguard Worker ///
489*9880d681SAndroid Build Coastguard Worker /// This function only tests target-independent requirements.
isInTailCallPosition(ImmutableCallSite CS,const TargetMachine & TM)490*9880d681SAndroid Build Coastguard Worker bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) {
491*9880d681SAndroid Build Coastguard Worker   const Instruction *I = CS.getInstruction();
492*9880d681SAndroid Build Coastguard Worker   const BasicBlock *ExitBB = I->getParent();
493*9880d681SAndroid Build Coastguard Worker   const TerminatorInst *Term = ExitBB->getTerminator();
494*9880d681SAndroid Build Coastguard Worker   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
495*9880d681SAndroid Build Coastguard Worker 
496*9880d681SAndroid Build Coastguard Worker   // The block must end in a return statement or unreachable.
497*9880d681SAndroid Build Coastguard Worker   //
498*9880d681SAndroid Build Coastguard Worker   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
499*9880d681SAndroid Build Coastguard Worker   // an unreachable, for now. The way tailcall optimization is currently
500*9880d681SAndroid Build Coastguard Worker   // implemented means it will add an epilogue followed by a jump. That is
501*9880d681SAndroid Build Coastguard Worker   // not profitable. Also, if the callee is a special function (e.g.
502*9880d681SAndroid Build Coastguard Worker   // longjmp on x86), it can end up causing miscompilation that has not
503*9880d681SAndroid Build Coastguard Worker   // been fully understood.
504*9880d681SAndroid Build Coastguard Worker   if (!Ret &&
505*9880d681SAndroid Build Coastguard Worker       (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
506*9880d681SAndroid Build Coastguard Worker     return false;
507*9880d681SAndroid Build Coastguard Worker 
508*9880d681SAndroid Build Coastguard Worker   // If I will have a chain, make sure no other instruction that will have a
509*9880d681SAndroid Build Coastguard Worker   // chain interposes between I and the return.
510*9880d681SAndroid Build Coastguard Worker   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
511*9880d681SAndroid Build Coastguard Worker       !isSafeToSpeculativelyExecute(I))
512*9880d681SAndroid Build Coastguard Worker     for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
513*9880d681SAndroid Build Coastguard Worker       if (&*BBI == I)
514*9880d681SAndroid Build Coastguard Worker         break;
515*9880d681SAndroid Build Coastguard Worker       // Debug info intrinsics do not get in the way of tail call optimization.
516*9880d681SAndroid Build Coastguard Worker       if (isa<DbgInfoIntrinsic>(BBI))
517*9880d681SAndroid Build Coastguard Worker         continue;
518*9880d681SAndroid Build Coastguard Worker       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
519*9880d681SAndroid Build Coastguard Worker           !isSafeToSpeculativelyExecute(&*BBI))
520*9880d681SAndroid Build Coastguard Worker         return false;
521*9880d681SAndroid Build Coastguard Worker     }
522*9880d681SAndroid Build Coastguard Worker 
523*9880d681SAndroid Build Coastguard Worker   const Function *F = ExitBB->getParent();
524*9880d681SAndroid Build Coastguard Worker   return returnTypeIsEligibleForTailCall(
525*9880d681SAndroid Build Coastguard Worker       F, I, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering());
526*9880d681SAndroid Build Coastguard Worker }
527*9880d681SAndroid Build Coastguard Worker 
returnTypeIsEligibleForTailCall(const Function * F,const Instruction * I,const ReturnInst * Ret,const TargetLoweringBase & TLI)528*9880d681SAndroid Build Coastguard Worker bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
529*9880d681SAndroid Build Coastguard Worker                                            const Instruction *I,
530*9880d681SAndroid Build Coastguard Worker                                            const ReturnInst *Ret,
531*9880d681SAndroid Build Coastguard Worker                                            const TargetLoweringBase &TLI) {
532*9880d681SAndroid Build Coastguard Worker   // If the block ends with a void return or unreachable, it doesn't matter
533*9880d681SAndroid Build Coastguard Worker   // what the call's return type is.
534*9880d681SAndroid Build Coastguard Worker   if (!Ret || Ret->getNumOperands() == 0) return true;
535*9880d681SAndroid Build Coastguard Worker 
536*9880d681SAndroid Build Coastguard Worker   // If the return value is undef, it doesn't matter what the call's
537*9880d681SAndroid Build Coastguard Worker   // return type is.
538*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(Ret->getOperand(0))) return true;
539*9880d681SAndroid Build Coastguard Worker 
540*9880d681SAndroid Build Coastguard Worker   // Make sure the attributes attached to each return are compatible.
541*9880d681SAndroid Build Coastguard Worker   AttrBuilder CallerAttrs(F->getAttributes(),
542*9880d681SAndroid Build Coastguard Worker                           AttributeSet::ReturnIndex);
543*9880d681SAndroid Build Coastguard Worker   AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
544*9880d681SAndroid Build Coastguard Worker                           AttributeSet::ReturnIndex);
545*9880d681SAndroid Build Coastguard Worker 
546*9880d681SAndroid Build Coastguard Worker   // Noalias is completely benign as far as calling convention goes, it
547*9880d681SAndroid Build Coastguard Worker   // shouldn't affect whether the call is a tail call.
548*9880d681SAndroid Build Coastguard Worker   CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias);
549*9880d681SAndroid Build Coastguard Worker   CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias);
550*9880d681SAndroid Build Coastguard Worker 
551*9880d681SAndroid Build Coastguard Worker   bool AllowDifferingSizes = true;
552*9880d681SAndroid Build Coastguard Worker   if (CallerAttrs.contains(Attribute::ZExt)) {
553*9880d681SAndroid Build Coastguard Worker     if (!CalleeAttrs.contains(Attribute::ZExt))
554*9880d681SAndroid Build Coastguard Worker       return false;
555*9880d681SAndroid Build Coastguard Worker 
556*9880d681SAndroid Build Coastguard Worker     AllowDifferingSizes = false;
557*9880d681SAndroid Build Coastguard Worker     CallerAttrs.removeAttribute(Attribute::ZExt);
558*9880d681SAndroid Build Coastguard Worker     CalleeAttrs.removeAttribute(Attribute::ZExt);
559*9880d681SAndroid Build Coastguard Worker   } else if (CallerAttrs.contains(Attribute::SExt)) {
560*9880d681SAndroid Build Coastguard Worker     if (!CalleeAttrs.contains(Attribute::SExt))
561*9880d681SAndroid Build Coastguard Worker       return false;
562*9880d681SAndroid Build Coastguard Worker 
563*9880d681SAndroid Build Coastguard Worker     AllowDifferingSizes = false;
564*9880d681SAndroid Build Coastguard Worker     CallerAttrs.removeAttribute(Attribute::SExt);
565*9880d681SAndroid Build Coastguard Worker     CalleeAttrs.removeAttribute(Attribute::SExt);
566*9880d681SAndroid Build Coastguard Worker   }
567*9880d681SAndroid Build Coastguard Worker 
568*9880d681SAndroid Build Coastguard Worker   // If they're still different, there's some facet we don't understand
569*9880d681SAndroid Build Coastguard Worker   // (currently only "inreg", but in future who knows). It may be OK but the
570*9880d681SAndroid Build Coastguard Worker   // only safe option is to reject the tail call.
571*9880d681SAndroid Build Coastguard Worker   if (CallerAttrs != CalleeAttrs)
572*9880d681SAndroid Build Coastguard Worker     return false;
573*9880d681SAndroid Build Coastguard Worker 
574*9880d681SAndroid Build Coastguard Worker   const Value *RetVal = Ret->getOperand(0), *CallVal = I;
575*9880d681SAndroid Build Coastguard Worker   SmallVector<unsigned, 4> RetPath, CallPath;
576*9880d681SAndroid Build Coastguard Worker   SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
577*9880d681SAndroid Build Coastguard Worker 
578*9880d681SAndroid Build Coastguard Worker   bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
579*9880d681SAndroid Build Coastguard Worker   bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
580*9880d681SAndroid Build Coastguard Worker 
581*9880d681SAndroid Build Coastguard Worker   // Nothing's actually returned, it doesn't matter what the callee put there
582*9880d681SAndroid Build Coastguard Worker   // it's a valid tail call.
583*9880d681SAndroid Build Coastguard Worker   if (RetEmpty)
584*9880d681SAndroid Build Coastguard Worker     return true;
585*9880d681SAndroid Build Coastguard Worker 
586*9880d681SAndroid Build Coastguard Worker   // Iterate pairwise through each of the value types making up the tail call
587*9880d681SAndroid Build Coastguard Worker   // and the corresponding return. For each one we want to know whether it's
588*9880d681SAndroid Build Coastguard Worker   // essentially going directly from the tail call to the ret, via operations
589*9880d681SAndroid Build Coastguard Worker   // that end up not generating any code.
590*9880d681SAndroid Build Coastguard Worker   //
591*9880d681SAndroid Build Coastguard Worker   // We allow a certain amount of covariance here. For example it's permitted
592*9880d681SAndroid Build Coastguard Worker   // for the tail call to define more bits than the ret actually cares about
593*9880d681SAndroid Build Coastguard Worker   // (e.g. via a truncate).
594*9880d681SAndroid Build Coastguard Worker   do {
595*9880d681SAndroid Build Coastguard Worker     if (CallEmpty) {
596*9880d681SAndroid Build Coastguard Worker       // We've exhausted the values produced by the tail call instruction, the
597*9880d681SAndroid Build Coastguard Worker       // rest are essentially undef. The type doesn't really matter, but we need
598*9880d681SAndroid Build Coastguard Worker       // *something*.
599*9880d681SAndroid Build Coastguard Worker       Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
600*9880d681SAndroid Build Coastguard Worker       CallVal = UndefValue::get(SlotType);
601*9880d681SAndroid Build Coastguard Worker     }
602*9880d681SAndroid Build Coastguard Worker 
603*9880d681SAndroid Build Coastguard Worker     // The manipulations performed when we're looking through an insertvalue or
604*9880d681SAndroid Build Coastguard Worker     // an extractvalue would happen at the front of the RetPath list, so since
605*9880d681SAndroid Build Coastguard Worker     // we have to copy it anyway it's more efficient to create a reversed copy.
606*9880d681SAndroid Build Coastguard Worker     SmallVector<unsigned, 4> TmpRetPath(RetPath.rbegin(), RetPath.rend());
607*9880d681SAndroid Build Coastguard Worker     SmallVector<unsigned, 4> TmpCallPath(CallPath.rbegin(), CallPath.rend());
608*9880d681SAndroid Build Coastguard Worker 
609*9880d681SAndroid Build Coastguard Worker     // Finally, we can check whether the value produced by the tail call at this
610*9880d681SAndroid Build Coastguard Worker     // index is compatible with the value we return.
611*9880d681SAndroid Build Coastguard Worker     if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
612*9880d681SAndroid Build Coastguard Worker                               AllowDifferingSizes, TLI,
613*9880d681SAndroid Build Coastguard Worker                               F->getParent()->getDataLayout()))
614*9880d681SAndroid Build Coastguard Worker       return false;
615*9880d681SAndroid Build Coastguard Worker 
616*9880d681SAndroid Build Coastguard Worker     CallEmpty  = !nextRealType(CallSubTypes, CallPath);
617*9880d681SAndroid Build Coastguard Worker   } while(nextRealType(RetSubTypes, RetPath));
618*9880d681SAndroid Build Coastguard Worker 
619*9880d681SAndroid Build Coastguard Worker   return true;
620*9880d681SAndroid Build Coastguard Worker }
621*9880d681SAndroid Build Coastguard Worker 
canBeOmittedFromSymbolTable(const GlobalValue * GV)622*9880d681SAndroid Build Coastguard Worker bool llvm::canBeOmittedFromSymbolTable(const GlobalValue *GV) {
623*9880d681SAndroid Build Coastguard Worker   if (!GV->hasLinkOnceODRLinkage())
624*9880d681SAndroid Build Coastguard Worker     return false;
625*9880d681SAndroid Build Coastguard Worker 
626*9880d681SAndroid Build Coastguard Worker   // We assume that anyone who sets global unnamed_addr on a non-constant knows
627*9880d681SAndroid Build Coastguard Worker   // what they're doing.
628*9880d681SAndroid Build Coastguard Worker   if (GV->hasGlobalUnnamedAddr())
629*9880d681SAndroid Build Coastguard Worker     return true;
630*9880d681SAndroid Build Coastguard Worker 
631*9880d681SAndroid Build Coastguard Worker   // If it is a non constant variable, it needs to be uniqued across shared
632*9880d681SAndroid Build Coastguard Worker   // objects.
633*9880d681SAndroid Build Coastguard Worker   if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
634*9880d681SAndroid Build Coastguard Worker     if (!Var->isConstant())
635*9880d681SAndroid Build Coastguard Worker       return false;
636*9880d681SAndroid Build Coastguard Worker   }
637*9880d681SAndroid Build Coastguard Worker 
638*9880d681SAndroid Build Coastguard Worker   return GV->hasAtLeastLocalUnnamedAddr();
639*9880d681SAndroid Build Coastguard Worker }
640*9880d681SAndroid Build Coastguard Worker 
collectFuncletMembers(DenseMap<const MachineBasicBlock *,int> & FuncletMembership,int Funclet,const MachineBasicBlock * MBB)641*9880d681SAndroid Build Coastguard Worker static void collectFuncletMembers(
642*9880d681SAndroid Build Coastguard Worker     DenseMap<const MachineBasicBlock *, int> &FuncletMembership, int Funclet,
643*9880d681SAndroid Build Coastguard Worker     const MachineBasicBlock *MBB) {
644*9880d681SAndroid Build Coastguard Worker   SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB};
645*9880d681SAndroid Build Coastguard Worker   while (!Worklist.empty()) {
646*9880d681SAndroid Build Coastguard Worker     const MachineBasicBlock *Visiting = Worklist.pop_back_val();
647*9880d681SAndroid Build Coastguard Worker     // Don't follow blocks which start new funclets.
648*9880d681SAndroid Build Coastguard Worker     if (Visiting->isEHPad() && Visiting != MBB)
649*9880d681SAndroid Build Coastguard Worker       continue;
650*9880d681SAndroid Build Coastguard Worker 
651*9880d681SAndroid Build Coastguard Worker     // Add this MBB to our funclet.
652*9880d681SAndroid Build Coastguard Worker     auto P = FuncletMembership.insert(std::make_pair(Visiting, Funclet));
653*9880d681SAndroid Build Coastguard Worker 
654*9880d681SAndroid Build Coastguard Worker     // Don't revisit blocks.
655*9880d681SAndroid Build Coastguard Worker     if (!P.second) {
656*9880d681SAndroid Build Coastguard Worker       assert(P.first->second == Funclet && "MBB is part of two funclets!");
657*9880d681SAndroid Build Coastguard Worker       continue;
658*9880d681SAndroid Build Coastguard Worker     }
659*9880d681SAndroid Build Coastguard Worker 
660*9880d681SAndroid Build Coastguard Worker     // Returns are boundaries where funclet transfer can occur, don't follow
661*9880d681SAndroid Build Coastguard Worker     // successors.
662*9880d681SAndroid Build Coastguard Worker     if (Visiting->isReturnBlock())
663*9880d681SAndroid Build Coastguard Worker       continue;
664*9880d681SAndroid Build Coastguard Worker 
665*9880d681SAndroid Build Coastguard Worker     for (const MachineBasicBlock *Succ : Visiting->successors())
666*9880d681SAndroid Build Coastguard Worker       Worklist.push_back(Succ);
667*9880d681SAndroid Build Coastguard Worker   }
668*9880d681SAndroid Build Coastguard Worker }
669*9880d681SAndroid Build Coastguard Worker 
670*9880d681SAndroid Build Coastguard Worker DenseMap<const MachineBasicBlock *, int>
getFuncletMembership(const MachineFunction & MF)671*9880d681SAndroid Build Coastguard Worker llvm::getFuncletMembership(const MachineFunction &MF) {
672*9880d681SAndroid Build Coastguard Worker   DenseMap<const MachineBasicBlock *, int> FuncletMembership;
673*9880d681SAndroid Build Coastguard Worker 
674*9880d681SAndroid Build Coastguard Worker   // We don't have anything to do if there aren't any EH pads.
675*9880d681SAndroid Build Coastguard Worker   if (!MF.getMMI().hasEHFunclets())
676*9880d681SAndroid Build Coastguard Worker     return FuncletMembership;
677*9880d681SAndroid Build Coastguard Worker 
678*9880d681SAndroid Build Coastguard Worker   int EntryBBNumber = MF.front().getNumber();
679*9880d681SAndroid Build Coastguard Worker   bool IsSEH = isAsynchronousEHPersonality(
680*9880d681SAndroid Build Coastguard Worker       classifyEHPersonality(MF.getFunction()->getPersonalityFn()));
681*9880d681SAndroid Build Coastguard Worker 
682*9880d681SAndroid Build Coastguard Worker   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
683*9880d681SAndroid Build Coastguard Worker   SmallVector<const MachineBasicBlock *, 16> FuncletBlocks;
684*9880d681SAndroid Build Coastguard Worker   SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks;
685*9880d681SAndroid Build Coastguard Worker   SmallVector<const MachineBasicBlock *, 16> SEHCatchPads;
686*9880d681SAndroid Build Coastguard Worker   SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors;
687*9880d681SAndroid Build Coastguard Worker   for (const MachineBasicBlock &MBB : MF) {
688*9880d681SAndroid Build Coastguard Worker     if (MBB.isEHFuncletEntry()) {
689*9880d681SAndroid Build Coastguard Worker       FuncletBlocks.push_back(&MBB);
690*9880d681SAndroid Build Coastguard Worker     } else if (IsSEH && MBB.isEHPad()) {
691*9880d681SAndroid Build Coastguard Worker       SEHCatchPads.push_back(&MBB);
692*9880d681SAndroid Build Coastguard Worker     } else if (MBB.pred_empty()) {
693*9880d681SAndroid Build Coastguard Worker       UnreachableBlocks.push_back(&MBB);
694*9880d681SAndroid Build Coastguard Worker     }
695*9880d681SAndroid Build Coastguard Worker 
696*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator();
697*9880d681SAndroid Build Coastguard Worker     // CatchPads are not funclets for SEH so do not consider CatchRet to
698*9880d681SAndroid Build Coastguard Worker     // transfer control to another funclet.
699*9880d681SAndroid Build Coastguard Worker     if (MBBI->getOpcode() != TII->getCatchReturnOpcode())
700*9880d681SAndroid Build Coastguard Worker       continue;
701*9880d681SAndroid Build Coastguard Worker 
702*9880d681SAndroid Build Coastguard Worker     // FIXME: SEH CatchPads are not necessarily in the parent function:
703*9880d681SAndroid Build Coastguard Worker     // they could be inside a finally block.
704*9880d681SAndroid Build Coastguard Worker     const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB();
705*9880d681SAndroid Build Coastguard Worker     const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB();
706*9880d681SAndroid Build Coastguard Worker     CatchRetSuccessors.push_back(
707*9880d681SAndroid Build Coastguard Worker         {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()});
708*9880d681SAndroid Build Coastguard Worker   }
709*9880d681SAndroid Build Coastguard Worker 
710*9880d681SAndroid Build Coastguard Worker   // We don't have anything to do if there aren't any EH pads.
711*9880d681SAndroid Build Coastguard Worker   if (FuncletBlocks.empty())
712*9880d681SAndroid Build Coastguard Worker     return FuncletMembership;
713*9880d681SAndroid Build Coastguard Worker 
714*9880d681SAndroid Build Coastguard Worker   // Identify all the basic blocks reachable from the function entry.
715*9880d681SAndroid Build Coastguard Worker   collectFuncletMembers(FuncletMembership, EntryBBNumber, &MF.front());
716*9880d681SAndroid Build Coastguard Worker   // All blocks not part of a funclet are in the parent function.
717*9880d681SAndroid Build Coastguard Worker   for (const MachineBasicBlock *MBB : UnreachableBlocks)
718*9880d681SAndroid Build Coastguard Worker     collectFuncletMembers(FuncletMembership, EntryBBNumber, MBB);
719*9880d681SAndroid Build Coastguard Worker   // Next, identify all the blocks inside the funclets.
720*9880d681SAndroid Build Coastguard Worker   for (const MachineBasicBlock *MBB : FuncletBlocks)
721*9880d681SAndroid Build Coastguard Worker     collectFuncletMembers(FuncletMembership, MBB->getNumber(), MBB);
722*9880d681SAndroid Build Coastguard Worker   // SEH CatchPads aren't really funclets, handle them separately.
723*9880d681SAndroid Build Coastguard Worker   for (const MachineBasicBlock *MBB : SEHCatchPads)
724*9880d681SAndroid Build Coastguard Worker     collectFuncletMembers(FuncletMembership, EntryBBNumber, MBB);
725*9880d681SAndroid Build Coastguard Worker   // Finally, identify all the targets of a catchret.
726*9880d681SAndroid Build Coastguard Worker   for (std::pair<const MachineBasicBlock *, int> CatchRetPair :
727*9880d681SAndroid Build Coastguard Worker        CatchRetSuccessors)
728*9880d681SAndroid Build Coastguard Worker     collectFuncletMembers(FuncletMembership, CatchRetPair.second,
729*9880d681SAndroid Build Coastguard Worker                           CatchRetPair.first);
730*9880d681SAndroid Build Coastguard Worker   return FuncletMembership;
731*9880d681SAndroid Build Coastguard Worker }
732