150f02cb2SNick Lewycky //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
2450aa64fSDan Gohman //
3450aa64fSDan Gohman //                     The LLVM Compiler Infrastructure
4450aa64fSDan Gohman //
5450aa64fSDan Gohman // This file is distributed under the University of Illinois Open Source
6450aa64fSDan Gohman // License. See LICENSE.TXT for details.
7450aa64fSDan Gohman //
8450aa64fSDan Gohman //===----------------------------------------------------------------------===//
9450aa64fSDan Gohman //
10db5028bdSEric Christopher // This file defines several CodeGen-specific LLVM IR analysis utilities.
11450aa64fSDan Gohman //
12450aa64fSDan Gohman //===----------------------------------------------------------------------===//
13450aa64fSDan Gohman 
1409fc276dSEric Christopher #include "llvm/CodeGen/Analysis.h"
15dda00098SEric Christopher #include "llvm/Analysis/ValueTracking.h"
16ed0881b2SChandler Carruth #include "llvm/CodeGen/MachineFunction.h"
17576d36aeSEric Christopher #include "llvm/CodeGen/SelectionDAG.h"
189fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
199fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
209fb823bbSChandler Carruth #include "llvm/IR/Function.h"
219fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
229fb823bbSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
239fb823bbSChandler Carruth #include "llvm/IR/LLVMContext.h"
249fb823bbSChandler Carruth #include "llvm/IR/Module.h"
25450aa64fSDan Gohman #include "llvm/Support/ErrorHandling.h"
26450aa64fSDan Gohman #include "llvm/Support/MathExtras.h"
27ed0881b2SChandler Carruth #include "llvm/Target/TargetLowering.h"
28450aa64fSDan Gohman using namespace llvm;
29450aa64fSDan Gohman 
30450aa64fSDan Gohman /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
31450aa64fSDan Gohman /// of insertvalue or extractvalue indices that identify a member, return
32450aa64fSDan Gohman /// the linearized index of the start of the member.
33450aa64fSDan Gohman ///
34229907cdSChris Lattner unsigned llvm::ComputeLinearIndex(Type *Ty,
35450aa64fSDan Gohman                                   const unsigned *Indices,
36450aa64fSDan Gohman                                   const unsigned *IndicesEnd,
37450aa64fSDan Gohman                                   unsigned CurIndex) {
38450aa64fSDan Gohman   // Base case: We're done.
39450aa64fSDan Gohman   if (Indices && Indices == IndicesEnd)
40450aa64fSDan Gohman     return CurIndex;
41450aa64fSDan Gohman 
42450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
43229907cdSChris Lattner   if (StructType *STy = dyn_cast<StructType>(Ty)) {
44450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
45450aa64fSDan Gohman                                       EI = EB,
46450aa64fSDan Gohman                                       EE = STy->element_end();
47450aa64fSDan Gohman         EI != EE; ++EI) {
48450aa64fSDan Gohman       if (Indices && *Indices == unsigned(EI - EB))
49aadc5596SDan Gohman         return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
50c0196b1bSCraig Topper       CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
51450aa64fSDan Gohman     }
52450aa64fSDan Gohman     return CurIndex;
53450aa64fSDan Gohman   }
54450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
55229907cdSChris Lattner   else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
56229907cdSChris Lattner     Type *EltTy = ATy->getElementType();
57450aa64fSDan Gohman     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
58450aa64fSDan Gohman       if (Indices && *Indices == i)
59aadc5596SDan Gohman         return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
60c0196b1bSCraig Topper       CurIndex = ComputeLinearIndex(EltTy, nullptr, nullptr, CurIndex);
61450aa64fSDan Gohman     }
62450aa64fSDan Gohman     return CurIndex;
63450aa64fSDan Gohman   }
64450aa64fSDan Gohman   // We haven't found the type we're looking for, so keep searching.
65450aa64fSDan Gohman   return CurIndex + 1;
66450aa64fSDan Gohman }
67450aa64fSDan Gohman 
68450aa64fSDan Gohman /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
69450aa64fSDan Gohman /// EVTs that represent all the individual underlying
70450aa64fSDan Gohman /// non-aggregate types that comprise it.
71450aa64fSDan Gohman ///
72450aa64fSDan Gohman /// If Offsets is non-null, it points to a vector to be filled in
73450aa64fSDan Gohman /// with the in-memory offsets of each of the individual values.
74450aa64fSDan Gohman ///
75229907cdSChris Lattner void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
76450aa64fSDan Gohman                            SmallVectorImpl<EVT> &ValueVTs,
77450aa64fSDan Gohman                            SmallVectorImpl<uint64_t> *Offsets,
78450aa64fSDan Gohman                            uint64_t StartingOffset) {
79450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
80229907cdSChris Lattner   if (StructType *STy = dyn_cast<StructType>(Ty)) {
81cdfe20b9SMicah Villmow     const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy);
82450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
83450aa64fSDan Gohman                                       EI = EB,
84450aa64fSDan Gohman                                       EE = STy->element_end();
85450aa64fSDan Gohman          EI != EE; ++EI)
86450aa64fSDan Gohman       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
87450aa64fSDan Gohman                       StartingOffset + SL->getElementOffset(EI - EB));
88450aa64fSDan Gohman     return;
89450aa64fSDan Gohman   }
90450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
91229907cdSChris Lattner   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
92229907cdSChris Lattner     Type *EltTy = ATy->getElementType();
93cdfe20b9SMicah Villmow     uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy);
94450aa64fSDan Gohman     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
95450aa64fSDan Gohman       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
96450aa64fSDan Gohman                       StartingOffset + i * EltSize);
97450aa64fSDan Gohman     return;
98450aa64fSDan Gohman   }
99450aa64fSDan Gohman   // Interpret void as zero return values.
100450aa64fSDan Gohman   if (Ty->isVoidTy())
101450aa64fSDan Gohman     return;
102450aa64fSDan Gohman   // Base case: we can get an EVT for this LLVM IR type.
103450aa64fSDan Gohman   ValueVTs.push_back(TLI.getValueType(Ty));
104450aa64fSDan Gohman   if (Offsets)
105450aa64fSDan Gohman     Offsets->push_back(StartingOffset);
106450aa64fSDan Gohman }
107450aa64fSDan Gohman 
108450aa64fSDan Gohman /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
109450aa64fSDan Gohman GlobalVariable *llvm::ExtractTypeInfo(Value *V) {
110450aa64fSDan Gohman   V = V->stripPointerCasts();
111450aa64fSDan Gohman   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
112450aa64fSDan Gohman 
113fa60b0eeSBill Wendling   if (GV && GV->getName() == "llvm.eh.catch.all.value") {
114450aa64fSDan Gohman     assert(GV->hasInitializer() &&
115450aa64fSDan Gohman            "The EH catch-all value must have an initializer");
116450aa64fSDan Gohman     Value *Init = GV->getInitializer();
117450aa64fSDan Gohman     GV = dyn_cast<GlobalVariable>(Init);
118450aa64fSDan Gohman     if (!GV) V = cast<ConstantPointerNull>(Init);
119450aa64fSDan Gohman   }
120450aa64fSDan Gohman 
121450aa64fSDan Gohman   assert((GV || isa<ConstantPointerNull>(V)) &&
122450aa64fSDan Gohman          "TypeInfo must be a global variable or NULL");
123450aa64fSDan Gohman   return GV;
124450aa64fSDan Gohman }
125450aa64fSDan Gohman 
126450aa64fSDan Gohman /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
127450aa64fSDan Gohman /// processed uses a memory 'm' constraint.
128450aa64fSDan Gohman bool
129e8360b71SJohn Thompson llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
130450aa64fSDan Gohman                                 const TargetLowering &TLI) {
131450aa64fSDan Gohman   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
132450aa64fSDan Gohman     InlineAsm::ConstraintInfo &CI = CInfos[i];
133450aa64fSDan Gohman     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
134450aa64fSDan Gohman       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
135450aa64fSDan Gohman       if (CType == TargetLowering::C_Memory)
136450aa64fSDan Gohman         return true;
137450aa64fSDan Gohman     }
138450aa64fSDan Gohman 
139450aa64fSDan Gohman     // Indirect operand accesses access memory.
140450aa64fSDan Gohman     if (CI.isIndirect)
141450aa64fSDan Gohman       return true;
142450aa64fSDan Gohman   }
143450aa64fSDan Gohman 
144450aa64fSDan Gohman   return false;
145450aa64fSDan Gohman }
146450aa64fSDan Gohman 
147450aa64fSDan Gohman /// getFCmpCondCode - Return the ISD condition code corresponding to
148450aa64fSDan Gohman /// the given LLVM IR floating-point condition code.  This includes
149450aa64fSDan Gohman /// consideration of global floating-point math flags.
150450aa64fSDan Gohman ///
151450aa64fSDan Gohman ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
152450aa64fSDan Gohman   switch (Pred) {
15350f02cb2SNick Lewycky   case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
15450f02cb2SNick Lewycky   case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
15550f02cb2SNick Lewycky   case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
15650f02cb2SNick Lewycky   case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
15750f02cb2SNick Lewycky   case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
15850f02cb2SNick Lewycky   case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
15950f02cb2SNick Lewycky   case FCmpInst::FCMP_ONE:   return ISD::SETONE;
16050f02cb2SNick Lewycky   case FCmpInst::FCMP_ORD:   return ISD::SETO;
16150f02cb2SNick Lewycky   case FCmpInst::FCMP_UNO:   return ISD::SETUO;
16250f02cb2SNick Lewycky   case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
16350f02cb2SNick Lewycky   case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
16450f02cb2SNick Lewycky   case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
16550f02cb2SNick Lewycky   case FCmpInst::FCMP_ULT:   return ISD::SETULT;
16650f02cb2SNick Lewycky   case FCmpInst::FCMP_ULE:   return ISD::SETULE;
16750f02cb2SNick Lewycky   case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
16850f02cb2SNick Lewycky   case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
16946a9f016SDavid Blaikie   default: llvm_unreachable("Invalid FCmp predicate opcode!");
170450aa64fSDan Gohman   }
17150f02cb2SNick Lewycky }
17250f02cb2SNick Lewycky 
17350f02cb2SNick Lewycky ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
17450f02cb2SNick Lewycky   switch (CC) {
17550f02cb2SNick Lewycky     case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
17650f02cb2SNick Lewycky     case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
17750f02cb2SNick Lewycky     case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
17850f02cb2SNick Lewycky     case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
17950f02cb2SNick Lewycky     case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
18050f02cb2SNick Lewycky     case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
18146a9f016SDavid Blaikie     default: return CC;
18250f02cb2SNick Lewycky   }
183450aa64fSDan Gohman }
184450aa64fSDan Gohman 
185450aa64fSDan Gohman /// getICmpCondCode - Return the ISD condition code corresponding to
186450aa64fSDan Gohman /// the given LLVM IR integer condition code.
187450aa64fSDan Gohman ///
188450aa64fSDan Gohman ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
189450aa64fSDan Gohman   switch (Pred) {
190450aa64fSDan Gohman   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
191450aa64fSDan Gohman   case ICmpInst::ICMP_NE:  return ISD::SETNE;
192450aa64fSDan Gohman   case ICmpInst::ICMP_SLE: return ISD::SETLE;
193450aa64fSDan Gohman   case ICmpInst::ICMP_ULE: return ISD::SETULE;
194450aa64fSDan Gohman   case ICmpInst::ICMP_SGE: return ISD::SETGE;
195450aa64fSDan Gohman   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
196450aa64fSDan Gohman   case ICmpInst::ICMP_SLT: return ISD::SETLT;
197450aa64fSDan Gohman   case ICmpInst::ICMP_ULT: return ISD::SETULT;
198450aa64fSDan Gohman   case ICmpInst::ICMP_SGT: return ISD::SETGT;
199450aa64fSDan Gohman   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
200450aa64fSDan Gohman   default:
201450aa64fSDan Gohman     llvm_unreachable("Invalid ICmp predicate opcode!");
202450aa64fSDan Gohman   }
203450aa64fSDan Gohman }
204450aa64fSDan Gohman 
205ffc44549SStephen Lin static bool isNoopBitcast(Type *T1, Type *T2,
206c0659fadSMichael Gottesman                           const TargetLoweringBase& TLI) {
207ffc44549SStephen Lin   return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
208ffc44549SStephen Lin          (isa<VectorType>(T1) && isa<VectorType>(T2) &&
209ffc44549SStephen Lin           TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
210ffc44549SStephen Lin }
2114f3615deSChris Lattner 
212a4415854STim Northover /// Look through operations that will be free to find the earliest source of
213a4415854STim Northover /// this value.
214a4415854STim Northover ///
215a4415854STim Northover /// @param ValLoc If V has aggegate type, we will be interested in a particular
216a4415854STim Northover /// scalar component. This records its address; the reverse of this list gives a
217a4415854STim Northover /// sequence of indices appropriate for an extractvalue to locate the important
218a4415854STim Northover /// value. This value is updated during the function and on exit will indicate
219a4415854STim Northover /// similar information for the Value returned.
220a4415854STim Northover ///
221a4415854STim Northover /// @param DataBits If this function looks through truncate instructions, this
222a4415854STim Northover /// will record the smallest size attained.
223a4415854STim Northover static const Value *getNoopInput(const Value *V,
224a4415854STim Northover                                  SmallVectorImpl<unsigned> &ValLoc,
225a4415854STim Northover                                  unsigned &DataBits,
226c0659fadSMichael Gottesman                                  const TargetLoweringBase &TLI) {
227ffc44549SStephen Lin   while (true) {
228ffc44549SStephen Lin     // Try to look through V1; if V1 is not an instruction, it can't be looked
229ffc44549SStephen Lin     // through.
230a4415854STim Northover     const Instruction *I = dyn_cast<Instruction>(V);
231a4415854STim Northover     if (!I || I->getNumOperands() == 0) return V;
232c0196b1bSCraig Topper     const Value *NoopInput = nullptr;
233a4415854STim Northover 
234182fe3eeSChris Lattner     Value *Op = I->getOperand(0);
235a4415854STim Northover     if (isa<BitCastInst>(I)) {
2364f3615deSChris Lattner       // Look through truly no-op bitcasts.
237ffc44549SStephen Lin       if (isNoopBitcast(Op->getType(), I->getType(), TLI))
238ffc44549SStephen Lin         NoopInput = Op;
239ffc44549SStephen Lin     } else if (isa<GetElementPtrInst>(I)) {
240ffc44549SStephen Lin       // Look through getelementptr
241ffc44549SStephen Lin       if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
242ffc44549SStephen Lin         NoopInput = Op;
243ffc44549SStephen Lin     } else if (isa<IntToPtrInst>(I)) {
244182fe3eeSChris Lattner       // Look through inttoptr.
245ffc44549SStephen Lin       // Make sure this isn't a truncating or extending cast.  We could
246ffc44549SStephen Lin       // support this eventually, but don't bother for now.
247ffc44549SStephen Lin       if (!isa<VectorType>(I->getType()) &&
248ffc44549SStephen Lin           TLI.getPointerTy().getSizeInBits() ==
249182fe3eeSChris Lattner           cast<IntegerType>(Op->getType())->getBitWidth())
250ffc44549SStephen Lin         NoopInput = Op;
251ffc44549SStephen Lin     } else if (isa<PtrToIntInst>(I)) {
252182fe3eeSChris Lattner       // Look through ptrtoint.
253ffc44549SStephen Lin       // Make sure this isn't a truncating or extending cast.  We could
254ffc44549SStephen Lin       // support this eventually, but don't bother for now.
255ffc44549SStephen Lin       if (!isa<VectorType>(I->getType()) &&
256ffc44549SStephen Lin           TLI.getPointerTy().getSizeInBits() ==
257182fe3eeSChris Lattner           cast<IntegerType>(I->getType())->getBitWidth())
258ffc44549SStephen Lin         NoopInput = Op;
259a4415854STim Northover     } else if (isa<TruncInst>(I) &&
260a4415854STim Northover                TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
261a4415854STim Northover       DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
262a4415854STim Northover       NoopInput = Op;
263b8bd232aSStephen Lin     } else if (isa<CallInst>(I)) {
264a4415854STim Northover       // Look through call (skipping callee)
265a4415854STim Northover       for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1;
266b8bd232aSStephen Lin            i != e; ++i) {
267b8bd232aSStephen Lin         unsigned attrInd = i - I->op_begin() + 1;
268b8bd232aSStephen Lin         if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
269b8bd232aSStephen Lin             isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
270b8bd232aSStephen Lin           NoopInput = *i;
271b8bd232aSStephen Lin           break;
272b8bd232aSStephen Lin         }
273b8bd232aSStephen Lin       }
274b8bd232aSStephen Lin     } else if (isa<InvokeInst>(I)) {
275a4415854STim Northover       // Look through invoke (skipping BB, BB, Callee)
276a4415854STim Northover       for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3;
277b8bd232aSStephen Lin            i != e; ++i) {
278b8bd232aSStephen Lin         unsigned attrInd = i - I->op_begin() + 1;
279b8bd232aSStephen Lin         if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
280b8bd232aSStephen Lin             isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
281b8bd232aSStephen Lin           NoopInput = *i;
282b8bd232aSStephen Lin           break;
283b8bd232aSStephen Lin         }
284b8bd232aSStephen Lin       }
285a4415854STim Northover     } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
286a4415854STim Northover       // Value may come from either the aggregate or the scalar
287a4415854STim Northover       ArrayRef<unsigned> InsertLoc = IVI->getIndices();
288a4415854STim Northover       if (std::equal(InsertLoc.rbegin(), InsertLoc.rend(),
289a4415854STim Northover                      ValLoc.rbegin())) {
290a4415854STim Northover         // The type being inserted is a nested sub-type of the aggregate; we
291a4415854STim Northover         // have to remove those initial indices to get the location we're
292a4415854STim Northover         // interested in for the operand.
293a4415854STim Northover         ValLoc.resize(ValLoc.size() - InsertLoc.size());
294a4415854STim Northover         NoopInput = IVI->getInsertedValueOperand();
295a4415854STim Northover       } else {
296a4415854STim Northover         // The struct we're inserting into has the value we're interested in, no
297a4415854STim Northover         // change of address.
298a4415854STim Northover         NoopInput = Op;
299a4415854STim Northover       }
300a4415854STim Northover     } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
301a4415854STim Northover       // The part we're interested in will inevitably be some sub-section of the
302a4415854STim Northover       // previous aggregate. Combine the two paths to obtain the true address of
303a4415854STim Northover       // our element.
304a4415854STim Northover       ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
305a4415854STim Northover       std::copy(ExtractLoc.rbegin(), ExtractLoc.rend(),
306a4415854STim Northover                 std::back_inserter(ValLoc));
307a4415854STim Northover       NoopInput = Op;
308a4415854STim Northover     }
309a4415854STim Northover     // Terminate if we couldn't find anything to look through.
310a4415854STim Northover     if (!NoopInput)
311a4415854STim Northover       return V;
312a4415854STim Northover 
313a4415854STim Northover     V = NoopInput;
314ffc44549SStephen Lin   }
315182fe3eeSChris Lattner }
316182fe3eeSChris Lattner 
317a4415854STim Northover /// Return true if this scalar return value only has bits discarded on its path
318a4415854STim Northover /// from the "tail call" to the "ret". This includes the obvious noop
319a4415854STim Northover /// instructions handled by getNoopInput above as well as free truncations (or
320a4415854STim Northover /// extensions prior to the call).
321a4415854STim Northover static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
322a4415854STim Northover                                  SmallVectorImpl<unsigned> &RetIndices,
323a4415854STim Northover                                  SmallVectorImpl<unsigned> &CallIndices,
324707d68f0STim Northover                                  bool AllowDifferingSizes,
325a4415854STim Northover                                  const TargetLoweringBase &TLI) {
3264f3615deSChris Lattner 
327a4415854STim Northover   // Trace the sub-value needed by the return value as far back up the graph as
328a4415854STim Northover   // possible, in the hope that it will intersect with the value produced by the
329a4415854STim Northover   // call. In the simple case with no "returned" attribute, the hope is actually
330a4415854STim Northover   // that we end up back at the tail call instruction itself.
331a4415854STim Northover   unsigned BitsRequired = UINT_MAX;
332a4415854STim Northover   RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI);
333ffc44549SStephen Lin 
334a4415854STim Northover   // If this slot in the value returned is undef, it doesn't matter what the
335a4415854STim Northover   // call puts there, it'll be fine.
336a4415854STim Northover   if (isa<UndefValue>(RetVal))
337a4415854STim Northover     return true;
338ffc44549SStephen Lin 
339a4415854STim Northover   // Now do a similar search up through the graph to find where the value
340a4415854STim Northover   // actually returned by the "tail call" comes from. In the simple case without
341a4415854STim Northover   // a "returned" attribute, the search will be blocked immediately and the loop
342a4415854STim Northover   // a Noop.
343a4415854STim Northover   unsigned BitsProvided = UINT_MAX;
344a4415854STim Northover   CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI);
345a4415854STim Northover 
346a4415854STim Northover   // There's no hope if we can't actually trace them to (the same part of!) the
347a4415854STim Northover   // same value.
348a4415854STim Northover   if (CallVal != RetVal || CallIndices != RetIndices)
349a4415854STim Northover     return false;
350a4415854STim Northover 
351a4415854STim Northover   // However, intervening truncates may have made the call non-tail. Make sure
352a4415854STim Northover   // all the bits that are needed by the "ret" have been provided by the "tail
353a4415854STim Northover   // call". FIXME: with sufficiently cunning bit-tracking, we could look through
354a4415854STim Northover   // extensions too.
355707d68f0STim Northover   if (BitsProvided < BitsRequired ||
356707d68f0STim Northover       (!AllowDifferingSizes && BitsProvided != BitsRequired))
357a4415854STim Northover     return false;
358a4415854STim Northover 
359ffc44549SStephen Lin   return true;
360ffc44549SStephen Lin }
361a4415854STim Northover 
362a4415854STim Northover /// For an aggregate type, determine whether a given index is within bounds or
363a4415854STim Northover /// not.
364a4415854STim Northover static bool indexReallyValid(CompositeType *T, unsigned Idx) {
365a4415854STim Northover   if (ArrayType *AT = dyn_cast<ArrayType>(T))
366a4415854STim Northover     return Idx < AT->getNumElements();
367a4415854STim Northover 
368a4415854STim Northover   return Idx < cast<StructType>(T)->getNumElements();
369ffc44549SStephen Lin }
370a4415854STim Northover 
371a4415854STim Northover /// Move the given iterators to the next leaf type in depth first traversal.
372a4415854STim Northover ///
373a4415854STim Northover /// Performs a depth-first traversal of the type as specified by its arguments,
374a4415854STim Northover /// stopping at the next leaf node (which may be a legitimate scalar type or an
375a4415854STim Northover /// empty struct or array).
376a4415854STim Northover ///
377a4415854STim Northover /// @param SubTypes List of the partial components making up the type from
378a4415854STim Northover /// outermost to innermost non-empty aggregate. The element currently
379a4415854STim Northover /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
380a4415854STim Northover ///
381a4415854STim Northover /// @param Path Set of extractvalue indices leading from the outermost type
382a4415854STim Northover /// (SubTypes[0]) to the leaf node currently represented.
383a4415854STim Northover ///
384a4415854STim Northover /// @returns true if a new type was found, false otherwise. Calling this
385a4415854STim Northover /// function again on a finished iterator will repeatedly return
386a4415854STim Northover /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
387a4415854STim Northover /// aggregate or a non-aggregate
388df03449aSBenjamin Kramer static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
389a4415854STim Northover                                   SmallVectorImpl<unsigned> &Path) {
390a4415854STim Northover   // First march back up the tree until we can successfully increment one of the
391a4415854STim Northover   // coordinates in Path.
392a4415854STim Northover   while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
393a4415854STim Northover     Path.pop_back();
394a4415854STim Northover     SubTypes.pop_back();
395a4415854STim Northover   }
396a4415854STim Northover 
397a4415854STim Northover   // If we reached the top, then the iterator is done.
398a4415854STim Northover   if (Path.empty())
399a4415854STim Northover     return false;
400a4415854STim Northover 
401a4415854STim Northover   // We know there's *some* valid leaf now, so march back down the tree picking
402a4415854STim Northover   // out the left-most element at each node.
403a4415854STim Northover   ++Path.back();
404a4415854STim Northover   Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
405a4415854STim Northover   while (DeeperType->isAggregateType()) {
406a4415854STim Northover     CompositeType *CT = cast<CompositeType>(DeeperType);
407a4415854STim Northover     if (!indexReallyValid(CT, 0))
408a4415854STim Northover       return true;
409a4415854STim Northover 
410a4415854STim Northover     SubTypes.push_back(CT);
411a4415854STim Northover     Path.push_back(0);
412a4415854STim Northover 
413a4415854STim Northover     DeeperType = CT->getTypeAtIndex(0U);
414a4415854STim Northover   }
415a4415854STim Northover 
416ffc44549SStephen Lin   return true;
417ffc44549SStephen Lin }
418a4415854STim Northover 
419a4415854STim Northover /// Find the first non-empty, scalar-like type in Next and setup the iterator
420a4415854STim Northover /// components.
421a4415854STim Northover ///
422a4415854STim Northover /// Assuming Next is an aggregate of some kind, this function will traverse the
423a4415854STim Northover /// tree from left to right (i.e. depth-first) looking for the first
424a4415854STim Northover /// non-aggregate type which will play a role in function return.
425a4415854STim Northover ///
426a4415854STim Northover /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
427a4415854STim Northover /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
428a4415854STim Northover /// i32 in that type.
429a4415854STim Northover static bool firstRealType(Type *Next,
430a4415854STim Northover                           SmallVectorImpl<CompositeType *> &SubTypes,
431a4415854STim Northover                           SmallVectorImpl<unsigned> &Path) {
432a4415854STim Northover   // First initialise the iterator components to the first "leaf" node
433a4415854STim Northover   // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
434a4415854STim Northover   // despite nominally being an aggregate).
435a4415854STim Northover   while (Next->isAggregateType() &&
436a4415854STim Northover          indexReallyValid(cast<CompositeType>(Next), 0)) {
437a4415854STim Northover     SubTypes.push_back(cast<CompositeType>(Next));
438a4415854STim Northover     Path.push_back(0);
439a4415854STim Northover     Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
440ffc44549SStephen Lin   }
441ffc44549SStephen Lin 
442a4415854STim Northover   // If there's no Path now, Next was originally scalar already (or empty
443a4415854STim Northover   // leaf). We're done.
444a4415854STim Northover   if (Path.empty())
445a4415854STim Northover     return true;
446ffc44549SStephen Lin 
447a4415854STim Northover   // Otherwise, use normal iteration to keep looking through the tree until we
448a4415854STim Northover   // find a non-aggregate type.
449a4415854STim Northover   while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
450a4415854STim Northover     if (!advanceToNextLeafType(SubTypes, Path))
451ffc44549SStephen Lin       return false;
452ffc44549SStephen Lin   }
4534f3615deSChris Lattner 
454a4415854STim Northover   return true;
455a4415854STim Northover }
456a4415854STim Northover 
457a4415854STim Northover /// Set the iterator data-structures to the next non-empty, non-aggregate
458a4415854STim Northover /// subtype.
459df03449aSBenjamin Kramer static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
460a4415854STim Northover                          SmallVectorImpl<unsigned> &Path) {
461a4415854STim Northover   do {
462a4415854STim Northover     if (!advanceToNextLeafType(SubTypes, Path))
463a4415854STim Northover       return false;
464a4415854STim Northover 
465a4415854STim Northover     assert(!Path.empty() && "found a leaf but didn't set the path?");
466a4415854STim Northover   } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
467a4415854STim Northover 
468a4415854STim Northover   return true;
469a4415854STim Northover }
470a4415854STim Northover 
471a4415854STim Northover 
472450aa64fSDan Gohman /// Test if the given instruction is in a position to be optimized
473450aa64fSDan Gohman /// with a tail-call. This roughly means that it's in a block with
474450aa64fSDan Gohman /// a return and there's nothing that needs to be scheduled
475450aa64fSDan Gohman /// between it and the return.
476450aa64fSDan Gohman ///
477450aa64fSDan Gohman /// This function only tests target-independent requirements.
478*4ce9863dSJuergen Ributzka bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM,
479*4ce9863dSJuergen Ributzka                                 const TargetLoweringBase &TLI) {
480450aa64fSDan Gohman   const Instruction *I = CS.getInstruction();
481450aa64fSDan Gohman   const BasicBlock *ExitBB = I->getParent();
482450aa64fSDan Gohman   const TerminatorInst *Term = ExitBB->getTerminator();
483450aa64fSDan Gohman   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
484450aa64fSDan Gohman 
485450aa64fSDan Gohman   // The block must end in a return statement or unreachable.
486450aa64fSDan Gohman   //
487450aa64fSDan Gohman   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
488450aa64fSDan Gohman   // an unreachable, for now. The way tailcall optimization is currently
489450aa64fSDan Gohman   // implemented means it will add an epilogue followed by a jump. That is
490450aa64fSDan Gohman   // not profitable. Also, if the callee is a special function (e.g.
491450aa64fSDan Gohman   // longjmp on x86), it can end up causing miscompilation that has not
492450aa64fSDan Gohman   // been fully understood.
493450aa64fSDan Gohman   if (!Ret &&
494*4ce9863dSJuergen Ributzka       (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
4954f3615deSChris Lattner     return false;
496450aa64fSDan Gohman 
497450aa64fSDan Gohman   // If I will have a chain, make sure no other instruction that will have a
498450aa64fSDan Gohman   // chain interposes between I and the return.
499450aa64fSDan Gohman   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
50075d7d5e9SDan Gohman       !isSafeToSpeculativelyExecute(I))
501b6d0bd48SBenjamin Kramer     for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
502450aa64fSDan Gohman       if (&*BBI == I)
503450aa64fSDan Gohman         break;
504450aa64fSDan Gohman       // Debug info intrinsics do not get in the way of tail call optimization.
505450aa64fSDan Gohman       if (isa<DbgInfoIntrinsic>(BBI))
506450aa64fSDan Gohman         continue;
507450aa64fSDan Gohman       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
50875d7d5e9SDan Gohman           !isSafeToSpeculativelyExecute(BBI))
509450aa64fSDan Gohman         return false;
510450aa64fSDan Gohman     }
511450aa64fSDan Gohman 
512*4ce9863dSJuergen Ributzka   return returnTypeIsEligibleForTailCall(ExitBB->getParent(), I, Ret, TLI);
513ce0e4c26SMichael Gottesman }
514ce0e4c26SMichael Gottesman 
515ce0e4c26SMichael Gottesman bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
516ce0e4c26SMichael Gottesman                                            const Instruction *I,
517ce0e4c26SMichael Gottesman                                            const ReturnInst *Ret,
518ce0e4c26SMichael Gottesman                                            const TargetLoweringBase &TLI) {
519450aa64fSDan Gohman   // If the block ends with a void return or unreachable, it doesn't matter
520450aa64fSDan Gohman   // what the call's return type is.
521450aa64fSDan Gohman   if (!Ret || Ret->getNumOperands() == 0) return true;
522450aa64fSDan Gohman 
523450aa64fSDan Gohman   // If the return value is undef, it doesn't matter what the call's
524450aa64fSDan Gohman   // return type is.
525450aa64fSDan Gohman   if (isa<UndefValue>(Ret->getOperand(0))) return true;
526450aa64fSDan Gohman 
527707d68f0STim Northover   // Make sure the attributes attached to each return are compatible.
528ce0e4c26SMichael Gottesman   AttrBuilder CallerAttrs(F->getAttributes(),
529707d68f0STim Northover                           AttributeSet::ReturnIndex);
530707d68f0STim Northover   AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
531707d68f0STim Northover                           AttributeSet::ReturnIndex);
532707d68f0STim Northover 
533707d68f0STim Northover   // Noalias is completely benign as far as calling convention goes, it
534707d68f0STim Northover   // shouldn't affect whether the call is a tail call.
535707d68f0STim Northover   CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias);
536707d68f0STim Northover   CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias);
537707d68f0STim Northover 
538707d68f0STim Northover   bool AllowDifferingSizes = true;
539707d68f0STim Northover   if (CallerAttrs.contains(Attribute::ZExt)) {
540707d68f0STim Northover     if (!CalleeAttrs.contains(Attribute::ZExt))
541450aa64fSDan Gohman       return false;
542450aa64fSDan Gohman 
543707d68f0STim Northover     AllowDifferingSizes = false;
544707d68f0STim Northover     CallerAttrs.removeAttribute(Attribute::ZExt);
545707d68f0STim Northover     CalleeAttrs.removeAttribute(Attribute::ZExt);
546707d68f0STim Northover   } else if (CallerAttrs.contains(Attribute::SExt)) {
547707d68f0STim Northover     if (!CalleeAttrs.contains(Attribute::SExt))
548707d68f0STim Northover       return false;
549707d68f0STim Northover 
550707d68f0STim Northover     AllowDifferingSizes = false;
551707d68f0STim Northover     CallerAttrs.removeAttribute(Attribute::SExt);
552707d68f0STim Northover     CalleeAttrs.removeAttribute(Attribute::SExt);
553707d68f0STim Northover   }
554707d68f0STim Northover 
555707d68f0STim Northover   // If they're still different, there's some facet we don't understand
556707d68f0STim Northover   // (currently only "inreg", but in future who knows). It may be OK but the
557707d68f0STim Northover   // only safe option is to reject the tail call.
558707d68f0STim Northover   if (CallerAttrs != CalleeAttrs)
559450aa64fSDan Gohman     return false;
560450aa64fSDan Gohman 
561a4415854STim Northover   const Value *RetVal = Ret->getOperand(0), *CallVal = I;
562a4415854STim Northover   SmallVector<unsigned, 4> RetPath, CallPath;
563a4415854STim Northover   SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
564a4415854STim Northover 
565a4415854STim Northover   bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
566a4415854STim Northover   bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
567a4415854STim Northover 
568a4415854STim Northover   // Nothing's actually returned, it doesn't matter what the callee put there
569a4415854STim Northover   // it's a valid tail call.
570a4415854STim Northover   if (RetEmpty)
571a4415854STim Northover     return true;
572a4415854STim Northover 
573a4415854STim Northover   // Iterate pairwise through each of the value types making up the tail call
574a4415854STim Northover   // and the corresponding return. For each one we want to know whether it's
575a4415854STim Northover   // essentially going directly from the tail call to the ret, via operations
576a4415854STim Northover   // that end up not generating any code.
577a4415854STim Northover   //
578a4415854STim Northover   // We allow a certain amount of covariance here. For example it's permitted
579a4415854STim Northover   // for the tail call to define more bits than the ret actually cares about
580a4415854STim Northover   // (e.g. via a truncate).
581a4415854STim Northover   do {
582a4415854STim Northover     if (CallEmpty) {
583a4415854STim Northover       // We've exhausted the values produced by the tail call instruction, the
584a4415854STim Northover       // rest are essentially undef. The type doesn't really matter, but we need
585a4415854STim Northover       // *something*.
586a4415854STim Northover       Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
587a4415854STim Northover       CallVal = UndefValue::get(SlotType);
588a4415854STim Northover     }
589a4415854STim Northover 
590a4415854STim Northover     // The manipulations performed when we're looking through an insertvalue or
591a4415854STim Northover     // an extractvalue would happen at the front of the RetPath list, so since
592a4415854STim Northover     // we have to copy it anyway it's more efficient to create a reversed copy.
593a4415854STim Northover     using std::copy;
594a4415854STim Northover     SmallVector<unsigned, 4> TmpRetPath, TmpCallPath;
595a4415854STim Northover     copy(RetPath.rbegin(), RetPath.rend(), std::back_inserter(TmpRetPath));
596a4415854STim Northover     copy(CallPath.rbegin(), CallPath.rend(), std::back_inserter(TmpCallPath));
597a4415854STim Northover 
598a4415854STim Northover     // Finally, we can check whether the value produced by the tail call at this
599a4415854STim Northover     // index is compatible with the value we return.
600707d68f0STim Northover     if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
601707d68f0STim Northover                               AllowDifferingSizes, TLI))
602a4415854STim Northover       return false;
603a4415854STim Northover 
604a4415854STim Northover     CallEmpty  = !nextRealType(CallSubTypes, CallPath);
605a4415854STim Northover   } while(nextRealType(RetSubTypes, RetPath));
606a4415854STim Northover 
607a4415854STim Northover   return true;
608450aa64fSDan Gohman }
609