150f02cb2SNick Lewycky //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
2450aa64fSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6450aa64fSDan Gohman //
7450aa64fSDan Gohman //===----------------------------------------------------------------------===//
8450aa64fSDan Gohman //
9db5028bdSEric Christopher // This file defines several CodeGen-specific LLVM IR analysis utilities.
10450aa64fSDan Gohman //
11450aa64fSDan Gohman //===----------------------------------------------------------------------===//
12450aa64fSDan Gohman 
1309fc276dSEric Christopher #include "llvm/CodeGen/Analysis.h"
14dda00098SEric Christopher #include "llvm/Analysis/ValueTracking.h"
15ed0881b2SChandler Carruth #include "llvm/CodeGen/MachineFunction.h"
163f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
17b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetLowering.h"
18b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
199fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
209fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
219fb823bbSChandler Carruth #include "llvm/IR/Function.h"
229fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
239fb823bbSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
249fb823bbSChandler Carruth #include "llvm/IR/LLVMContext.h"
259fb823bbSChandler Carruth #include "llvm/IR/Module.h"
26450aa64fSDan Gohman #include "llvm/Support/ErrorHandling.h"
27450aa64fSDan Gohman #include "llvm/Support/MathExtras.h"
28f21434ccSRafael Espindola #include "llvm/Transforms/Utils/GlobalStatus.h"
29d913448bSEric Christopher 
30450aa64fSDan Gohman using namespace llvm;
31450aa64fSDan Gohman 
328923cc54SMehdi Amini /// Compute the linearized index of a member in a nested aggregate/struct/array
338923cc54SMehdi Amini /// by recursing and accumulating CurIndex as long as there are indices in the
348923cc54SMehdi Amini /// index list.
35229907cdSChris Lattner unsigned llvm::ComputeLinearIndex(Type *Ty,
36450aa64fSDan Gohman                                   const unsigned *Indices,
37450aa64fSDan Gohman                                   const unsigned *IndicesEnd,
38450aa64fSDan Gohman                                   unsigned CurIndex) {
39450aa64fSDan Gohman   // Base case: We're done.
40450aa64fSDan Gohman   if (Indices && Indices == IndicesEnd)
41450aa64fSDan Gohman     return CurIndex;
42450aa64fSDan Gohman 
43450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
44229907cdSChris Lattner   if (StructType *STy = dyn_cast<StructType>(Ty)) {
45450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
46450aa64fSDan Gohman                                       EI = EB,
47450aa64fSDan Gohman                                       EE = STy->element_end();
48450aa64fSDan Gohman         EI != EE; ++EI) {
49450aa64fSDan Gohman       if (Indices && *Indices == unsigned(EI - EB))
50aadc5596SDan Gohman         return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
51c0196b1bSCraig Topper       CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
52450aa64fSDan Gohman     }
537b068f6bSMehdi Amini     assert(!Indices && "Unexpected out of bound");
54450aa64fSDan Gohman     return CurIndex;
55450aa64fSDan Gohman   }
56450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
57229907cdSChris Lattner   else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
58229907cdSChris Lattner     Type *EltTy = ATy->getElementType();
598923cc54SMehdi Amini     unsigned NumElts = ATy->getNumElements();
608923cc54SMehdi Amini     // Compute the Linear offset when jumping one element of the array
618923cc54SMehdi Amini     unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
627b068f6bSMehdi Amini     if (Indices) {
637b068f6bSMehdi Amini       assert(*Indices < NumElts && "Unexpected out of bound");
648923cc54SMehdi Amini       // If the indice is inside the array, compute the index to the requested
658923cc54SMehdi Amini       // elt and recurse inside the element with the end of the indices list
668923cc54SMehdi Amini       CurIndex += EltLinearOffset* *Indices;
67aadc5596SDan Gohman       return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
68450aa64fSDan Gohman     }
698923cc54SMehdi Amini     CurIndex += EltLinearOffset*NumElts;
70450aa64fSDan Gohman     return CurIndex;
71450aa64fSDan Gohman   }
72450aa64fSDan Gohman   // We haven't found the type we're looking for, so keep searching.
73450aa64fSDan Gohman   return CurIndex + 1;
74450aa64fSDan Gohman }
75450aa64fSDan Gohman 
76450aa64fSDan Gohman /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
77450aa64fSDan Gohman /// EVTs that represent all the individual underlying
78450aa64fSDan Gohman /// non-aggregate types that comprise it.
79450aa64fSDan Gohman ///
80450aa64fSDan Gohman /// If Offsets is non-null, it points to a vector to be filled in
81450aa64fSDan Gohman /// with the in-memory offsets of each of the individual values.
82450aa64fSDan Gohman ///
8356228dabSMehdi Amini void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
8456228dabSMehdi Amini                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
85*ee2474dfSTim Northover                            SmallVectorImpl<EVT> *MemVTs,
86450aa64fSDan Gohman                            SmallVectorImpl<uint64_t> *Offsets,
87450aa64fSDan Gohman                            uint64_t StartingOffset) {
88450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
89229907cdSChris Lattner   if (StructType *STy = dyn_cast<StructType>(Ty)) {
9056228dabSMehdi Amini     const StructLayout *SL = DL.getStructLayout(STy);
91450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
92450aa64fSDan Gohman                                       EI = EB,
93450aa64fSDan Gohman                                       EE = STy->element_end();
94450aa64fSDan Gohman          EI != EE; ++EI)
95*ee2474dfSTim Northover       ComputeValueVTs(TLI, DL, *EI, ValueVTs, MemVTs, Offsets,
96450aa64fSDan Gohman                       StartingOffset + SL->getElementOffset(EI - EB));
97450aa64fSDan Gohman     return;
98450aa64fSDan Gohman   }
99450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
100229907cdSChris Lattner   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
101229907cdSChris Lattner     Type *EltTy = ATy->getElementType();
10256228dabSMehdi Amini     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
103450aa64fSDan Gohman     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
104*ee2474dfSTim Northover       ComputeValueVTs(TLI, DL, EltTy, ValueVTs, MemVTs, Offsets,
105450aa64fSDan Gohman                       StartingOffset + i * EltSize);
106450aa64fSDan Gohman     return;
107450aa64fSDan Gohman   }
108450aa64fSDan Gohman   // Interpret void as zero return values.
109450aa64fSDan Gohman   if (Ty->isVoidTy())
110450aa64fSDan Gohman     return;
111450aa64fSDan Gohman   // Base case: we can get an EVT for this LLVM IR type.
11244ede33aSMehdi Amini   ValueVTs.push_back(TLI.getValueType(DL, Ty));
113*ee2474dfSTim Northover   if (MemVTs)
114*ee2474dfSTim Northover     MemVTs->push_back(TLI.getMemValueType(DL, Ty));
115450aa64fSDan Gohman   if (Offsets)
116450aa64fSDan Gohman     Offsets->push_back(StartingOffset);
117450aa64fSDan Gohman }
118450aa64fSDan Gohman 
119*ee2474dfSTim Northover void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
120*ee2474dfSTim Northover                            Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
121*ee2474dfSTim Northover                            SmallVectorImpl<uint64_t> *Offsets,
122*ee2474dfSTim Northover                            uint64_t StartingOffset) {
123*ee2474dfSTim Northover   return ComputeValueVTs(TLI, DL, Ty, ValueVTs, /*MemVTs=*/nullptr, Offsets,
124*ee2474dfSTim Northover                          StartingOffset);
125*ee2474dfSTim Northover }
126*ee2474dfSTim Northover 
1272064e45cSMatt Arsenault void llvm::computeValueLLTs(const DataLayout &DL, Type &Ty,
1282064e45cSMatt Arsenault                             SmallVectorImpl<LLT> &ValueTys,
1292064e45cSMatt Arsenault                             SmallVectorImpl<uint64_t> *Offsets,
1302064e45cSMatt Arsenault                             uint64_t StartingOffset) {
1312064e45cSMatt Arsenault   // Given a struct type, recursively traverse the elements.
1322064e45cSMatt Arsenault   if (StructType *STy = dyn_cast<StructType>(&Ty)) {
1332064e45cSMatt Arsenault     const StructLayout *SL = DL.getStructLayout(STy);
1342064e45cSMatt Arsenault     for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
1352064e45cSMatt Arsenault       computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
1362064e45cSMatt Arsenault                        StartingOffset + SL->getElementOffset(I));
1372064e45cSMatt Arsenault     return;
1382064e45cSMatt Arsenault   }
1392064e45cSMatt Arsenault   // Given an array type, recursively traverse the elements.
1402064e45cSMatt Arsenault   if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
1412064e45cSMatt Arsenault     Type *EltTy = ATy->getElementType();
1422064e45cSMatt Arsenault     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
1432064e45cSMatt Arsenault     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1442064e45cSMatt Arsenault       computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
1452064e45cSMatt Arsenault                        StartingOffset + i * EltSize);
1462064e45cSMatt Arsenault     return;
1472064e45cSMatt Arsenault   }
1482064e45cSMatt Arsenault   // Interpret void as zero return values.
1492064e45cSMatt Arsenault   if (Ty.isVoidTy())
1502064e45cSMatt Arsenault     return;
1512064e45cSMatt Arsenault   // Base case: we can get an LLT for this LLVM IR type.
1522064e45cSMatt Arsenault   ValueTys.push_back(getLLTForType(Ty, DL));
1532064e45cSMatt Arsenault   if (Offsets != nullptr)
1542064e45cSMatt Arsenault     Offsets->push_back(StartingOffset * 8);
1552064e45cSMatt Arsenault }
1562064e45cSMatt Arsenault 
157450aa64fSDan Gohman /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
158283bc2edSReid Kleckner GlobalValue *llvm::ExtractTypeInfo(Value *V) {
159450aa64fSDan Gohman   V = V->stripPointerCasts();
160283bc2edSReid Kleckner   GlobalValue *GV = dyn_cast<GlobalValue>(V);
161283bc2edSReid Kleckner   GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
162450aa64fSDan Gohman 
163283bc2edSReid Kleckner   if (Var && Var->getName() == "llvm.eh.catch.all.value") {
164283bc2edSReid Kleckner     assert(Var->hasInitializer() &&
165450aa64fSDan Gohman            "The EH catch-all value must have an initializer");
166283bc2edSReid Kleckner     Value *Init = Var->getInitializer();
167283bc2edSReid Kleckner     GV = dyn_cast<GlobalValue>(Init);
168450aa64fSDan Gohman     if (!GV) V = cast<ConstantPointerNull>(Init);
169450aa64fSDan Gohman   }
170450aa64fSDan Gohman 
171450aa64fSDan Gohman   assert((GV || isa<ConstantPointerNull>(V)) &&
172450aa64fSDan Gohman          "TypeInfo must be a global variable or NULL");
173450aa64fSDan Gohman   return GV;
174450aa64fSDan Gohman }
175450aa64fSDan Gohman 
176450aa64fSDan Gohman /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
177450aa64fSDan Gohman /// processed uses a memory 'm' constraint.
178450aa64fSDan Gohman bool
179e8360b71SJohn Thompson llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
180450aa64fSDan Gohman                                 const TargetLowering &TLI) {
181450aa64fSDan Gohman   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
182450aa64fSDan Gohman     InlineAsm::ConstraintInfo &CI = CInfos[i];
183450aa64fSDan Gohman     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
184450aa64fSDan Gohman       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
185450aa64fSDan Gohman       if (CType == TargetLowering::C_Memory)
186450aa64fSDan Gohman         return true;
187450aa64fSDan Gohman     }
188450aa64fSDan Gohman 
189450aa64fSDan Gohman     // Indirect operand accesses access memory.
190450aa64fSDan Gohman     if (CI.isIndirect)
191450aa64fSDan Gohman       return true;
192450aa64fSDan Gohman   }
193450aa64fSDan Gohman 
194450aa64fSDan Gohman   return false;
195450aa64fSDan Gohman }
196450aa64fSDan Gohman 
197450aa64fSDan Gohman /// getFCmpCondCode - Return the ISD condition code corresponding to
198450aa64fSDan Gohman /// the given LLVM IR floating-point condition code.  This includes
199450aa64fSDan Gohman /// consideration of global floating-point math flags.
200450aa64fSDan Gohman ///
201450aa64fSDan Gohman ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
202450aa64fSDan Gohman   switch (Pred) {
20350f02cb2SNick Lewycky   case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
20450f02cb2SNick Lewycky   case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
20550f02cb2SNick Lewycky   case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
20650f02cb2SNick Lewycky   case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
20750f02cb2SNick Lewycky   case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
20850f02cb2SNick Lewycky   case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
20950f02cb2SNick Lewycky   case FCmpInst::FCMP_ONE:   return ISD::SETONE;
21050f02cb2SNick Lewycky   case FCmpInst::FCMP_ORD:   return ISD::SETO;
21150f02cb2SNick Lewycky   case FCmpInst::FCMP_UNO:   return ISD::SETUO;
21250f02cb2SNick Lewycky   case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
21350f02cb2SNick Lewycky   case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
21450f02cb2SNick Lewycky   case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
21550f02cb2SNick Lewycky   case FCmpInst::FCMP_ULT:   return ISD::SETULT;
21650f02cb2SNick Lewycky   case FCmpInst::FCMP_ULE:   return ISD::SETULE;
21750f02cb2SNick Lewycky   case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
21850f02cb2SNick Lewycky   case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
21946a9f016SDavid Blaikie   default: llvm_unreachable("Invalid FCmp predicate opcode!");
220450aa64fSDan Gohman   }
22150f02cb2SNick Lewycky }
22250f02cb2SNick Lewycky 
22350f02cb2SNick Lewycky ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
22450f02cb2SNick Lewycky   switch (CC) {
22550f02cb2SNick Lewycky     case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
22650f02cb2SNick Lewycky     case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
22750f02cb2SNick Lewycky     case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
22850f02cb2SNick Lewycky     case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
22950f02cb2SNick Lewycky     case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
23050f02cb2SNick Lewycky     case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
23146a9f016SDavid Blaikie     default: return CC;
23250f02cb2SNick Lewycky   }
233450aa64fSDan Gohman }
234450aa64fSDan Gohman 
235450aa64fSDan Gohman /// getICmpCondCode - Return the ISD condition code corresponding to
236450aa64fSDan Gohman /// the given LLVM IR integer condition code.
237450aa64fSDan Gohman ///
238450aa64fSDan Gohman ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
239450aa64fSDan Gohman   switch (Pred) {
240450aa64fSDan Gohman   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
241450aa64fSDan Gohman   case ICmpInst::ICMP_NE:  return ISD::SETNE;
242450aa64fSDan Gohman   case ICmpInst::ICMP_SLE: return ISD::SETLE;
243450aa64fSDan Gohman   case ICmpInst::ICMP_ULE: return ISD::SETULE;
244450aa64fSDan Gohman   case ICmpInst::ICMP_SGE: return ISD::SETGE;
245450aa64fSDan Gohman   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
246450aa64fSDan Gohman   case ICmpInst::ICMP_SLT: return ISD::SETLT;
247450aa64fSDan Gohman   case ICmpInst::ICMP_ULT: return ISD::SETULT;
248450aa64fSDan Gohman   case ICmpInst::ICMP_SGT: return ISD::SETGT;
249450aa64fSDan Gohman   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
250450aa64fSDan Gohman   default:
251450aa64fSDan Gohman     llvm_unreachable("Invalid ICmp predicate opcode!");
252450aa64fSDan Gohman   }
253450aa64fSDan Gohman }
254450aa64fSDan Gohman 
255ffc44549SStephen Lin static bool isNoopBitcast(Type *T1, Type *T2,
256c0659fadSMichael Gottesman                           const TargetLoweringBase& TLI) {
257ffc44549SStephen Lin   return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
258ffc44549SStephen Lin          (isa<VectorType>(T1) && isa<VectorType>(T2) &&
259ffc44549SStephen Lin           TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
260ffc44549SStephen Lin }
2614f3615deSChris Lattner 
262a4415854STim Northover /// Look through operations that will be free to find the earliest source of
263a4415854STim Northover /// this value.
264a4415854STim Northover ///
265a4415854STim Northover /// @param ValLoc If V has aggegate type, we will be interested in a particular
266a4415854STim Northover /// scalar component. This records its address; the reverse of this list gives a
267a4415854STim Northover /// sequence of indices appropriate for an extractvalue to locate the important
268a4415854STim Northover /// value. This value is updated during the function and on exit will indicate
269a4415854STim Northover /// similar information for the Value returned.
270a4415854STim Northover ///
271a4415854STim Northover /// @param DataBits If this function looks through truncate instructions, this
272a4415854STim Northover /// will record the smallest size attained.
273a4415854STim Northover static const Value *getNoopInput(const Value *V,
274a4415854STim Northover                                  SmallVectorImpl<unsigned> &ValLoc,
275a4415854STim Northover                                  unsigned &DataBits,
27644ede33aSMehdi Amini                                  const TargetLoweringBase &TLI,
27744ede33aSMehdi Amini                                  const DataLayout &DL) {
278ffc44549SStephen Lin   while (true) {
279ffc44549SStephen Lin     // Try to look through V1; if V1 is not an instruction, it can't be looked
280ffc44549SStephen Lin     // through.
281a4415854STim Northover     const Instruction *I = dyn_cast<Instruction>(V);
282a4415854STim Northover     if (!I || I->getNumOperands() == 0) return V;
283c0196b1bSCraig Topper     const Value *NoopInput = nullptr;
284a4415854STim Northover 
285182fe3eeSChris Lattner     Value *Op = I->getOperand(0);
286a4415854STim Northover     if (isa<BitCastInst>(I)) {
2874f3615deSChris Lattner       // Look through truly no-op bitcasts.
288ffc44549SStephen Lin       if (isNoopBitcast(Op->getType(), I->getType(), TLI))
289ffc44549SStephen Lin         NoopInput = Op;
290ffc44549SStephen Lin     } else if (isa<GetElementPtrInst>(I)) {
291ffc44549SStephen Lin       // Look through getelementptr
292ffc44549SStephen Lin       if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
293ffc44549SStephen Lin         NoopInput = Op;
294ffc44549SStephen Lin     } else if (isa<IntToPtrInst>(I)) {
295182fe3eeSChris Lattner       // Look through inttoptr.
296ffc44549SStephen Lin       // Make sure this isn't a truncating or extending cast.  We could
297ffc44549SStephen Lin       // support this eventually, but don't bother for now.
298ffc44549SStephen Lin       if (!isa<VectorType>(I->getType()) &&
29944ede33aSMehdi Amini           DL.getPointerSizeInBits() ==
300182fe3eeSChris Lattner               cast<IntegerType>(Op->getType())->getBitWidth())
301ffc44549SStephen Lin         NoopInput = Op;
302ffc44549SStephen Lin     } else if (isa<PtrToIntInst>(I)) {
303182fe3eeSChris Lattner       // Look through ptrtoint.
304ffc44549SStephen Lin       // Make sure this isn't a truncating or extending cast.  We could
305ffc44549SStephen Lin       // support this eventually, but don't bother for now.
306ffc44549SStephen Lin       if (!isa<VectorType>(I->getType()) &&
30744ede33aSMehdi Amini           DL.getPointerSizeInBits() ==
308182fe3eeSChris Lattner               cast<IntegerType>(I->getType())->getBitWidth())
309ffc44549SStephen Lin         NoopInput = Op;
310a4415854STim Northover     } else if (isa<TruncInst>(I) &&
311a4415854STim Northover                TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
312a4415854STim Northover       DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
313a4415854STim Northover       NoopInput = Op;
3148a41319dSAhmed Bougacha     } else if (auto CS = ImmutableCallSite(I)) {
3158a41319dSAhmed Bougacha       const Value *ReturnedOp = CS.getReturnedArgOperand();
3166aff744eSAhmed Bougacha       if (ReturnedOp && isNoopBitcast(ReturnedOp->getType(), I->getType(), TLI))
3176aff744eSAhmed Bougacha         NoopInput = ReturnedOp;
318a4415854STim Northover     } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
319a4415854STim Northover       // Value may come from either the aggregate or the scalar
320a4415854STim Northover       ArrayRef<unsigned> InsertLoc = IVI->getIndices();
321e4310fe9STim Northover       if (ValLoc.size() >= InsertLoc.size() &&
322e4310fe9STim Northover           std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
323a4415854STim Northover         // The type being inserted is a nested sub-type of the aggregate; we
324a4415854STim Northover         // have to remove those initial indices to get the location we're
325a4415854STim Northover         // interested in for the operand.
326a4415854STim Northover         ValLoc.resize(ValLoc.size() - InsertLoc.size());
327a4415854STim Northover         NoopInput = IVI->getInsertedValueOperand();
328a4415854STim Northover       } else {
329a4415854STim Northover         // The struct we're inserting into has the value we're interested in, no
330a4415854STim Northover         // change of address.
331a4415854STim Northover         NoopInput = Op;
332a4415854STim Northover       }
333a4415854STim Northover     } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
334a4415854STim Northover       // The part we're interested in will inevitably be some sub-section of the
335a4415854STim Northover       // previous aggregate. Combine the two paths to obtain the true address of
336a4415854STim Northover       // our element.
337a4415854STim Northover       ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
3384f6ac162SBenjamin Kramer       ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
339a4415854STim Northover       NoopInput = Op;
340a4415854STim Northover     }
341a4415854STim Northover     // Terminate if we couldn't find anything to look through.
342a4415854STim Northover     if (!NoopInput)
343a4415854STim Northover       return V;
344a4415854STim Northover 
345a4415854STim Northover     V = NoopInput;
346ffc44549SStephen Lin   }
347182fe3eeSChris Lattner }
348182fe3eeSChris Lattner 
349a4415854STim Northover /// Return true if this scalar return value only has bits discarded on its path
350a4415854STim Northover /// from the "tail call" to the "ret". This includes the obvious noop
351a4415854STim Northover /// instructions handled by getNoopInput above as well as free truncations (or
352a4415854STim Northover /// extensions prior to the call).
353a4415854STim Northover static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
354a4415854STim Northover                                  SmallVectorImpl<unsigned> &RetIndices,
355a4415854STim Northover                                  SmallVectorImpl<unsigned> &CallIndices,
356707d68f0STim Northover                                  bool AllowDifferingSizes,
35744ede33aSMehdi Amini                                  const TargetLoweringBase &TLI,
35844ede33aSMehdi Amini                                  const DataLayout &DL) {
3594f3615deSChris Lattner 
360a4415854STim Northover   // Trace the sub-value needed by the return value as far back up the graph as
361a4415854STim Northover   // possible, in the hope that it will intersect with the value produced by the
362a4415854STim Northover   // call. In the simple case with no "returned" attribute, the hope is actually
363a4415854STim Northover   // that we end up back at the tail call instruction itself.
364a4415854STim Northover   unsigned BitsRequired = UINT_MAX;
36544ede33aSMehdi Amini   RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL);
366ffc44549SStephen Lin 
367a4415854STim Northover   // If this slot in the value returned is undef, it doesn't matter what the
368a4415854STim Northover   // call puts there, it'll be fine.
369a4415854STim Northover   if (isa<UndefValue>(RetVal))
370a4415854STim Northover     return true;
371ffc44549SStephen Lin 
372a4415854STim Northover   // Now do a similar search up through the graph to find where the value
373a4415854STim Northover   // actually returned by the "tail call" comes from. In the simple case without
374a4415854STim Northover   // a "returned" attribute, the search will be blocked immediately and the loop
375a4415854STim Northover   // a Noop.
376a4415854STim Northover   unsigned BitsProvided = UINT_MAX;
37744ede33aSMehdi Amini   CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL);
378a4415854STim Northover 
379a4415854STim Northover   // There's no hope if we can't actually trace them to (the same part of!) the
380a4415854STim Northover   // same value.
381a4415854STim Northover   if (CallVal != RetVal || CallIndices != RetIndices)
382a4415854STim Northover     return false;
383a4415854STim Northover 
384a4415854STim Northover   // However, intervening truncates may have made the call non-tail. Make sure
385a4415854STim Northover   // all the bits that are needed by the "ret" have been provided by the "tail
386a4415854STim Northover   // call". FIXME: with sufficiently cunning bit-tracking, we could look through
387a4415854STim Northover   // extensions too.
388707d68f0STim Northover   if (BitsProvided < BitsRequired ||
389707d68f0STim Northover       (!AllowDifferingSizes && BitsProvided != BitsRequired))
390a4415854STim Northover     return false;
391a4415854STim Northover 
392ffc44549SStephen Lin   return true;
393ffc44549SStephen Lin }
394a4415854STim Northover 
395a4415854STim Northover /// For an aggregate type, determine whether a given index is within bounds or
396a4415854STim Northover /// not.
397a4415854STim Northover static bool indexReallyValid(CompositeType *T, unsigned Idx) {
398a4415854STim Northover   if (ArrayType *AT = dyn_cast<ArrayType>(T))
399a4415854STim Northover     return Idx < AT->getNumElements();
400a4415854STim Northover 
401a4415854STim Northover   return Idx < cast<StructType>(T)->getNumElements();
402ffc44549SStephen Lin }
403a4415854STim Northover 
404a4415854STim Northover /// Move the given iterators to the next leaf type in depth first traversal.
405a4415854STim Northover ///
406a4415854STim Northover /// Performs a depth-first traversal of the type as specified by its arguments,
407a4415854STim Northover /// stopping at the next leaf node (which may be a legitimate scalar type or an
408a4415854STim Northover /// empty struct or array).
409a4415854STim Northover ///
410a4415854STim Northover /// @param SubTypes List of the partial components making up the type from
411a4415854STim Northover /// outermost to innermost non-empty aggregate. The element currently
412a4415854STim Northover /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
413a4415854STim Northover ///
414a4415854STim Northover /// @param Path Set of extractvalue indices leading from the outermost type
415a4415854STim Northover /// (SubTypes[0]) to the leaf node currently represented.
416a4415854STim Northover ///
417a4415854STim Northover /// @returns true if a new type was found, false otherwise. Calling this
418a4415854STim Northover /// function again on a finished iterator will repeatedly return
419a4415854STim Northover /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
420a4415854STim Northover /// aggregate or a non-aggregate
421df03449aSBenjamin Kramer static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
422a4415854STim Northover                                   SmallVectorImpl<unsigned> &Path) {
423a4415854STim Northover   // First march back up the tree until we can successfully increment one of the
424a4415854STim Northover   // coordinates in Path.
425a4415854STim Northover   while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
426a4415854STim Northover     Path.pop_back();
427a4415854STim Northover     SubTypes.pop_back();
428a4415854STim Northover   }
429a4415854STim Northover 
430a4415854STim Northover   // If we reached the top, then the iterator is done.
431a4415854STim Northover   if (Path.empty())
432a4415854STim Northover     return false;
433a4415854STim Northover 
434a4415854STim Northover   // We know there's *some* valid leaf now, so march back down the tree picking
435a4415854STim Northover   // out the left-most element at each node.
436a4415854STim Northover   ++Path.back();
437a4415854STim Northover   Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
438a4415854STim Northover   while (DeeperType->isAggregateType()) {
439a4415854STim Northover     CompositeType *CT = cast<CompositeType>(DeeperType);
440a4415854STim Northover     if (!indexReallyValid(CT, 0))
441a4415854STim Northover       return true;
442a4415854STim Northover 
443a4415854STim Northover     SubTypes.push_back(CT);
444a4415854STim Northover     Path.push_back(0);
445a4415854STim Northover 
446a4415854STim Northover     DeeperType = CT->getTypeAtIndex(0U);
447a4415854STim Northover   }
448a4415854STim Northover 
449ffc44549SStephen Lin   return true;
450ffc44549SStephen Lin }
451a4415854STim Northover 
452a4415854STim Northover /// Find the first non-empty, scalar-like type in Next and setup the iterator
453a4415854STim Northover /// components.
454a4415854STim Northover ///
455a4415854STim Northover /// Assuming Next is an aggregate of some kind, this function will traverse the
456a4415854STim Northover /// tree from left to right (i.e. depth-first) looking for the first
457a4415854STim Northover /// non-aggregate type which will play a role in function return.
458a4415854STim Northover ///
459a4415854STim Northover /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
460a4415854STim Northover /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
461a4415854STim Northover /// i32 in that type.
462a4415854STim Northover static bool firstRealType(Type *Next,
463a4415854STim Northover                           SmallVectorImpl<CompositeType *> &SubTypes,
464a4415854STim Northover                           SmallVectorImpl<unsigned> &Path) {
465a4415854STim Northover   // First initialise the iterator components to the first "leaf" node
466a4415854STim Northover   // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
467a4415854STim Northover   // despite nominally being an aggregate).
468a4415854STim Northover   while (Next->isAggregateType() &&
469a4415854STim Northover          indexReallyValid(cast<CompositeType>(Next), 0)) {
470a4415854STim Northover     SubTypes.push_back(cast<CompositeType>(Next));
471a4415854STim Northover     Path.push_back(0);
472a4415854STim Northover     Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
473ffc44549SStephen Lin   }
474ffc44549SStephen Lin 
475a4415854STim Northover   // If there's no Path now, Next was originally scalar already (or empty
476a4415854STim Northover   // leaf). We're done.
477a4415854STim Northover   if (Path.empty())
478a4415854STim Northover     return true;
479ffc44549SStephen Lin 
480a4415854STim Northover   // Otherwise, use normal iteration to keep looking through the tree until we
481a4415854STim Northover   // find a non-aggregate type.
482a4415854STim Northover   while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
483a4415854STim Northover     if (!advanceToNextLeafType(SubTypes, Path))
484ffc44549SStephen Lin       return false;
485ffc44549SStephen Lin   }
4864f3615deSChris Lattner 
487a4415854STim Northover   return true;
488a4415854STim Northover }
489a4415854STim Northover 
490a4415854STim Northover /// Set the iterator data-structures to the next non-empty, non-aggregate
491a4415854STim Northover /// subtype.
492df03449aSBenjamin Kramer static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
493a4415854STim Northover                          SmallVectorImpl<unsigned> &Path) {
494a4415854STim Northover   do {
495a4415854STim Northover     if (!advanceToNextLeafType(SubTypes, Path))
496a4415854STim Northover       return false;
497a4415854STim Northover 
498a4415854STim Northover     assert(!Path.empty() && "found a leaf but didn't set the path?");
499a4415854STim Northover   } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
500a4415854STim Northover 
501a4415854STim Northover   return true;
502a4415854STim Northover }
503a4415854STim Northover 
504a4415854STim Northover 
505450aa64fSDan Gohman /// Test if the given instruction is in a position to be optimized
506450aa64fSDan Gohman /// with a tail-call. This roughly means that it's in a block with
507450aa64fSDan Gohman /// a return and there's nothing that needs to be scheduled
508450aa64fSDan Gohman /// between it and the return.
509450aa64fSDan Gohman ///
510450aa64fSDan Gohman /// This function only tests target-independent requirements.
511480872b4SJuergen Ributzka bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) {
512450aa64fSDan Gohman   const Instruction *I = CS.getInstruction();
513450aa64fSDan Gohman   const BasicBlock *ExitBB = I->getParent();
514edb12a83SChandler Carruth   const Instruction *Term = ExitBB->getTerminator();
515450aa64fSDan Gohman   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
516450aa64fSDan Gohman 
517450aa64fSDan Gohman   // The block must end in a return statement or unreachable.
518450aa64fSDan Gohman   //
519450aa64fSDan Gohman   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
520450aa64fSDan Gohman   // an unreachable, for now. The way tailcall optimization is currently
521450aa64fSDan Gohman   // implemented means it will add an epilogue followed by a jump. That is
522450aa64fSDan Gohman   // not profitable. Also, if the callee is a special function (e.g.
523450aa64fSDan Gohman   // longjmp on x86), it can end up causing miscompilation that has not
524450aa64fSDan Gohman   // been fully understood.
525450aa64fSDan Gohman   if (!Ret &&
5264ce9863dSJuergen Ributzka       (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
5274f3615deSChris Lattner     return false;
528450aa64fSDan Gohman 
529450aa64fSDan Gohman   // If I will have a chain, make sure no other instruction that will have a
530450aa64fSDan Gohman   // chain interposes between I and the return.
5310a92f86fSDavid Majnemer   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
5320a92f86fSDavid Majnemer       !isSafeToSpeculativelyExecute(I))
533b6d0bd48SBenjamin Kramer     for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
534450aa64fSDan Gohman       if (&*BBI == I)
535450aa64fSDan Gohman         break;
536450aa64fSDan Gohman       // Debug info intrinsics do not get in the way of tail call optimization.
537450aa64fSDan Gohman       if (isa<DbgInfoIntrinsic>(BBI))
538450aa64fSDan Gohman         continue;
53918bfb3a5SRobert Lougher       // A lifetime end intrinsic should not stop tail call optimization.
54018bfb3a5SRobert Lougher       if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
54118bfb3a5SRobert Lougher         if (II->getIntrinsicID() == Intrinsic::lifetime_end)
54218bfb3a5SRobert Lougher           continue;
543450aa64fSDan Gohman       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
544980f8f26SDuncan P. N. Exon Smith           !isSafeToSpeculativelyExecute(&*BBI))
545450aa64fSDan Gohman         return false;
546450aa64fSDan Gohman     }
547450aa64fSDan Gohman 
548f734a8baSEric Christopher   const Function *F = ExitBB->getParent();
549d913448bSEric Christopher   return returnTypeIsEligibleForTailCall(
550f734a8baSEric Christopher       F, I, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering());
551ce0e4c26SMichael Gottesman }
552ce0e4c26SMichael Gottesman 
553f79af6f8SMichael Kuperstein bool llvm::attributesPermitTailCall(const Function *F, const Instruction *I,
554f79af6f8SMichael Kuperstein                                     const ReturnInst *Ret,
555f79af6f8SMichael Kuperstein                                     const TargetLoweringBase &TLI,
556f79af6f8SMichael Kuperstein                                     bool *AllowDifferingSizes) {
557f79af6f8SMichael Kuperstein   // ADS may be null, so don't write to it directly.
558f79af6f8SMichael Kuperstein   bool DummyADS;
559f79af6f8SMichael Kuperstein   bool &ADS = AllowDifferingSizes ? *AllowDifferingSizes : DummyADS;
560f79af6f8SMichael Kuperstein   ADS = true;
561f79af6f8SMichael Kuperstein 
562b518054bSReid Kleckner   AttrBuilder CallerAttrs(F->getAttributes(), AttributeList::ReturnIndex);
563f79af6f8SMichael Kuperstein   AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
564b518054bSReid Kleckner                           AttributeList::ReturnIndex);
565f79af6f8SMichael Kuperstein 
566353cb3d4SDavid Green   // NoAlias and NonNull are completely benign as far as calling convention
567353cb3d4SDavid Green   // goes, they shouldn't affect whether the call is a tail call.
568807f732cSBjorn Pettersson   CallerAttrs.removeAttribute(Attribute::NoAlias);
569807f732cSBjorn Pettersson   CalleeAttrs.removeAttribute(Attribute::NoAlias);
570353cb3d4SDavid Green   CallerAttrs.removeAttribute(Attribute::NonNull);
571353cb3d4SDavid Green   CalleeAttrs.removeAttribute(Attribute::NonNull);
572f79af6f8SMichael Kuperstein 
573f79af6f8SMichael Kuperstein   if (CallerAttrs.contains(Attribute::ZExt)) {
574f79af6f8SMichael Kuperstein     if (!CalleeAttrs.contains(Attribute::ZExt))
575f79af6f8SMichael Kuperstein       return false;
576f79af6f8SMichael Kuperstein 
577f79af6f8SMichael Kuperstein     ADS = false;
578f79af6f8SMichael Kuperstein     CallerAttrs.removeAttribute(Attribute::ZExt);
579f79af6f8SMichael Kuperstein     CalleeAttrs.removeAttribute(Attribute::ZExt);
580f79af6f8SMichael Kuperstein   } else if (CallerAttrs.contains(Attribute::SExt)) {
581f79af6f8SMichael Kuperstein     if (!CalleeAttrs.contains(Attribute::SExt))
582f79af6f8SMichael Kuperstein       return false;
583f79af6f8SMichael Kuperstein 
584f79af6f8SMichael Kuperstein     ADS = false;
585f79af6f8SMichael Kuperstein     CallerAttrs.removeAttribute(Attribute::SExt);
586f79af6f8SMichael Kuperstein     CalleeAttrs.removeAttribute(Attribute::SExt);
587f79af6f8SMichael Kuperstein   }
588f79af6f8SMichael Kuperstein 
589ac6454a7SFrancis Visoiu Mistrih   // Drop sext and zext return attributes if the result is not used.
590ac6454a7SFrancis Visoiu Mistrih   // This enables tail calls for code like:
591ac6454a7SFrancis Visoiu Mistrih   //
592ac6454a7SFrancis Visoiu Mistrih   // define void @caller() {
593ac6454a7SFrancis Visoiu Mistrih   // entry:
594ac6454a7SFrancis Visoiu Mistrih   //   %unused_result = tail call zeroext i1 @callee()
595ac6454a7SFrancis Visoiu Mistrih   //   br label %retlabel
596ac6454a7SFrancis Visoiu Mistrih   // retlabel:
597ac6454a7SFrancis Visoiu Mistrih   //   ret void
598ac6454a7SFrancis Visoiu Mistrih   // }
599ac6454a7SFrancis Visoiu Mistrih   if (I->use_empty()) {
600ac6454a7SFrancis Visoiu Mistrih     CalleeAttrs.removeAttribute(Attribute::SExt);
601ac6454a7SFrancis Visoiu Mistrih     CalleeAttrs.removeAttribute(Attribute::ZExt);
602ac6454a7SFrancis Visoiu Mistrih   }
603ac6454a7SFrancis Visoiu Mistrih 
604f79af6f8SMichael Kuperstein   // If they're still different, there's some facet we don't understand
605f79af6f8SMichael Kuperstein   // (currently only "inreg", but in future who knows). It may be OK but the
606f79af6f8SMichael Kuperstein   // only safe option is to reject the tail call.
607f79af6f8SMichael Kuperstein   return CallerAttrs == CalleeAttrs;
608f79af6f8SMichael Kuperstein }
609f79af6f8SMichael Kuperstein 
610ce0e4c26SMichael Gottesman bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
611ce0e4c26SMichael Gottesman                                            const Instruction *I,
612ce0e4c26SMichael Gottesman                                            const ReturnInst *Ret,
613ce0e4c26SMichael Gottesman                                            const TargetLoweringBase &TLI) {
614450aa64fSDan Gohman   // If the block ends with a void return or unreachable, it doesn't matter
615450aa64fSDan Gohman   // what the call's return type is.
616450aa64fSDan Gohman   if (!Ret || Ret->getNumOperands() == 0) return true;
617450aa64fSDan Gohman 
618450aa64fSDan Gohman   // If the return value is undef, it doesn't matter what the call's
619450aa64fSDan Gohman   // return type is.
620450aa64fSDan Gohman   if (isa<UndefValue>(Ret->getOperand(0))) return true;
621450aa64fSDan Gohman 
622707d68f0STim Northover   // Make sure the attributes attached to each return are compatible.
623f79af6f8SMichael Kuperstein   bool AllowDifferingSizes;
624f79af6f8SMichael Kuperstein   if (!attributesPermitTailCall(F, I, Ret, TLI, &AllowDifferingSizes))
625450aa64fSDan Gohman     return false;
626450aa64fSDan Gohman 
627a4415854STim Northover   const Value *RetVal = Ret->getOperand(0), *CallVal = I;
6285d84d9b3SWei Mi   // Intrinsic like llvm.memcpy has no return value, but the expanded
6295d84d9b3SWei Mi   // libcall may or may not have return value. On most platforms, it
6305d84d9b3SWei Mi   // will be expanded as memcpy in libc, which returns the first
6315d84d9b3SWei Mi   // argument. On other platforms like arm-none-eabi, memcpy may be
6325d84d9b3SWei Mi   // expanded as library call without return value, like __aeabi_memcpy.
633818d50a9SWei Mi   const CallInst *Call = cast<CallInst>(I);
634818d50a9SWei Mi   if (Function *F = Call->getCalledFunction()) {
635818d50a9SWei Mi     Intrinsic::ID IID = F->getIntrinsicID();
6365d84d9b3SWei Mi     if (((IID == Intrinsic::memcpy &&
6375d84d9b3SWei Mi           TLI.getLibcallName(RTLIB::MEMCPY) == StringRef("memcpy")) ||
6385d84d9b3SWei Mi          (IID == Intrinsic::memmove &&
6395d84d9b3SWei Mi           TLI.getLibcallName(RTLIB::MEMMOVE) == StringRef("memmove")) ||
6405d84d9b3SWei Mi          (IID == Intrinsic::memset &&
6415d84d9b3SWei Mi           TLI.getLibcallName(RTLIB::MEMSET) == StringRef("memset"))) &&
642818d50a9SWei Mi         RetVal == Call->getArgOperand(0))
643818d50a9SWei Mi       return true;
644818d50a9SWei Mi   }
645818d50a9SWei Mi 
646a4415854STim Northover   SmallVector<unsigned, 4> RetPath, CallPath;
647a4415854STim Northover   SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
648a4415854STim Northover 
649a4415854STim Northover   bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
650a4415854STim Northover   bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
651a4415854STim Northover 
652a4415854STim Northover   // Nothing's actually returned, it doesn't matter what the callee put there
653a4415854STim Northover   // it's a valid tail call.
654a4415854STim Northover   if (RetEmpty)
655a4415854STim Northover     return true;
656a4415854STim Northover 
657a4415854STim Northover   // Iterate pairwise through each of the value types making up the tail call
658a4415854STim Northover   // and the corresponding return. For each one we want to know whether it's
659a4415854STim Northover   // essentially going directly from the tail call to the ret, via operations
660a4415854STim Northover   // that end up not generating any code.
661a4415854STim Northover   //
662a4415854STim Northover   // We allow a certain amount of covariance here. For example it's permitted
663a4415854STim Northover   // for the tail call to define more bits than the ret actually cares about
664a4415854STim Northover   // (e.g. via a truncate).
665a4415854STim Northover   do {
666a4415854STim Northover     if (CallEmpty) {
667a4415854STim Northover       // We've exhausted the values produced by the tail call instruction, the
668a4415854STim Northover       // rest are essentially undef. The type doesn't really matter, but we need
669a4415854STim Northover       // *something*.
670a4415854STim Northover       Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
671a4415854STim Northover       CallVal = UndefValue::get(SlotType);
672a4415854STim Northover     }
673a4415854STim Northover 
674a4415854STim Northover     // The manipulations performed when we're looking through an insertvalue or
675a4415854STim Northover     // an extractvalue would happen at the front of the RetPath list, so since
676a4415854STim Northover     // we have to copy it anyway it's more efficient to create a reversed copy.
6774f6ac162SBenjamin Kramer     SmallVector<unsigned, 4> TmpRetPath(RetPath.rbegin(), RetPath.rend());
6784f6ac162SBenjamin Kramer     SmallVector<unsigned, 4> TmpCallPath(CallPath.rbegin(), CallPath.rend());
679a4415854STim Northover 
680a4415854STim Northover     // Finally, we can check whether the value produced by the tail call at this
681a4415854STim Northover     // index is compatible with the value we return.
682707d68f0STim Northover     if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
68344ede33aSMehdi Amini                               AllowDifferingSizes, TLI,
68444ede33aSMehdi Amini                               F->getParent()->getDataLayout()))
685a4415854STim Northover       return false;
686a4415854STim Northover 
687a4415854STim Northover     CallEmpty  = !nextRealType(CallSubTypes, CallPath);
688a4415854STim Northover   } while(nextRealType(RetSubTypes, RetPath));
689a4415854STim Northover 
690a4415854STim Northover   return true;
691450aa64fSDan Gohman }
692f21434ccSRafael Espindola 
693d69acf3bSHeejin Ahn static void collectEHScopeMembers(
694d69acf3bSHeejin Ahn     DenseMap<const MachineBasicBlock *, int> &EHScopeMembership, int EHScope,
695d69acf3bSHeejin Ahn     const MachineBasicBlock *MBB) {
696734d7c32SDavid Majnemer   SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB};
697734d7c32SDavid Majnemer   while (!Worklist.empty()) {
698734d7c32SDavid Majnemer     const MachineBasicBlock *Visiting = Worklist.pop_back_val();
6991e4d3504SHeejin Ahn     // Don't follow blocks which start new scopes.
700734d7c32SDavid Majnemer     if (Visiting->isEHPad() && Visiting != MBB)
701734d7c32SDavid Majnemer       continue;
702734d7c32SDavid Majnemer 
7031e4d3504SHeejin Ahn     // Add this MBB to our scope.
704d69acf3bSHeejin Ahn     auto P = EHScopeMembership.insert(std::make_pair(Visiting, EHScope));
7057b54b525SDavid Blaikie 
70616193552SDavid Majnemer     // Don't revisit blocks.
7077b54b525SDavid Blaikie     if (!P.second) {
708d69acf3bSHeejin Ahn       assert(P.first->second == EHScope && "MBB is part of two scopes!");
709734d7c32SDavid Majnemer       continue;
71016193552SDavid Majnemer     }
71116193552SDavid Majnemer 
7121e4d3504SHeejin Ahn     // Returns are boundaries where scope transfer can occur, don't follow
71316193552SDavid Majnemer     // successors.
714ed5e06b0SHeejin Ahn     if (Visiting->isEHScopeReturnBlock())
715734d7c32SDavid Majnemer       continue;
71616193552SDavid Majnemer 
717734d7c32SDavid Majnemer     for (const MachineBasicBlock *Succ : Visiting->successors())
718734d7c32SDavid Majnemer       Worklist.push_back(Succ);
719734d7c32SDavid Majnemer   }
72016193552SDavid Majnemer }
72116193552SDavid Majnemer 
72216193552SDavid Majnemer DenseMap<const MachineBasicBlock *, int>
7231e4d3504SHeejin Ahn llvm::getEHScopeMembership(const MachineFunction &MF) {
724d69acf3bSHeejin Ahn   DenseMap<const MachineBasicBlock *, int> EHScopeMembership;
72516193552SDavid Majnemer 
72616193552SDavid Majnemer   // We don't have anything to do if there aren't any EH pads.
7271e4d3504SHeejin Ahn   if (!MF.hasEHScopes())
728d69acf3bSHeejin Ahn     return EHScopeMembership;
72916193552SDavid Majnemer 
730e4f9b09bSDavid Majnemer   int EntryBBNumber = MF.front().getNumber();
73116193552SDavid Majnemer   bool IsSEH = isAsynchronousEHPersonality(
732f1caa283SMatthias Braun       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
73316193552SDavid Majnemer 
73416193552SDavid Majnemer   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
735d69acf3bSHeejin Ahn   SmallVector<const MachineBasicBlock *, 16> EHScopeBlocks;
736e4f9b09bSDavid Majnemer   SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks;
737e4f9b09bSDavid Majnemer   SmallVector<const MachineBasicBlock *, 16> SEHCatchPads;
73816193552SDavid Majnemer   SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors;
73916193552SDavid Majnemer   for (const MachineBasicBlock &MBB : MF) {
7401e4d3504SHeejin Ahn     if (MBB.isEHScopeEntry()) {
741d69acf3bSHeejin Ahn       EHScopeBlocks.push_back(&MBB);
742e4f9b09bSDavid Majnemer     } else if (IsSEH && MBB.isEHPad()) {
743e4f9b09bSDavid Majnemer       SEHCatchPads.push_back(&MBB);
744e4f9b09bSDavid Majnemer     } else if (MBB.pred_empty()) {
745e4f9b09bSDavid Majnemer       UnreachableBlocks.push_back(&MBB);
746e4f9b09bSDavid Majnemer     }
74716193552SDavid Majnemer 
74816193552SDavid Majnemer     MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator();
7492e7af979SDuncan P. N. Exon Smith 
7501e4d3504SHeejin Ahn     // CatchPads are not scopes for SEH so do not consider CatchRet to
7511e4d3504SHeejin Ahn     // transfer control to another scope.
75226f9e9ebSReid Kleckner     if (MBBI == MBB.end() || MBBI->getOpcode() != TII->getCatchReturnOpcode())
75316193552SDavid Majnemer       continue;
75416193552SDavid Majnemer 
755e4f9b09bSDavid Majnemer     // FIXME: SEH CatchPads are not necessarily in the parent function:
756e4f9b09bSDavid Majnemer     // they could be inside a finally block.
75716193552SDavid Majnemer     const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB();
75816193552SDavid Majnemer     const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB();
759e4f9b09bSDavid Majnemer     CatchRetSuccessors.push_back(
760e4f9b09bSDavid Majnemer         {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()});
76116193552SDavid Majnemer   }
76216193552SDavid Majnemer 
76316193552SDavid Majnemer   // We don't have anything to do if there aren't any EH pads.
764d69acf3bSHeejin Ahn   if (EHScopeBlocks.empty())
765d69acf3bSHeejin Ahn     return EHScopeMembership;
76616193552SDavid Majnemer 
76716193552SDavid Majnemer   // Identify all the basic blocks reachable from the function entry.
768d69acf3bSHeejin Ahn   collectEHScopeMembers(EHScopeMembership, EntryBBNumber, &MF.front());
7691e4d3504SHeejin Ahn   // All blocks not part of a scope are in the parent function.
770e4f9b09bSDavid Majnemer   for (const MachineBasicBlock *MBB : UnreachableBlocks)
771d69acf3bSHeejin Ahn     collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB);
7721e4d3504SHeejin Ahn   // Next, identify all the blocks inside the scopes.
773d69acf3bSHeejin Ahn   for (const MachineBasicBlock *MBB : EHScopeBlocks)
774d69acf3bSHeejin Ahn     collectEHScopeMembers(EHScopeMembership, MBB->getNumber(), MBB);
7751e4d3504SHeejin Ahn   // SEH CatchPads aren't really scopes, handle them separately.
776e4f9b09bSDavid Majnemer   for (const MachineBasicBlock *MBB : SEHCatchPads)
777d69acf3bSHeejin Ahn     collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB);
77816193552SDavid Majnemer   // Finally, identify all the targets of a catchret.
77916193552SDavid Majnemer   for (std::pair<const MachineBasicBlock *, int> CatchRetPair :
78016193552SDavid Majnemer        CatchRetSuccessors)
781d69acf3bSHeejin Ahn     collectEHScopeMembers(EHScopeMembership, CatchRetPair.second,
78216193552SDavid Majnemer                           CatchRetPair.first);
783d69acf3bSHeejin Ahn   return EHScopeMembership;
78416193552SDavid Majnemer }
785