10b57cec5SDimitry Andric //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines several CodeGen-specific LLVM IR analysis utilities.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "llvm/CodeGen/Analysis.h"
140b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
150b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
160b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
190b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
200b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
210b57cec5SDimitry Andric #include "llvm/IR/Function.h"
220b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
230b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
240b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
250b57cec5SDimitry Andric #include "llvm/IR/Module.h"
260b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
270b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
285ffd83dbSDimitry Andric #include "llvm/Target/TargetMachine.h"
290b57cec5SDimitry Andric #include "llvm/Transforms/Utils/GlobalStatus.h"
300b57cec5SDimitry Andric
310b57cec5SDimitry Andric using namespace llvm;
320b57cec5SDimitry Andric
330b57cec5SDimitry Andric /// Compute the linearized index of a member in a nested aggregate/struct/array
340b57cec5SDimitry Andric /// by recursing and accumulating CurIndex as long as there are indices in the
350b57cec5SDimitry Andric /// index list.
ComputeLinearIndex(Type * Ty,const unsigned * Indices,const unsigned * IndicesEnd,unsigned CurIndex)360b57cec5SDimitry Andric unsigned llvm::ComputeLinearIndex(Type *Ty,
370b57cec5SDimitry Andric const unsigned *Indices,
380b57cec5SDimitry Andric const unsigned *IndicesEnd,
390b57cec5SDimitry Andric unsigned CurIndex) {
400b57cec5SDimitry Andric // Base case: We're done.
410b57cec5SDimitry Andric if (Indices && Indices == IndicesEnd)
420b57cec5SDimitry Andric return CurIndex;
430b57cec5SDimitry Andric
440b57cec5SDimitry Andric // Given a struct type, recursively traverse the elements.
450b57cec5SDimitry Andric if (StructType *STy = dyn_cast<StructType>(Ty)) {
46*5f7ddb14SDimitry Andric for (auto I : llvm::enumerate(STy->elements())) {
47*5f7ddb14SDimitry Andric Type *ET = I.value();
48*5f7ddb14SDimitry Andric if (Indices && *Indices == I.index())
49*5f7ddb14SDimitry Andric return ComputeLinearIndex(ET, Indices + 1, IndicesEnd, CurIndex);
50*5f7ddb14SDimitry Andric CurIndex = ComputeLinearIndex(ET, nullptr, nullptr, CurIndex);
510b57cec5SDimitry Andric }
520b57cec5SDimitry Andric assert(!Indices && "Unexpected out of bound");
530b57cec5SDimitry Andric return CurIndex;
540b57cec5SDimitry Andric }
550b57cec5SDimitry Andric // Given an array type, recursively traverse the elements.
560b57cec5SDimitry Andric else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
570b57cec5SDimitry Andric Type *EltTy = ATy->getElementType();
580b57cec5SDimitry Andric unsigned NumElts = ATy->getNumElements();
590b57cec5SDimitry Andric // Compute the Linear offset when jumping one element of the array
600b57cec5SDimitry Andric unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
610b57cec5SDimitry Andric if (Indices) {
620b57cec5SDimitry Andric assert(*Indices < NumElts && "Unexpected out of bound");
630b57cec5SDimitry Andric // If the indice is inside the array, compute the index to the requested
640b57cec5SDimitry Andric // elt and recurse inside the element with the end of the indices list
650b57cec5SDimitry Andric CurIndex += EltLinearOffset* *Indices;
660b57cec5SDimitry Andric return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric CurIndex += EltLinearOffset*NumElts;
690b57cec5SDimitry Andric return CurIndex;
700b57cec5SDimitry Andric }
710b57cec5SDimitry Andric // We haven't found the type we're looking for, so keep searching.
720b57cec5SDimitry Andric return CurIndex + 1;
730b57cec5SDimitry Andric }
740b57cec5SDimitry Andric
750b57cec5SDimitry Andric /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
760b57cec5SDimitry Andric /// EVTs that represent all the individual underlying
770b57cec5SDimitry Andric /// non-aggregate types that comprise it.
780b57cec5SDimitry Andric ///
790b57cec5SDimitry Andric /// If Offsets is non-null, it points to a vector to be filled in
800b57cec5SDimitry Andric /// with the in-memory offsets of each of the individual values.
810b57cec5SDimitry Andric ///
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<EVT> * MemVTs,SmallVectorImpl<uint64_t> * Offsets,uint64_t StartingOffset)820b57cec5SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
830b57cec5SDimitry Andric Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
840b57cec5SDimitry Andric SmallVectorImpl<EVT> *MemVTs,
850b57cec5SDimitry Andric SmallVectorImpl<uint64_t> *Offsets,
860b57cec5SDimitry Andric uint64_t StartingOffset) {
870b57cec5SDimitry Andric // Given a struct type, recursively traverse the elements.
880b57cec5SDimitry Andric if (StructType *STy = dyn_cast<StructType>(Ty)) {
89af732203SDimitry Andric // If the Offsets aren't needed, don't query the struct layout. This allows
90af732203SDimitry Andric // us to support structs with scalable vectors for operations that don't
91af732203SDimitry Andric // need offsets.
92af732203SDimitry Andric const StructLayout *SL = Offsets ? DL.getStructLayout(STy) : nullptr;
930b57cec5SDimitry Andric for (StructType::element_iterator EB = STy->element_begin(),
940b57cec5SDimitry Andric EI = EB,
950b57cec5SDimitry Andric EE = STy->element_end();
96af732203SDimitry Andric EI != EE; ++EI) {
97af732203SDimitry Andric // Don't compute the element offset if we didn't get a StructLayout above.
98af732203SDimitry Andric uint64_t EltOffset = SL ? SL->getElementOffset(EI - EB) : 0;
990b57cec5SDimitry Andric ComputeValueVTs(TLI, DL, *EI, ValueVTs, MemVTs, Offsets,
100af732203SDimitry Andric StartingOffset + EltOffset);
101af732203SDimitry Andric }
1020b57cec5SDimitry Andric return;
1030b57cec5SDimitry Andric }
1040b57cec5SDimitry Andric // Given an array type, recursively traverse the elements.
1050b57cec5SDimitry Andric if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1060b57cec5SDimitry Andric Type *EltTy = ATy->getElementType();
107af732203SDimitry Andric uint64_t EltSize = DL.getTypeAllocSize(EltTy).getFixedValue();
1080b57cec5SDimitry Andric for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1090b57cec5SDimitry Andric ComputeValueVTs(TLI, DL, EltTy, ValueVTs, MemVTs, Offsets,
1100b57cec5SDimitry Andric StartingOffset + i * EltSize);
1110b57cec5SDimitry Andric return;
1120b57cec5SDimitry Andric }
1130b57cec5SDimitry Andric // Interpret void as zero return values.
1140b57cec5SDimitry Andric if (Ty->isVoidTy())
1150b57cec5SDimitry Andric return;
1160b57cec5SDimitry Andric // Base case: we can get an EVT for this LLVM IR type.
1170b57cec5SDimitry Andric ValueVTs.push_back(TLI.getValueType(DL, Ty));
1180b57cec5SDimitry Andric if (MemVTs)
1190b57cec5SDimitry Andric MemVTs->push_back(TLI.getMemValueType(DL, Ty));
1200b57cec5SDimitry Andric if (Offsets)
1210b57cec5SDimitry Andric Offsets->push_back(StartingOffset);
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric
ComputeValueVTs(const TargetLowering & TLI,const DataLayout & DL,Type * Ty,SmallVectorImpl<EVT> & ValueVTs,SmallVectorImpl<uint64_t> * Offsets,uint64_t StartingOffset)1240b57cec5SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
1250b57cec5SDimitry Andric Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
1260b57cec5SDimitry Andric SmallVectorImpl<uint64_t> *Offsets,
1270b57cec5SDimitry Andric uint64_t StartingOffset) {
1280b57cec5SDimitry Andric return ComputeValueVTs(TLI, DL, Ty, ValueVTs, /*MemVTs=*/nullptr, Offsets,
1290b57cec5SDimitry Andric StartingOffset);
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric
computeValueLLTs(const DataLayout & DL,Type & Ty,SmallVectorImpl<LLT> & ValueTys,SmallVectorImpl<uint64_t> * Offsets,uint64_t StartingOffset)1320b57cec5SDimitry Andric void llvm::computeValueLLTs(const DataLayout &DL, Type &Ty,
1330b57cec5SDimitry Andric SmallVectorImpl<LLT> &ValueTys,
1340b57cec5SDimitry Andric SmallVectorImpl<uint64_t> *Offsets,
1350b57cec5SDimitry Andric uint64_t StartingOffset) {
1360b57cec5SDimitry Andric // Given a struct type, recursively traverse the elements.
1370b57cec5SDimitry Andric if (StructType *STy = dyn_cast<StructType>(&Ty)) {
138af732203SDimitry Andric // If the Offsets aren't needed, don't query the struct layout. This allows
139af732203SDimitry Andric // us to support structs with scalable vectors for operations that don't
140af732203SDimitry Andric // need offsets.
141af732203SDimitry Andric const StructLayout *SL = Offsets ? DL.getStructLayout(STy) : nullptr;
142af732203SDimitry Andric for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
143af732203SDimitry Andric uint64_t EltOffset = SL ? SL->getElementOffset(I) : 0;
1440b57cec5SDimitry Andric computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
145af732203SDimitry Andric StartingOffset + EltOffset);
146af732203SDimitry Andric }
1470b57cec5SDimitry Andric return;
1480b57cec5SDimitry Andric }
1490b57cec5SDimitry Andric // Given an array type, recursively traverse the elements.
1500b57cec5SDimitry Andric if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
1510b57cec5SDimitry Andric Type *EltTy = ATy->getElementType();
152af732203SDimitry Andric uint64_t EltSize = DL.getTypeAllocSize(EltTy).getFixedValue();
1530b57cec5SDimitry Andric for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1540b57cec5SDimitry Andric computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
1550b57cec5SDimitry Andric StartingOffset + i * EltSize);
1560b57cec5SDimitry Andric return;
1570b57cec5SDimitry Andric }
1580b57cec5SDimitry Andric // Interpret void as zero return values.
1590b57cec5SDimitry Andric if (Ty.isVoidTy())
1600b57cec5SDimitry Andric return;
1610b57cec5SDimitry Andric // Base case: we can get an LLT for this LLVM IR type.
1620b57cec5SDimitry Andric ValueTys.push_back(getLLTForType(Ty, DL));
1630b57cec5SDimitry Andric if (Offsets != nullptr)
1640b57cec5SDimitry Andric Offsets->push_back(StartingOffset * 8);
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric
1670b57cec5SDimitry Andric /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
ExtractTypeInfo(Value * V)1680b57cec5SDimitry Andric GlobalValue *llvm::ExtractTypeInfo(Value *V) {
1690b57cec5SDimitry Andric V = V->stripPointerCasts();
1700b57cec5SDimitry Andric GlobalValue *GV = dyn_cast<GlobalValue>(V);
1710b57cec5SDimitry Andric GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
1720b57cec5SDimitry Andric
1730b57cec5SDimitry Andric if (Var && Var->getName() == "llvm.eh.catch.all.value") {
1740b57cec5SDimitry Andric assert(Var->hasInitializer() &&
1750b57cec5SDimitry Andric "The EH catch-all value must have an initializer");
1760b57cec5SDimitry Andric Value *Init = Var->getInitializer();
1770b57cec5SDimitry Andric GV = dyn_cast<GlobalValue>(Init);
1780b57cec5SDimitry Andric if (!GV) V = cast<ConstantPointerNull>(Init);
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric
1810b57cec5SDimitry Andric assert((GV || isa<ConstantPointerNull>(V)) &&
1820b57cec5SDimitry Andric "TypeInfo must be a global variable or NULL");
1830b57cec5SDimitry Andric return GV;
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric
1860b57cec5SDimitry Andric /// getFCmpCondCode - Return the ISD condition code corresponding to
1870b57cec5SDimitry Andric /// the given LLVM IR floating-point condition code. This includes
1880b57cec5SDimitry Andric /// consideration of global floating-point math flags.
1890b57cec5SDimitry Andric ///
getFCmpCondCode(FCmpInst::Predicate Pred)1900b57cec5SDimitry Andric ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
1910b57cec5SDimitry Andric switch (Pred) {
1920b57cec5SDimitry Andric case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
1930b57cec5SDimitry Andric case FCmpInst::FCMP_OEQ: return ISD::SETOEQ;
1940b57cec5SDimitry Andric case FCmpInst::FCMP_OGT: return ISD::SETOGT;
1950b57cec5SDimitry Andric case FCmpInst::FCMP_OGE: return ISD::SETOGE;
1960b57cec5SDimitry Andric case FCmpInst::FCMP_OLT: return ISD::SETOLT;
1970b57cec5SDimitry Andric case FCmpInst::FCMP_OLE: return ISD::SETOLE;
1980b57cec5SDimitry Andric case FCmpInst::FCMP_ONE: return ISD::SETONE;
1990b57cec5SDimitry Andric case FCmpInst::FCMP_ORD: return ISD::SETO;
2000b57cec5SDimitry Andric case FCmpInst::FCMP_UNO: return ISD::SETUO;
2010b57cec5SDimitry Andric case FCmpInst::FCMP_UEQ: return ISD::SETUEQ;
2020b57cec5SDimitry Andric case FCmpInst::FCMP_UGT: return ISD::SETUGT;
2030b57cec5SDimitry Andric case FCmpInst::FCMP_UGE: return ISD::SETUGE;
2040b57cec5SDimitry Andric case FCmpInst::FCMP_ULT: return ISD::SETULT;
2050b57cec5SDimitry Andric case FCmpInst::FCMP_ULE: return ISD::SETULE;
2060b57cec5SDimitry Andric case FCmpInst::FCMP_UNE: return ISD::SETUNE;
2070b57cec5SDimitry Andric case FCmpInst::FCMP_TRUE: return ISD::SETTRUE;
2080b57cec5SDimitry Andric default: llvm_unreachable("Invalid FCmp predicate opcode!");
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric
getFCmpCodeWithoutNaN(ISD::CondCode CC)2120b57cec5SDimitry Andric ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
2130b57cec5SDimitry Andric switch (CC) {
2140b57cec5SDimitry Andric case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
2150b57cec5SDimitry Andric case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
2160b57cec5SDimitry Andric case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
2170b57cec5SDimitry Andric case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
2180b57cec5SDimitry Andric case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
2190b57cec5SDimitry Andric case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
2200b57cec5SDimitry Andric default: return CC;
2210b57cec5SDimitry Andric }
2220b57cec5SDimitry Andric }
2230b57cec5SDimitry Andric
2240b57cec5SDimitry Andric /// getICmpCondCode - Return the ISD condition code corresponding to
2250b57cec5SDimitry Andric /// the given LLVM IR integer condition code.
2260b57cec5SDimitry Andric ///
getICmpCondCode(ICmpInst::Predicate Pred)2270b57cec5SDimitry Andric ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
2280b57cec5SDimitry Andric switch (Pred) {
2290b57cec5SDimitry Andric case ICmpInst::ICMP_EQ: return ISD::SETEQ;
2300b57cec5SDimitry Andric case ICmpInst::ICMP_NE: return ISD::SETNE;
2310b57cec5SDimitry Andric case ICmpInst::ICMP_SLE: return ISD::SETLE;
2320b57cec5SDimitry Andric case ICmpInst::ICMP_ULE: return ISD::SETULE;
2330b57cec5SDimitry Andric case ICmpInst::ICMP_SGE: return ISD::SETGE;
2340b57cec5SDimitry Andric case ICmpInst::ICMP_UGE: return ISD::SETUGE;
2350b57cec5SDimitry Andric case ICmpInst::ICMP_SLT: return ISD::SETLT;
2360b57cec5SDimitry Andric case ICmpInst::ICMP_ULT: return ISD::SETULT;
2370b57cec5SDimitry Andric case ICmpInst::ICMP_SGT: return ISD::SETGT;
2380b57cec5SDimitry Andric case ICmpInst::ICMP_UGT: return ISD::SETUGT;
2390b57cec5SDimitry Andric default:
2400b57cec5SDimitry Andric llvm_unreachable("Invalid ICmp predicate opcode!");
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric
isNoopBitcast(Type * T1,Type * T2,const TargetLoweringBase & TLI)2440b57cec5SDimitry Andric static bool isNoopBitcast(Type *T1, Type *T2,
2450b57cec5SDimitry Andric const TargetLoweringBase& TLI) {
2460b57cec5SDimitry Andric return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
2470b57cec5SDimitry Andric (isa<VectorType>(T1) && isa<VectorType>(T2) &&
2480b57cec5SDimitry Andric TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
2490b57cec5SDimitry Andric }
2500b57cec5SDimitry Andric
2510b57cec5SDimitry Andric /// Look through operations that will be free to find the earliest source of
2520b57cec5SDimitry Andric /// this value.
2530b57cec5SDimitry Andric ///
254480093f4SDimitry Andric /// @param ValLoc If V has aggregate type, we will be interested in a particular
2550b57cec5SDimitry Andric /// scalar component. This records its address; the reverse of this list gives a
2560b57cec5SDimitry Andric /// sequence of indices appropriate for an extractvalue to locate the important
2570b57cec5SDimitry Andric /// value. This value is updated during the function and on exit will indicate
2580b57cec5SDimitry Andric /// similar information for the Value returned.
2590b57cec5SDimitry Andric ///
2600b57cec5SDimitry Andric /// @param DataBits If this function looks through truncate instructions, this
2610b57cec5SDimitry Andric /// will record the smallest size attained.
getNoopInput(const Value * V,SmallVectorImpl<unsigned> & ValLoc,unsigned & DataBits,const TargetLoweringBase & TLI,const DataLayout & DL)2620b57cec5SDimitry Andric static const Value *getNoopInput(const Value *V,
2630b57cec5SDimitry Andric SmallVectorImpl<unsigned> &ValLoc,
2640b57cec5SDimitry Andric unsigned &DataBits,
2650b57cec5SDimitry Andric const TargetLoweringBase &TLI,
2660b57cec5SDimitry Andric const DataLayout &DL) {
2670b57cec5SDimitry Andric while (true) {
2680b57cec5SDimitry Andric // Try to look through V1; if V1 is not an instruction, it can't be looked
2690b57cec5SDimitry Andric // through.
2700b57cec5SDimitry Andric const Instruction *I = dyn_cast<Instruction>(V);
2710b57cec5SDimitry Andric if (!I || I->getNumOperands() == 0) return V;
2720b57cec5SDimitry Andric const Value *NoopInput = nullptr;
2730b57cec5SDimitry Andric
2740b57cec5SDimitry Andric Value *Op = I->getOperand(0);
2750b57cec5SDimitry Andric if (isa<BitCastInst>(I)) {
2760b57cec5SDimitry Andric // Look through truly no-op bitcasts.
2770b57cec5SDimitry Andric if (isNoopBitcast(Op->getType(), I->getType(), TLI))
2780b57cec5SDimitry Andric NoopInput = Op;
2790b57cec5SDimitry Andric } else if (isa<GetElementPtrInst>(I)) {
2800b57cec5SDimitry Andric // Look through getelementptr
2810b57cec5SDimitry Andric if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
2820b57cec5SDimitry Andric NoopInput = Op;
2830b57cec5SDimitry Andric } else if (isa<IntToPtrInst>(I)) {
2840b57cec5SDimitry Andric // Look through inttoptr.
2850b57cec5SDimitry Andric // Make sure this isn't a truncating or extending cast. We could
2860b57cec5SDimitry Andric // support this eventually, but don't bother for now.
2870b57cec5SDimitry Andric if (!isa<VectorType>(I->getType()) &&
2880b57cec5SDimitry Andric DL.getPointerSizeInBits() ==
2890b57cec5SDimitry Andric cast<IntegerType>(Op->getType())->getBitWidth())
2900b57cec5SDimitry Andric NoopInput = Op;
2910b57cec5SDimitry Andric } else if (isa<PtrToIntInst>(I)) {
2920b57cec5SDimitry Andric // Look through ptrtoint.
2930b57cec5SDimitry Andric // Make sure this isn't a truncating or extending cast. We could
2940b57cec5SDimitry Andric // support this eventually, but don't bother for now.
2950b57cec5SDimitry Andric if (!isa<VectorType>(I->getType()) &&
2960b57cec5SDimitry Andric DL.getPointerSizeInBits() ==
2970b57cec5SDimitry Andric cast<IntegerType>(I->getType())->getBitWidth())
2980b57cec5SDimitry Andric NoopInput = Op;
2990b57cec5SDimitry Andric } else if (isa<TruncInst>(I) &&
3000b57cec5SDimitry Andric TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
3018bcb0991SDimitry Andric DataBits = std::min((uint64_t)DataBits,
3028bcb0991SDimitry Andric I->getType()->getPrimitiveSizeInBits().getFixedSize());
3030b57cec5SDimitry Andric NoopInput = Op;
3045ffd83dbSDimitry Andric } else if (auto *CB = dyn_cast<CallBase>(I)) {
3055ffd83dbSDimitry Andric const Value *ReturnedOp = CB->getReturnedArgOperand();
3060b57cec5SDimitry Andric if (ReturnedOp && isNoopBitcast(ReturnedOp->getType(), I->getType(), TLI))
3070b57cec5SDimitry Andric NoopInput = ReturnedOp;
3080b57cec5SDimitry Andric } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
3090b57cec5SDimitry Andric // Value may come from either the aggregate or the scalar
3100b57cec5SDimitry Andric ArrayRef<unsigned> InsertLoc = IVI->getIndices();
3110b57cec5SDimitry Andric if (ValLoc.size() >= InsertLoc.size() &&
3120b57cec5SDimitry Andric std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
3130b57cec5SDimitry Andric // The type being inserted is a nested sub-type of the aggregate; we
3140b57cec5SDimitry Andric // have to remove those initial indices to get the location we're
3150b57cec5SDimitry Andric // interested in for the operand.
3160b57cec5SDimitry Andric ValLoc.resize(ValLoc.size() - InsertLoc.size());
3170b57cec5SDimitry Andric NoopInput = IVI->getInsertedValueOperand();
3180b57cec5SDimitry Andric } else {
3190b57cec5SDimitry Andric // The struct we're inserting into has the value we're interested in, no
3200b57cec5SDimitry Andric // change of address.
3210b57cec5SDimitry Andric NoopInput = Op;
3220b57cec5SDimitry Andric }
3230b57cec5SDimitry Andric } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
3240b57cec5SDimitry Andric // The part we're interested in will inevitably be some sub-section of the
3250b57cec5SDimitry Andric // previous aggregate. Combine the two paths to obtain the true address of
3260b57cec5SDimitry Andric // our element.
3270b57cec5SDimitry Andric ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
3280b57cec5SDimitry Andric ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
3290b57cec5SDimitry Andric NoopInput = Op;
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric // Terminate if we couldn't find anything to look through.
3320b57cec5SDimitry Andric if (!NoopInput)
3330b57cec5SDimitry Andric return V;
3340b57cec5SDimitry Andric
3350b57cec5SDimitry Andric V = NoopInput;
3360b57cec5SDimitry Andric }
3370b57cec5SDimitry Andric }
3380b57cec5SDimitry Andric
3390b57cec5SDimitry Andric /// Return true if this scalar return value only has bits discarded on its path
3400b57cec5SDimitry Andric /// from the "tail call" to the "ret". This includes the obvious noop
3410b57cec5SDimitry Andric /// instructions handled by getNoopInput above as well as free truncations (or
3420b57cec5SDimitry Andric /// extensions prior to the call).
slotOnlyDiscardsData(const Value * RetVal,const Value * CallVal,SmallVectorImpl<unsigned> & RetIndices,SmallVectorImpl<unsigned> & CallIndices,bool AllowDifferingSizes,const TargetLoweringBase & TLI,const DataLayout & DL)3430b57cec5SDimitry Andric static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
3440b57cec5SDimitry Andric SmallVectorImpl<unsigned> &RetIndices,
3450b57cec5SDimitry Andric SmallVectorImpl<unsigned> &CallIndices,
3460b57cec5SDimitry Andric bool AllowDifferingSizes,
3470b57cec5SDimitry Andric const TargetLoweringBase &TLI,
3480b57cec5SDimitry Andric const DataLayout &DL) {
3490b57cec5SDimitry Andric
3500b57cec5SDimitry Andric // Trace the sub-value needed by the return value as far back up the graph as
3510b57cec5SDimitry Andric // possible, in the hope that it will intersect with the value produced by the
3520b57cec5SDimitry Andric // call. In the simple case with no "returned" attribute, the hope is actually
3530b57cec5SDimitry Andric // that we end up back at the tail call instruction itself.
3540b57cec5SDimitry Andric unsigned BitsRequired = UINT_MAX;
3550b57cec5SDimitry Andric RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL);
3560b57cec5SDimitry Andric
3570b57cec5SDimitry Andric // If this slot in the value returned is undef, it doesn't matter what the
3580b57cec5SDimitry Andric // call puts there, it'll be fine.
3590b57cec5SDimitry Andric if (isa<UndefValue>(RetVal))
3600b57cec5SDimitry Andric return true;
3610b57cec5SDimitry Andric
3620b57cec5SDimitry Andric // Now do a similar search up through the graph to find where the value
3630b57cec5SDimitry Andric // actually returned by the "tail call" comes from. In the simple case without
3640b57cec5SDimitry Andric // a "returned" attribute, the search will be blocked immediately and the loop
3650b57cec5SDimitry Andric // a Noop.
3660b57cec5SDimitry Andric unsigned BitsProvided = UINT_MAX;
3670b57cec5SDimitry Andric CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL);
3680b57cec5SDimitry Andric
3690b57cec5SDimitry Andric // There's no hope if we can't actually trace them to (the same part of!) the
3700b57cec5SDimitry Andric // same value.
3710b57cec5SDimitry Andric if (CallVal != RetVal || CallIndices != RetIndices)
3720b57cec5SDimitry Andric return false;
3730b57cec5SDimitry Andric
3740b57cec5SDimitry Andric // However, intervening truncates may have made the call non-tail. Make sure
3750b57cec5SDimitry Andric // all the bits that are needed by the "ret" have been provided by the "tail
3760b57cec5SDimitry Andric // call". FIXME: with sufficiently cunning bit-tracking, we could look through
3770b57cec5SDimitry Andric // extensions too.
3780b57cec5SDimitry Andric if (BitsProvided < BitsRequired ||
3790b57cec5SDimitry Andric (!AllowDifferingSizes && BitsProvided != BitsRequired))
3800b57cec5SDimitry Andric return false;
3810b57cec5SDimitry Andric
3820b57cec5SDimitry Andric return true;
3830b57cec5SDimitry Andric }
3840b57cec5SDimitry Andric
3850b57cec5SDimitry Andric /// For an aggregate type, determine whether a given index is within bounds or
3860b57cec5SDimitry Andric /// not.
indexReallyValid(Type * T,unsigned Idx)3875ffd83dbSDimitry Andric static bool indexReallyValid(Type *T, unsigned Idx) {
3880b57cec5SDimitry Andric if (ArrayType *AT = dyn_cast<ArrayType>(T))
3890b57cec5SDimitry Andric return Idx < AT->getNumElements();
3900b57cec5SDimitry Andric
3910b57cec5SDimitry Andric return Idx < cast<StructType>(T)->getNumElements();
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric
3940b57cec5SDimitry Andric /// Move the given iterators to the next leaf type in depth first traversal.
3950b57cec5SDimitry Andric ///
3960b57cec5SDimitry Andric /// Performs a depth-first traversal of the type as specified by its arguments,
3970b57cec5SDimitry Andric /// stopping at the next leaf node (which may be a legitimate scalar type or an
3980b57cec5SDimitry Andric /// empty struct or array).
3990b57cec5SDimitry Andric ///
4000b57cec5SDimitry Andric /// @param SubTypes List of the partial components making up the type from
4010b57cec5SDimitry Andric /// outermost to innermost non-empty aggregate. The element currently
4020b57cec5SDimitry Andric /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
4030b57cec5SDimitry Andric ///
4040b57cec5SDimitry Andric /// @param Path Set of extractvalue indices leading from the outermost type
4050b57cec5SDimitry Andric /// (SubTypes[0]) to the leaf node currently represented.
4060b57cec5SDimitry Andric ///
4070b57cec5SDimitry Andric /// @returns true if a new type was found, false otherwise. Calling this
4080b57cec5SDimitry Andric /// function again on a finished iterator will repeatedly return
4090b57cec5SDimitry Andric /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
4100b57cec5SDimitry Andric /// aggregate or a non-aggregate
advanceToNextLeafType(SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)4115ffd83dbSDimitry Andric static bool advanceToNextLeafType(SmallVectorImpl<Type *> &SubTypes,
4120b57cec5SDimitry Andric SmallVectorImpl<unsigned> &Path) {
4130b57cec5SDimitry Andric // First march back up the tree until we can successfully increment one of the
4140b57cec5SDimitry Andric // coordinates in Path.
4150b57cec5SDimitry Andric while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
4160b57cec5SDimitry Andric Path.pop_back();
4170b57cec5SDimitry Andric SubTypes.pop_back();
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric
4200b57cec5SDimitry Andric // If we reached the top, then the iterator is done.
4210b57cec5SDimitry Andric if (Path.empty())
4220b57cec5SDimitry Andric return false;
4230b57cec5SDimitry Andric
4240b57cec5SDimitry Andric // We know there's *some* valid leaf now, so march back down the tree picking
4250b57cec5SDimitry Andric // out the left-most element at each node.
4260b57cec5SDimitry Andric ++Path.back();
4275ffd83dbSDimitry Andric Type *DeeperType =
4285ffd83dbSDimitry Andric ExtractValueInst::getIndexedType(SubTypes.back(), Path.back());
4290b57cec5SDimitry Andric while (DeeperType->isAggregateType()) {
4305ffd83dbSDimitry Andric if (!indexReallyValid(DeeperType, 0))
4310b57cec5SDimitry Andric return true;
4320b57cec5SDimitry Andric
4335ffd83dbSDimitry Andric SubTypes.push_back(DeeperType);
4340b57cec5SDimitry Andric Path.push_back(0);
4350b57cec5SDimitry Andric
4365ffd83dbSDimitry Andric DeeperType = ExtractValueInst::getIndexedType(DeeperType, 0);
4370b57cec5SDimitry Andric }
4380b57cec5SDimitry Andric
4390b57cec5SDimitry Andric return true;
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric
4420b57cec5SDimitry Andric /// Find the first non-empty, scalar-like type in Next and setup the iterator
4430b57cec5SDimitry Andric /// components.
4440b57cec5SDimitry Andric ///
4450b57cec5SDimitry Andric /// Assuming Next is an aggregate of some kind, this function will traverse the
4460b57cec5SDimitry Andric /// tree from left to right (i.e. depth-first) looking for the first
4470b57cec5SDimitry Andric /// non-aggregate type which will play a role in function return.
4480b57cec5SDimitry Andric ///
4490b57cec5SDimitry Andric /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
4500b57cec5SDimitry Andric /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
4510b57cec5SDimitry Andric /// i32 in that type.
firstRealType(Type * Next,SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)4525ffd83dbSDimitry Andric static bool firstRealType(Type *Next, SmallVectorImpl<Type *> &SubTypes,
4530b57cec5SDimitry Andric SmallVectorImpl<unsigned> &Path) {
4540b57cec5SDimitry Andric // First initialise the iterator components to the first "leaf" node
4550b57cec5SDimitry Andric // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
4560b57cec5SDimitry Andric // despite nominally being an aggregate).
4575ffd83dbSDimitry Andric while (Type *FirstInner = ExtractValueInst::getIndexedType(Next, 0)) {
4585ffd83dbSDimitry Andric SubTypes.push_back(Next);
4590b57cec5SDimitry Andric Path.push_back(0);
4605ffd83dbSDimitry Andric Next = FirstInner;
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric
4630b57cec5SDimitry Andric // If there's no Path now, Next was originally scalar already (or empty
4640b57cec5SDimitry Andric // leaf). We're done.
4650b57cec5SDimitry Andric if (Path.empty())
4660b57cec5SDimitry Andric return true;
4670b57cec5SDimitry Andric
4680b57cec5SDimitry Andric // Otherwise, use normal iteration to keep looking through the tree until we
4690b57cec5SDimitry Andric // find a non-aggregate type.
4705ffd83dbSDimitry Andric while (ExtractValueInst::getIndexedType(SubTypes.back(), Path.back())
4715ffd83dbSDimitry Andric ->isAggregateType()) {
4720b57cec5SDimitry Andric if (!advanceToNextLeafType(SubTypes, Path))
4730b57cec5SDimitry Andric return false;
4740b57cec5SDimitry Andric }
4750b57cec5SDimitry Andric
4760b57cec5SDimitry Andric return true;
4770b57cec5SDimitry Andric }
4780b57cec5SDimitry Andric
4790b57cec5SDimitry Andric /// Set the iterator data-structures to the next non-empty, non-aggregate
4800b57cec5SDimitry Andric /// subtype.
nextRealType(SmallVectorImpl<Type * > & SubTypes,SmallVectorImpl<unsigned> & Path)4815ffd83dbSDimitry Andric static bool nextRealType(SmallVectorImpl<Type *> &SubTypes,
4820b57cec5SDimitry Andric SmallVectorImpl<unsigned> &Path) {
4830b57cec5SDimitry Andric do {
4840b57cec5SDimitry Andric if (!advanceToNextLeafType(SubTypes, Path))
4850b57cec5SDimitry Andric return false;
4860b57cec5SDimitry Andric
4870b57cec5SDimitry Andric assert(!Path.empty() && "found a leaf but didn't set the path?");
4885ffd83dbSDimitry Andric } while (ExtractValueInst::getIndexedType(SubTypes.back(), Path.back())
4895ffd83dbSDimitry Andric ->isAggregateType());
4900b57cec5SDimitry Andric
4910b57cec5SDimitry Andric return true;
4920b57cec5SDimitry Andric }
4930b57cec5SDimitry Andric
4940b57cec5SDimitry Andric
4950b57cec5SDimitry Andric /// Test if the given instruction is in a position to be optimized
4960b57cec5SDimitry Andric /// with a tail-call. This roughly means that it's in a block with
4970b57cec5SDimitry Andric /// a return and there's nothing that needs to be scheduled
4980b57cec5SDimitry Andric /// between it and the return.
4990b57cec5SDimitry Andric ///
5000b57cec5SDimitry Andric /// This function only tests target-independent requirements.
isInTailCallPosition(const CallBase & Call,const TargetMachine & TM)5015ffd83dbSDimitry Andric bool llvm::isInTailCallPosition(const CallBase &Call, const TargetMachine &TM) {
5025ffd83dbSDimitry Andric const BasicBlock *ExitBB = Call.getParent();
5030b57cec5SDimitry Andric const Instruction *Term = ExitBB->getTerminator();
5040b57cec5SDimitry Andric const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
5050b57cec5SDimitry Andric
5060b57cec5SDimitry Andric // The block must end in a return statement or unreachable.
5070b57cec5SDimitry Andric //
5080b57cec5SDimitry Andric // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
5090b57cec5SDimitry Andric // an unreachable, for now. The way tailcall optimization is currently
5100b57cec5SDimitry Andric // implemented means it will add an epilogue followed by a jump. That is
5110b57cec5SDimitry Andric // not profitable. Also, if the callee is a special function (e.g.
5120b57cec5SDimitry Andric // longjmp on x86), it can end up causing miscompilation that has not
5130b57cec5SDimitry Andric // been fully understood.
514*5f7ddb14SDimitry Andric if (!Ret && ((!TM.Options.GuaranteedTailCallOpt &&
515*5f7ddb14SDimitry Andric Call.getCallingConv() != CallingConv::Tail &&
516*5f7ddb14SDimitry Andric Call.getCallingConv() != CallingConv::SwiftTail) ||
517*5f7ddb14SDimitry Andric !isa<UnreachableInst>(Term)))
5180b57cec5SDimitry Andric return false;
5190b57cec5SDimitry Andric
5200b57cec5SDimitry Andric // If I will have a chain, make sure no other instruction that will have a
5210b57cec5SDimitry Andric // chain interposes between I and the return.
5225ffd83dbSDimitry Andric // Check for all calls including speculatable functions.
5230b57cec5SDimitry Andric for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
5245ffd83dbSDimitry Andric if (&*BBI == &Call)
5250b57cec5SDimitry Andric break;
5260b57cec5SDimitry Andric // Debug info intrinsics do not get in the way of tail call optimization.
5270b57cec5SDimitry Andric if (isa<DbgInfoIntrinsic>(BBI))
5280b57cec5SDimitry Andric continue;
529af732203SDimitry Andric // Pseudo probe intrinsics do not block tail call optimization either.
530af732203SDimitry Andric if (isa<PseudoProbeInst>(BBI))
531af732203SDimitry Andric continue;
532af732203SDimitry Andric // A lifetime end, assume or noalias.decl intrinsic should not stop tail
533af732203SDimitry Andric // call optimization.
5340b57cec5SDimitry Andric if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
5358bcb0991SDimitry Andric if (II->getIntrinsicID() == Intrinsic::lifetime_end ||
536af732203SDimitry Andric II->getIntrinsicID() == Intrinsic::assume ||
537af732203SDimitry Andric II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl)
5380b57cec5SDimitry Andric continue;
5390b57cec5SDimitry Andric if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
5400b57cec5SDimitry Andric !isSafeToSpeculativelyExecute(&*BBI))
5410b57cec5SDimitry Andric return false;
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric
5440b57cec5SDimitry Andric const Function *F = ExitBB->getParent();
5450b57cec5SDimitry Andric return returnTypeIsEligibleForTailCall(
5465ffd83dbSDimitry Andric F, &Call, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering());
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric
attributesPermitTailCall(const Function * F,const Instruction * I,const ReturnInst * Ret,const TargetLoweringBase & TLI,bool * AllowDifferingSizes)5490b57cec5SDimitry Andric bool llvm::attributesPermitTailCall(const Function *F, const Instruction *I,
5500b57cec5SDimitry Andric const ReturnInst *Ret,
5510b57cec5SDimitry Andric const TargetLoweringBase &TLI,
5520b57cec5SDimitry Andric bool *AllowDifferingSizes) {
5530b57cec5SDimitry Andric // ADS may be null, so don't write to it directly.
5540b57cec5SDimitry Andric bool DummyADS;
5550b57cec5SDimitry Andric bool &ADS = AllowDifferingSizes ? *AllowDifferingSizes : DummyADS;
5560b57cec5SDimitry Andric ADS = true;
5570b57cec5SDimitry Andric
5580b57cec5SDimitry Andric AttrBuilder CallerAttrs(F->getAttributes(), AttributeList::ReturnIndex);
5590b57cec5SDimitry Andric AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
5600b57cec5SDimitry Andric AttributeList::ReturnIndex);
5610b57cec5SDimitry Andric
562480093f4SDimitry Andric // Following attributes are completely benign as far as calling convention
5630b57cec5SDimitry Andric // goes, they shouldn't affect whether the call is a tail call.
564*5f7ddb14SDimitry Andric for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
565*5f7ddb14SDimitry Andric Attribute::DereferenceableOrNull, Attribute::NoAlias,
566*5f7ddb14SDimitry Andric Attribute::NonNull}) {
567*5f7ddb14SDimitry Andric CallerAttrs.removeAttribute(Attr);
568*5f7ddb14SDimitry Andric CalleeAttrs.removeAttribute(Attr);
569*5f7ddb14SDimitry Andric }
5700b57cec5SDimitry Andric
5710b57cec5SDimitry Andric if (CallerAttrs.contains(Attribute::ZExt)) {
5720b57cec5SDimitry Andric if (!CalleeAttrs.contains(Attribute::ZExt))
5730b57cec5SDimitry Andric return false;
5740b57cec5SDimitry Andric
5750b57cec5SDimitry Andric ADS = false;
5760b57cec5SDimitry Andric CallerAttrs.removeAttribute(Attribute::ZExt);
5770b57cec5SDimitry Andric CalleeAttrs.removeAttribute(Attribute::ZExt);
5780b57cec5SDimitry Andric } else if (CallerAttrs.contains(Attribute::SExt)) {
5790b57cec5SDimitry Andric if (!CalleeAttrs.contains(Attribute::SExt))
5800b57cec5SDimitry Andric return false;
5810b57cec5SDimitry Andric
5820b57cec5SDimitry Andric ADS = false;
5830b57cec5SDimitry Andric CallerAttrs.removeAttribute(Attribute::SExt);
5840b57cec5SDimitry Andric CalleeAttrs.removeAttribute(Attribute::SExt);
5850b57cec5SDimitry Andric }
5860b57cec5SDimitry Andric
5870b57cec5SDimitry Andric // Drop sext and zext return attributes if the result is not used.
5880b57cec5SDimitry Andric // This enables tail calls for code like:
5890b57cec5SDimitry Andric //
5900b57cec5SDimitry Andric // define void @caller() {
5910b57cec5SDimitry Andric // entry:
5920b57cec5SDimitry Andric // %unused_result = tail call zeroext i1 @callee()
5930b57cec5SDimitry Andric // br label %retlabel
5940b57cec5SDimitry Andric // retlabel:
5950b57cec5SDimitry Andric // ret void
5960b57cec5SDimitry Andric // }
5970b57cec5SDimitry Andric if (I->use_empty()) {
5980b57cec5SDimitry Andric CalleeAttrs.removeAttribute(Attribute::SExt);
5990b57cec5SDimitry Andric CalleeAttrs.removeAttribute(Attribute::ZExt);
6000b57cec5SDimitry Andric }
6010b57cec5SDimitry Andric
6020b57cec5SDimitry Andric // If they're still different, there's some facet we don't understand
6030b57cec5SDimitry Andric // (currently only "inreg", but in future who knows). It may be OK but the
6040b57cec5SDimitry Andric // only safe option is to reject the tail call.
6050b57cec5SDimitry Andric return CallerAttrs == CalleeAttrs;
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric
608480093f4SDimitry Andric /// Check whether B is a bitcast of a pointer type to another pointer type,
609480093f4SDimitry Andric /// which is equal to A.
isPointerBitcastEqualTo(const Value * A,const Value * B)610480093f4SDimitry Andric static bool isPointerBitcastEqualTo(const Value *A, const Value *B) {
611480093f4SDimitry Andric assert(A && B && "Expected non-null inputs!");
612480093f4SDimitry Andric
613480093f4SDimitry Andric auto *BitCastIn = dyn_cast<BitCastInst>(B);
614480093f4SDimitry Andric
615480093f4SDimitry Andric if (!BitCastIn)
616480093f4SDimitry Andric return false;
617480093f4SDimitry Andric
618480093f4SDimitry Andric if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
619480093f4SDimitry Andric return false;
620480093f4SDimitry Andric
621480093f4SDimitry Andric return A == BitCastIn->getOperand(0);
622480093f4SDimitry Andric }
623480093f4SDimitry Andric
returnTypeIsEligibleForTailCall(const Function * F,const Instruction * I,const ReturnInst * Ret,const TargetLoweringBase & TLI)6240b57cec5SDimitry Andric bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
6250b57cec5SDimitry Andric const Instruction *I,
6260b57cec5SDimitry Andric const ReturnInst *Ret,
6270b57cec5SDimitry Andric const TargetLoweringBase &TLI) {
6280b57cec5SDimitry Andric // If the block ends with a void return or unreachable, it doesn't matter
6290b57cec5SDimitry Andric // what the call's return type is.
6300b57cec5SDimitry Andric if (!Ret || Ret->getNumOperands() == 0) return true;
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric // If the return value is undef, it doesn't matter what the call's
6330b57cec5SDimitry Andric // return type is.
6340b57cec5SDimitry Andric if (isa<UndefValue>(Ret->getOperand(0))) return true;
6350b57cec5SDimitry Andric
6360b57cec5SDimitry Andric // Make sure the attributes attached to each return are compatible.
6370b57cec5SDimitry Andric bool AllowDifferingSizes;
6380b57cec5SDimitry Andric if (!attributesPermitTailCall(F, I, Ret, TLI, &AllowDifferingSizes))
6390b57cec5SDimitry Andric return false;
6400b57cec5SDimitry Andric
6410b57cec5SDimitry Andric const Value *RetVal = Ret->getOperand(0), *CallVal = I;
6420b57cec5SDimitry Andric // Intrinsic like llvm.memcpy has no return value, but the expanded
6430b57cec5SDimitry Andric // libcall may or may not have return value. On most platforms, it
6440b57cec5SDimitry Andric // will be expanded as memcpy in libc, which returns the first
6450b57cec5SDimitry Andric // argument. On other platforms like arm-none-eabi, memcpy may be
6460b57cec5SDimitry Andric // expanded as library call without return value, like __aeabi_memcpy.
6470b57cec5SDimitry Andric const CallInst *Call = cast<CallInst>(I);
6480b57cec5SDimitry Andric if (Function *F = Call->getCalledFunction()) {
6490b57cec5SDimitry Andric Intrinsic::ID IID = F->getIntrinsicID();
6500b57cec5SDimitry Andric if (((IID == Intrinsic::memcpy &&
6510b57cec5SDimitry Andric TLI.getLibcallName(RTLIB::MEMCPY) == StringRef("memcpy")) ||
6520b57cec5SDimitry Andric (IID == Intrinsic::memmove &&
6530b57cec5SDimitry Andric TLI.getLibcallName(RTLIB::MEMMOVE) == StringRef("memmove")) ||
6540b57cec5SDimitry Andric (IID == Intrinsic::memset &&
6550b57cec5SDimitry Andric TLI.getLibcallName(RTLIB::MEMSET) == StringRef("memset"))) &&
656480093f4SDimitry Andric (RetVal == Call->getArgOperand(0) ||
657480093f4SDimitry Andric isPointerBitcastEqualTo(RetVal, Call->getArgOperand(0))))
6580b57cec5SDimitry Andric return true;
6590b57cec5SDimitry Andric }
6600b57cec5SDimitry Andric
6610b57cec5SDimitry Andric SmallVector<unsigned, 4> RetPath, CallPath;
6625ffd83dbSDimitry Andric SmallVector<Type *, 4> RetSubTypes, CallSubTypes;
6630b57cec5SDimitry Andric
6640b57cec5SDimitry Andric bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
6650b57cec5SDimitry Andric bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
6660b57cec5SDimitry Andric
6670b57cec5SDimitry Andric // Nothing's actually returned, it doesn't matter what the callee put there
6680b57cec5SDimitry Andric // it's a valid tail call.
6690b57cec5SDimitry Andric if (RetEmpty)
6700b57cec5SDimitry Andric return true;
6710b57cec5SDimitry Andric
6720b57cec5SDimitry Andric // Iterate pairwise through each of the value types making up the tail call
6730b57cec5SDimitry Andric // and the corresponding return. For each one we want to know whether it's
6740b57cec5SDimitry Andric // essentially going directly from the tail call to the ret, via operations
6750b57cec5SDimitry Andric // that end up not generating any code.
6760b57cec5SDimitry Andric //
6770b57cec5SDimitry Andric // We allow a certain amount of covariance here. For example it's permitted
6780b57cec5SDimitry Andric // for the tail call to define more bits than the ret actually cares about
6790b57cec5SDimitry Andric // (e.g. via a truncate).
6800b57cec5SDimitry Andric do {
6810b57cec5SDimitry Andric if (CallEmpty) {
6820b57cec5SDimitry Andric // We've exhausted the values produced by the tail call instruction, the
6830b57cec5SDimitry Andric // rest are essentially undef. The type doesn't really matter, but we need
6840b57cec5SDimitry Andric // *something*.
6855ffd83dbSDimitry Andric Type *SlotType =
6865ffd83dbSDimitry Andric ExtractValueInst::getIndexedType(RetSubTypes.back(), RetPath.back());
6870b57cec5SDimitry Andric CallVal = UndefValue::get(SlotType);
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric
6900b57cec5SDimitry Andric // The manipulations performed when we're looking through an insertvalue or
6910b57cec5SDimitry Andric // an extractvalue would happen at the front of the RetPath list, so since
6920b57cec5SDimitry Andric // we have to copy it anyway it's more efficient to create a reversed copy.
6930b57cec5SDimitry Andric SmallVector<unsigned, 4> TmpRetPath(RetPath.rbegin(), RetPath.rend());
6940b57cec5SDimitry Andric SmallVector<unsigned, 4> TmpCallPath(CallPath.rbegin(), CallPath.rend());
6950b57cec5SDimitry Andric
6960b57cec5SDimitry Andric // Finally, we can check whether the value produced by the tail call at this
6970b57cec5SDimitry Andric // index is compatible with the value we return.
6980b57cec5SDimitry Andric if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
6990b57cec5SDimitry Andric AllowDifferingSizes, TLI,
7000b57cec5SDimitry Andric F->getParent()->getDataLayout()))
7010b57cec5SDimitry Andric return false;
7020b57cec5SDimitry Andric
7030b57cec5SDimitry Andric CallEmpty = !nextRealType(CallSubTypes, CallPath);
7040b57cec5SDimitry Andric } while(nextRealType(RetSubTypes, RetPath));
7050b57cec5SDimitry Andric
7060b57cec5SDimitry Andric return true;
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric
collectEHScopeMembers(DenseMap<const MachineBasicBlock *,int> & EHScopeMembership,int EHScope,const MachineBasicBlock * MBB)7090b57cec5SDimitry Andric static void collectEHScopeMembers(
7100b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, int> &EHScopeMembership, int EHScope,
7110b57cec5SDimitry Andric const MachineBasicBlock *MBB) {
7120b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB};
7130b57cec5SDimitry Andric while (!Worklist.empty()) {
7140b57cec5SDimitry Andric const MachineBasicBlock *Visiting = Worklist.pop_back_val();
7150b57cec5SDimitry Andric // Don't follow blocks which start new scopes.
7160b57cec5SDimitry Andric if (Visiting->isEHPad() && Visiting != MBB)
7170b57cec5SDimitry Andric continue;
7180b57cec5SDimitry Andric
7190b57cec5SDimitry Andric // Add this MBB to our scope.
7200b57cec5SDimitry Andric auto P = EHScopeMembership.insert(std::make_pair(Visiting, EHScope));
7210b57cec5SDimitry Andric
7220b57cec5SDimitry Andric // Don't revisit blocks.
7230b57cec5SDimitry Andric if (!P.second) {
7240b57cec5SDimitry Andric assert(P.first->second == EHScope && "MBB is part of two scopes!");
7250b57cec5SDimitry Andric continue;
7260b57cec5SDimitry Andric }
7270b57cec5SDimitry Andric
7280b57cec5SDimitry Andric // Returns are boundaries where scope transfer can occur, don't follow
7290b57cec5SDimitry Andric // successors.
7300b57cec5SDimitry Andric if (Visiting->isEHScopeReturnBlock())
7310b57cec5SDimitry Andric continue;
7320b57cec5SDimitry Andric
733af732203SDimitry Andric append_range(Worklist, Visiting->successors());
7340b57cec5SDimitry Andric }
7350b57cec5SDimitry Andric }
7360b57cec5SDimitry Andric
7370b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, int>
getEHScopeMembership(const MachineFunction & MF)7380b57cec5SDimitry Andric llvm::getEHScopeMembership(const MachineFunction &MF) {
7390b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, int> EHScopeMembership;
7400b57cec5SDimitry Andric
7410b57cec5SDimitry Andric // We don't have anything to do if there aren't any EH pads.
7420b57cec5SDimitry Andric if (!MF.hasEHScopes())
7430b57cec5SDimitry Andric return EHScopeMembership;
7440b57cec5SDimitry Andric
7450b57cec5SDimitry Andric int EntryBBNumber = MF.front().getNumber();
7460b57cec5SDimitry Andric bool IsSEH = isAsynchronousEHPersonality(
7470b57cec5SDimitry Andric classifyEHPersonality(MF.getFunction().getPersonalityFn()));
7480b57cec5SDimitry Andric
7490b57cec5SDimitry Andric const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7500b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 16> EHScopeBlocks;
7510b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks;
7520b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 16> SEHCatchPads;
7530b57cec5SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors;
7540b57cec5SDimitry Andric for (const MachineBasicBlock &MBB : MF) {
7550b57cec5SDimitry Andric if (MBB.isEHScopeEntry()) {
7560b57cec5SDimitry Andric EHScopeBlocks.push_back(&MBB);
7570b57cec5SDimitry Andric } else if (IsSEH && MBB.isEHPad()) {
7580b57cec5SDimitry Andric SEHCatchPads.push_back(&MBB);
7590b57cec5SDimitry Andric } else if (MBB.pred_empty()) {
7600b57cec5SDimitry Andric UnreachableBlocks.push_back(&MBB);
7610b57cec5SDimitry Andric }
7620b57cec5SDimitry Andric
7630b57cec5SDimitry Andric MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator();
7640b57cec5SDimitry Andric
7650b57cec5SDimitry Andric // CatchPads are not scopes for SEH so do not consider CatchRet to
7660b57cec5SDimitry Andric // transfer control to another scope.
7670b57cec5SDimitry Andric if (MBBI == MBB.end() || MBBI->getOpcode() != TII->getCatchReturnOpcode())
7680b57cec5SDimitry Andric continue;
7690b57cec5SDimitry Andric
7700b57cec5SDimitry Andric // FIXME: SEH CatchPads are not necessarily in the parent function:
7710b57cec5SDimitry Andric // they could be inside a finally block.
7720b57cec5SDimitry Andric const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB();
7730b57cec5SDimitry Andric const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB();
7740b57cec5SDimitry Andric CatchRetSuccessors.push_back(
7750b57cec5SDimitry Andric {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()});
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric
7780b57cec5SDimitry Andric // We don't have anything to do if there aren't any EH pads.
7790b57cec5SDimitry Andric if (EHScopeBlocks.empty())
7800b57cec5SDimitry Andric return EHScopeMembership;
7810b57cec5SDimitry Andric
7820b57cec5SDimitry Andric // Identify all the basic blocks reachable from the function entry.
7830b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, &MF.front());
7840b57cec5SDimitry Andric // All blocks not part of a scope are in the parent function.
7850b57cec5SDimitry Andric for (const MachineBasicBlock *MBB : UnreachableBlocks)
7860b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB);
7870b57cec5SDimitry Andric // Next, identify all the blocks inside the scopes.
7880b57cec5SDimitry Andric for (const MachineBasicBlock *MBB : EHScopeBlocks)
7890b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, MBB->getNumber(), MBB);
7900b57cec5SDimitry Andric // SEH CatchPads aren't really scopes, handle them separately.
7910b57cec5SDimitry Andric for (const MachineBasicBlock *MBB : SEHCatchPads)
7920b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB);
7930b57cec5SDimitry Andric // Finally, identify all the targets of a catchret.
7940b57cec5SDimitry Andric for (std::pair<const MachineBasicBlock *, int> CatchRetPair :
7950b57cec5SDimitry Andric CatchRetSuccessors)
7960b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, CatchRetPair.second,
7970b57cec5SDimitry Andric CatchRetPair.first);
7980b57cec5SDimitry Andric return EHScopeMembership;
7990b57cec5SDimitry Andric }
800