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/Module.h" 250b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 265ffd83dbSDimitry Andric #include "llvm/Target/TargetMachine.h" 270b57cec5SDimitry Andric 280b57cec5SDimitry Andric using namespace llvm; 290b57cec5SDimitry Andric 300b57cec5SDimitry Andric /// Compute the linearized index of a member in a nested aggregate/struct/array 310b57cec5SDimitry Andric /// by recursing and accumulating CurIndex as long as there are indices in the 320b57cec5SDimitry Andric /// index list. 330b57cec5SDimitry Andric unsigned llvm::ComputeLinearIndex(Type *Ty, 340b57cec5SDimitry Andric const unsigned *Indices, 350b57cec5SDimitry Andric const unsigned *IndicesEnd, 360b57cec5SDimitry Andric unsigned CurIndex) { 370b57cec5SDimitry Andric // Base case: We're done. 380b57cec5SDimitry Andric if (Indices && Indices == IndicesEnd) 390b57cec5SDimitry Andric return CurIndex; 400b57cec5SDimitry Andric 410b57cec5SDimitry Andric // Given a struct type, recursively traverse the elements. 420b57cec5SDimitry Andric if (StructType *STy = dyn_cast<StructType>(Ty)) { 43fe6060f1SDimitry Andric for (auto I : llvm::enumerate(STy->elements())) { 44fe6060f1SDimitry Andric Type *ET = I.value(); 45fe6060f1SDimitry Andric if (Indices && *Indices == I.index()) 46fe6060f1SDimitry Andric return ComputeLinearIndex(ET, Indices + 1, IndicesEnd, CurIndex); 47fe6060f1SDimitry Andric CurIndex = ComputeLinearIndex(ET, nullptr, nullptr, CurIndex); 480b57cec5SDimitry Andric } 490b57cec5SDimitry Andric assert(!Indices && "Unexpected out of bound"); 500b57cec5SDimitry Andric return CurIndex; 510b57cec5SDimitry Andric } 520b57cec5SDimitry Andric // Given an array type, recursively traverse the elements. 530b57cec5SDimitry Andric else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 540b57cec5SDimitry Andric Type *EltTy = ATy->getElementType(); 550b57cec5SDimitry Andric unsigned NumElts = ATy->getNumElements(); 560b57cec5SDimitry Andric // Compute the Linear offset when jumping one element of the array 570b57cec5SDimitry Andric unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0); 580b57cec5SDimitry Andric if (Indices) { 590b57cec5SDimitry Andric assert(*Indices < NumElts && "Unexpected out of bound"); 600b57cec5SDimitry Andric // If the indice is inside the array, compute the index to the requested 610b57cec5SDimitry Andric // elt and recurse inside the element with the end of the indices list 620b57cec5SDimitry Andric CurIndex += EltLinearOffset* *Indices; 630b57cec5SDimitry Andric return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex); 640b57cec5SDimitry Andric } 650b57cec5SDimitry Andric CurIndex += EltLinearOffset*NumElts; 660b57cec5SDimitry Andric return CurIndex; 670b57cec5SDimitry Andric } 680b57cec5SDimitry Andric // We haven't found the type we're looking for, so keep searching. 690b57cec5SDimitry Andric return CurIndex + 1; 700b57cec5SDimitry Andric } 710b57cec5SDimitry Andric 720b57cec5SDimitry Andric /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of 730b57cec5SDimitry Andric /// EVTs that represent all the individual underlying 740b57cec5SDimitry Andric /// non-aggregate types that comprise it. 750b57cec5SDimitry Andric /// 760b57cec5SDimitry Andric /// If Offsets is non-null, it points to a vector to be filled in 770b57cec5SDimitry Andric /// with the in-memory offsets of each of the individual values. 780b57cec5SDimitry Andric /// 790b57cec5SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, 800b57cec5SDimitry Andric Type *Ty, SmallVectorImpl<EVT> &ValueVTs, 810b57cec5SDimitry Andric SmallVectorImpl<EVT> *MemVTs, 8206c3fb27SDimitry Andric SmallVectorImpl<TypeSize> *Offsets, 8306c3fb27SDimitry Andric TypeSize StartingOffset) { 84*0fca6ea1SDimitry Andric assert((Ty->isScalableTy() == StartingOffset.isScalable() || 85*0fca6ea1SDimitry Andric StartingOffset.isZero()) && 86*0fca6ea1SDimitry Andric "Offset/TypeSize mismatch!"); 870b57cec5SDimitry Andric // Given a struct type, recursively traverse the elements. 880b57cec5SDimitry Andric if (StructType *STy = dyn_cast<StructType>(Ty)) { 89e8d8bef9SDimitry Andric // If the Offsets aren't needed, don't query the struct layout. This allows 90e8d8bef9SDimitry Andric // us to support structs with scalable vectors for operations that don't 91e8d8bef9SDimitry Andric // need offsets. 92e8d8bef9SDimitry 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(); 96e8d8bef9SDimitry Andric EI != EE; ++EI) { 97e8d8bef9SDimitry Andric // Don't compute the element offset if we didn't get a StructLayout above. 98*0fca6ea1SDimitry Andric TypeSize EltOffset = 99*0fca6ea1SDimitry Andric SL ? SL->getElementOffset(EI - EB) : TypeSize::getZero(); 1000b57cec5SDimitry Andric ComputeValueVTs(TLI, DL, *EI, ValueVTs, MemVTs, Offsets, 101e8d8bef9SDimitry Andric StartingOffset + EltOffset); 102e8d8bef9SDimitry Andric } 1030b57cec5SDimitry Andric return; 1040b57cec5SDimitry Andric } 1050b57cec5SDimitry Andric // Given an array type, recursively traverse the elements. 1060b57cec5SDimitry Andric if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1070b57cec5SDimitry Andric Type *EltTy = ATy->getElementType(); 10806c3fb27SDimitry Andric TypeSize EltSize = DL.getTypeAllocSize(EltTy); 1090b57cec5SDimitry Andric for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) 1100b57cec5SDimitry Andric ComputeValueVTs(TLI, DL, EltTy, ValueVTs, MemVTs, Offsets, 1110b57cec5SDimitry Andric StartingOffset + i * EltSize); 1120b57cec5SDimitry Andric return; 1130b57cec5SDimitry Andric } 1140b57cec5SDimitry Andric // Interpret void as zero return values. 1150b57cec5SDimitry Andric if (Ty->isVoidTy()) 1160b57cec5SDimitry Andric return; 1170b57cec5SDimitry Andric // Base case: we can get an EVT for this LLVM IR type. 1180b57cec5SDimitry Andric ValueVTs.push_back(TLI.getValueType(DL, Ty)); 1190b57cec5SDimitry Andric if (MemVTs) 1200b57cec5SDimitry Andric MemVTs->push_back(TLI.getMemValueType(DL, Ty)); 1210b57cec5SDimitry Andric if (Offsets) 1220b57cec5SDimitry Andric Offsets->push_back(StartingOffset); 1230b57cec5SDimitry Andric } 1240b57cec5SDimitry Andric 1250b57cec5SDimitry Andric void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, 1260b57cec5SDimitry Andric Type *Ty, SmallVectorImpl<EVT> &ValueVTs, 12706c3fb27SDimitry Andric SmallVectorImpl<EVT> *MemVTs, 12806c3fb27SDimitry Andric SmallVectorImpl<uint64_t> *FixedOffsets, 12906c3fb27SDimitry Andric uint64_t StartingOffset) { 130*0fca6ea1SDimitry Andric TypeSize Offset = TypeSize::getFixed(StartingOffset); 1315f757f3fSDimitry Andric if (FixedOffsets) { 13206c3fb27SDimitry Andric SmallVector<TypeSize, 4> Offsets; 13306c3fb27SDimitry Andric ComputeValueVTs(TLI, DL, Ty, ValueVTs, MemVTs, &Offsets, Offset); 13406c3fb27SDimitry Andric for (TypeSize Offset : Offsets) 1355f757f3fSDimitry Andric FixedOffsets->push_back(Offset.getFixedValue()); 1365f757f3fSDimitry Andric } else { 1375f757f3fSDimitry Andric ComputeValueVTs(TLI, DL, Ty, ValueVTs, MemVTs, nullptr, Offset); 1385f757f3fSDimitry Andric } 13906c3fb27SDimitry Andric } 14006c3fb27SDimitry Andric 1410b57cec5SDimitry Andric void llvm::computeValueLLTs(const DataLayout &DL, Type &Ty, 1420b57cec5SDimitry Andric SmallVectorImpl<LLT> &ValueTys, 1430b57cec5SDimitry Andric SmallVectorImpl<uint64_t> *Offsets, 1440b57cec5SDimitry Andric uint64_t StartingOffset) { 1450b57cec5SDimitry Andric // Given a struct type, recursively traverse the elements. 1460b57cec5SDimitry Andric if (StructType *STy = dyn_cast<StructType>(&Ty)) { 147e8d8bef9SDimitry Andric // If the Offsets aren't needed, don't query the struct layout. This allows 148e8d8bef9SDimitry Andric // us to support structs with scalable vectors for operations that don't 149e8d8bef9SDimitry Andric // need offsets. 150e8d8bef9SDimitry Andric const StructLayout *SL = Offsets ? DL.getStructLayout(STy) : nullptr; 151e8d8bef9SDimitry Andric for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) { 152e8d8bef9SDimitry Andric uint64_t EltOffset = SL ? SL->getElementOffset(I) : 0; 1530b57cec5SDimitry Andric computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets, 154e8d8bef9SDimitry Andric StartingOffset + EltOffset); 155e8d8bef9SDimitry Andric } 1560b57cec5SDimitry Andric return; 1570b57cec5SDimitry Andric } 1580b57cec5SDimitry Andric // Given an array type, recursively traverse the elements. 1590b57cec5SDimitry Andric if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) { 1600b57cec5SDimitry Andric Type *EltTy = ATy->getElementType(); 161e8d8bef9SDimitry Andric uint64_t EltSize = DL.getTypeAllocSize(EltTy).getFixedValue(); 1620b57cec5SDimitry Andric for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) 1630b57cec5SDimitry Andric computeValueLLTs(DL, *EltTy, ValueTys, Offsets, 1640b57cec5SDimitry Andric StartingOffset + i * EltSize); 1650b57cec5SDimitry Andric return; 1660b57cec5SDimitry Andric } 1670b57cec5SDimitry Andric // Interpret void as zero return values. 1680b57cec5SDimitry Andric if (Ty.isVoidTy()) 1690b57cec5SDimitry Andric return; 1700b57cec5SDimitry Andric // Base case: we can get an LLT for this LLVM IR type. 1710b57cec5SDimitry Andric ValueTys.push_back(getLLTForType(Ty, DL)); 1720b57cec5SDimitry Andric if (Offsets != nullptr) 1730b57cec5SDimitry Andric Offsets->push_back(StartingOffset * 8); 1740b57cec5SDimitry Andric } 1750b57cec5SDimitry Andric 1760b57cec5SDimitry Andric /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V. 1770b57cec5SDimitry Andric GlobalValue *llvm::ExtractTypeInfo(Value *V) { 1780b57cec5SDimitry Andric V = V->stripPointerCasts(); 1790b57cec5SDimitry Andric GlobalValue *GV = dyn_cast<GlobalValue>(V); 1800b57cec5SDimitry Andric GlobalVariable *Var = dyn_cast<GlobalVariable>(V); 1810b57cec5SDimitry Andric 1820b57cec5SDimitry Andric if (Var && Var->getName() == "llvm.eh.catch.all.value") { 1830b57cec5SDimitry Andric assert(Var->hasInitializer() && 1840b57cec5SDimitry Andric "The EH catch-all value must have an initializer"); 1850b57cec5SDimitry Andric Value *Init = Var->getInitializer(); 1860b57cec5SDimitry Andric GV = dyn_cast<GlobalValue>(Init); 1870b57cec5SDimitry Andric if (!GV) V = cast<ConstantPointerNull>(Init); 1880b57cec5SDimitry Andric } 1890b57cec5SDimitry Andric 1900b57cec5SDimitry Andric assert((GV || isa<ConstantPointerNull>(V)) && 1910b57cec5SDimitry Andric "TypeInfo must be a global variable or NULL"); 1920b57cec5SDimitry Andric return GV; 1930b57cec5SDimitry Andric } 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric /// getFCmpCondCode - Return the ISD condition code corresponding to 1960b57cec5SDimitry Andric /// the given LLVM IR floating-point condition code. This includes 1970b57cec5SDimitry Andric /// consideration of global floating-point math flags. 1980b57cec5SDimitry Andric /// 1990b57cec5SDimitry Andric ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) { 2000b57cec5SDimitry Andric switch (Pred) { 2010b57cec5SDimitry Andric case FCmpInst::FCMP_FALSE: return ISD::SETFALSE; 2020b57cec5SDimitry Andric case FCmpInst::FCMP_OEQ: return ISD::SETOEQ; 2030b57cec5SDimitry Andric case FCmpInst::FCMP_OGT: return ISD::SETOGT; 2040b57cec5SDimitry Andric case FCmpInst::FCMP_OGE: return ISD::SETOGE; 2050b57cec5SDimitry Andric case FCmpInst::FCMP_OLT: return ISD::SETOLT; 2060b57cec5SDimitry Andric case FCmpInst::FCMP_OLE: return ISD::SETOLE; 2070b57cec5SDimitry Andric case FCmpInst::FCMP_ONE: return ISD::SETONE; 2080b57cec5SDimitry Andric case FCmpInst::FCMP_ORD: return ISD::SETO; 2090b57cec5SDimitry Andric case FCmpInst::FCMP_UNO: return ISD::SETUO; 2100b57cec5SDimitry Andric case FCmpInst::FCMP_UEQ: return ISD::SETUEQ; 2110b57cec5SDimitry Andric case FCmpInst::FCMP_UGT: return ISD::SETUGT; 2120b57cec5SDimitry Andric case FCmpInst::FCMP_UGE: return ISD::SETUGE; 2130b57cec5SDimitry Andric case FCmpInst::FCMP_ULT: return ISD::SETULT; 2140b57cec5SDimitry Andric case FCmpInst::FCMP_ULE: return ISD::SETULE; 2150b57cec5SDimitry Andric case FCmpInst::FCMP_UNE: return ISD::SETUNE; 2160b57cec5SDimitry Andric case FCmpInst::FCMP_TRUE: return ISD::SETTRUE; 2170b57cec5SDimitry Andric default: llvm_unreachable("Invalid FCmp predicate opcode!"); 2180b57cec5SDimitry Andric } 2190b57cec5SDimitry Andric } 2200b57cec5SDimitry Andric 2210b57cec5SDimitry Andric ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) { 2220b57cec5SDimitry Andric switch (CC) { 2230b57cec5SDimitry Andric case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ; 2240b57cec5SDimitry Andric case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE; 2250b57cec5SDimitry Andric case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT; 2260b57cec5SDimitry Andric case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE; 2270b57cec5SDimitry Andric case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT; 2280b57cec5SDimitry Andric case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE; 2290b57cec5SDimitry Andric default: return CC; 2300b57cec5SDimitry Andric } 2310b57cec5SDimitry Andric } 2320b57cec5SDimitry Andric 2330b57cec5SDimitry Andric ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) { 2340b57cec5SDimitry Andric switch (Pred) { 2350b57cec5SDimitry Andric case ICmpInst::ICMP_EQ: return ISD::SETEQ; 2360b57cec5SDimitry Andric case ICmpInst::ICMP_NE: return ISD::SETNE; 2370b57cec5SDimitry Andric case ICmpInst::ICMP_SLE: return ISD::SETLE; 2380b57cec5SDimitry Andric case ICmpInst::ICMP_ULE: return ISD::SETULE; 2390b57cec5SDimitry Andric case ICmpInst::ICMP_SGE: return ISD::SETGE; 2400b57cec5SDimitry Andric case ICmpInst::ICMP_UGE: return ISD::SETUGE; 2410b57cec5SDimitry Andric case ICmpInst::ICMP_SLT: return ISD::SETLT; 2420b57cec5SDimitry Andric case ICmpInst::ICMP_ULT: return ISD::SETULT; 2430b57cec5SDimitry Andric case ICmpInst::ICMP_SGT: return ISD::SETGT; 2440b57cec5SDimitry Andric case ICmpInst::ICMP_UGT: return ISD::SETUGT; 2450b57cec5SDimitry Andric default: 2460b57cec5SDimitry Andric llvm_unreachable("Invalid ICmp predicate opcode!"); 2470b57cec5SDimitry Andric } 2480b57cec5SDimitry Andric } 2490b57cec5SDimitry Andric 250349cc55cSDimitry Andric ICmpInst::Predicate llvm::getICmpCondCode(ISD::CondCode Pred) { 251349cc55cSDimitry Andric switch (Pred) { 252349cc55cSDimitry Andric case ISD::SETEQ: 253349cc55cSDimitry Andric return ICmpInst::ICMP_EQ; 254349cc55cSDimitry Andric case ISD::SETNE: 255349cc55cSDimitry Andric return ICmpInst::ICMP_NE; 256349cc55cSDimitry Andric case ISD::SETLE: 257349cc55cSDimitry Andric return ICmpInst::ICMP_SLE; 258349cc55cSDimitry Andric case ISD::SETULE: 259349cc55cSDimitry Andric return ICmpInst::ICMP_ULE; 260349cc55cSDimitry Andric case ISD::SETGE: 261349cc55cSDimitry Andric return ICmpInst::ICMP_SGE; 262349cc55cSDimitry Andric case ISD::SETUGE: 263349cc55cSDimitry Andric return ICmpInst::ICMP_UGE; 264349cc55cSDimitry Andric case ISD::SETLT: 265349cc55cSDimitry Andric return ICmpInst::ICMP_SLT; 266349cc55cSDimitry Andric case ISD::SETULT: 267349cc55cSDimitry Andric return ICmpInst::ICMP_ULT; 268349cc55cSDimitry Andric case ISD::SETGT: 269349cc55cSDimitry Andric return ICmpInst::ICMP_SGT; 270349cc55cSDimitry Andric case ISD::SETUGT: 271349cc55cSDimitry Andric return ICmpInst::ICMP_UGT; 272349cc55cSDimitry Andric default: 273349cc55cSDimitry Andric llvm_unreachable("Invalid ISD integer condition code!"); 274349cc55cSDimitry Andric } 275349cc55cSDimitry Andric } 276349cc55cSDimitry Andric 2770b57cec5SDimitry Andric static bool isNoopBitcast(Type *T1, Type *T2, 2780b57cec5SDimitry Andric const TargetLoweringBase& TLI) { 2790b57cec5SDimitry Andric return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) || 2800b57cec5SDimitry Andric (isa<VectorType>(T1) && isa<VectorType>(T2) && 2810b57cec5SDimitry Andric TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2))); 2820b57cec5SDimitry Andric } 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric /// Look through operations that will be free to find the earliest source of 2850b57cec5SDimitry Andric /// this value. 2860b57cec5SDimitry Andric /// 287480093f4SDimitry Andric /// @param ValLoc If V has aggregate type, we will be interested in a particular 2880b57cec5SDimitry Andric /// scalar component. This records its address; the reverse of this list gives a 2890b57cec5SDimitry Andric /// sequence of indices appropriate for an extractvalue to locate the important 2900b57cec5SDimitry Andric /// value. This value is updated during the function and on exit will indicate 2910b57cec5SDimitry Andric /// similar information for the Value returned. 2920b57cec5SDimitry Andric /// 2930b57cec5SDimitry Andric /// @param DataBits If this function looks through truncate instructions, this 2940b57cec5SDimitry Andric /// will record the smallest size attained. 2950b57cec5SDimitry Andric static const Value *getNoopInput(const Value *V, 2960b57cec5SDimitry Andric SmallVectorImpl<unsigned> &ValLoc, 2970b57cec5SDimitry Andric unsigned &DataBits, 2980b57cec5SDimitry Andric const TargetLoweringBase &TLI, 2990b57cec5SDimitry Andric const DataLayout &DL) { 3000b57cec5SDimitry Andric while (true) { 3010b57cec5SDimitry Andric // Try to look through V1; if V1 is not an instruction, it can't be looked 3020b57cec5SDimitry Andric // through. 3030b57cec5SDimitry Andric const Instruction *I = dyn_cast<Instruction>(V); 3040b57cec5SDimitry Andric if (!I || I->getNumOperands() == 0) return V; 3050b57cec5SDimitry Andric const Value *NoopInput = nullptr; 3060b57cec5SDimitry Andric 3070b57cec5SDimitry Andric Value *Op = I->getOperand(0); 3080b57cec5SDimitry Andric if (isa<BitCastInst>(I)) { 3090b57cec5SDimitry Andric // Look through truly no-op bitcasts. 3100b57cec5SDimitry Andric if (isNoopBitcast(Op->getType(), I->getType(), TLI)) 3110b57cec5SDimitry Andric NoopInput = Op; 3120b57cec5SDimitry Andric } else if (isa<GetElementPtrInst>(I)) { 3130b57cec5SDimitry Andric // Look through getelementptr 3140b57cec5SDimitry Andric if (cast<GetElementPtrInst>(I)->hasAllZeroIndices()) 3150b57cec5SDimitry Andric NoopInput = Op; 3160b57cec5SDimitry Andric } else if (isa<IntToPtrInst>(I)) { 3170b57cec5SDimitry Andric // Look through inttoptr. 3180b57cec5SDimitry Andric // Make sure this isn't a truncating or extending cast. We could 3190b57cec5SDimitry Andric // support this eventually, but don't bother for now. 3200b57cec5SDimitry Andric if (!isa<VectorType>(I->getType()) && 3210b57cec5SDimitry Andric DL.getPointerSizeInBits() == 3220b57cec5SDimitry Andric cast<IntegerType>(Op->getType())->getBitWidth()) 3230b57cec5SDimitry Andric NoopInput = Op; 3240b57cec5SDimitry Andric } else if (isa<PtrToIntInst>(I)) { 3250b57cec5SDimitry Andric // Look through ptrtoint. 3260b57cec5SDimitry Andric // Make sure this isn't a truncating or extending cast. We could 3270b57cec5SDimitry Andric // support this eventually, but don't bother for now. 3280b57cec5SDimitry Andric if (!isa<VectorType>(I->getType()) && 3290b57cec5SDimitry Andric DL.getPointerSizeInBits() == 3300b57cec5SDimitry Andric cast<IntegerType>(I->getType())->getBitWidth()) 3310b57cec5SDimitry Andric NoopInput = Op; 3320b57cec5SDimitry Andric } else if (isa<TruncInst>(I) && 3330b57cec5SDimitry Andric TLI.allowTruncateForTailCall(Op->getType(), I->getType())) { 334bdd1243dSDimitry Andric DataBits = 335bdd1243dSDimitry Andric std::min((uint64_t)DataBits, 336bdd1243dSDimitry Andric I->getType()->getPrimitiveSizeInBits().getFixedValue()); 3370b57cec5SDimitry Andric NoopInput = Op; 3385ffd83dbSDimitry Andric } else if (auto *CB = dyn_cast<CallBase>(I)) { 3395ffd83dbSDimitry Andric const Value *ReturnedOp = CB->getReturnedArgOperand(); 3400b57cec5SDimitry Andric if (ReturnedOp && isNoopBitcast(ReturnedOp->getType(), I->getType(), TLI)) 3410b57cec5SDimitry Andric NoopInput = ReturnedOp; 3420b57cec5SDimitry Andric } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) { 3430b57cec5SDimitry Andric // Value may come from either the aggregate or the scalar 3440b57cec5SDimitry Andric ArrayRef<unsigned> InsertLoc = IVI->getIndices(); 3450b57cec5SDimitry Andric if (ValLoc.size() >= InsertLoc.size() && 3460b57cec5SDimitry Andric std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) { 3470b57cec5SDimitry Andric // The type being inserted is a nested sub-type of the aggregate; we 3480b57cec5SDimitry Andric // have to remove those initial indices to get the location we're 3490b57cec5SDimitry Andric // interested in for the operand. 3500b57cec5SDimitry Andric ValLoc.resize(ValLoc.size() - InsertLoc.size()); 3510b57cec5SDimitry Andric NoopInput = IVI->getInsertedValueOperand(); 3520b57cec5SDimitry Andric } else { 3530b57cec5SDimitry Andric // The struct we're inserting into has the value we're interested in, no 3540b57cec5SDimitry Andric // change of address. 3550b57cec5SDimitry Andric NoopInput = Op; 3560b57cec5SDimitry Andric } 3570b57cec5SDimitry Andric } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) { 3580b57cec5SDimitry Andric // The part we're interested in will inevitably be some sub-section of the 3590b57cec5SDimitry Andric // previous aggregate. Combine the two paths to obtain the true address of 3600b57cec5SDimitry Andric // our element. 3610b57cec5SDimitry Andric ArrayRef<unsigned> ExtractLoc = EVI->getIndices(); 3620b57cec5SDimitry Andric ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend()); 3630b57cec5SDimitry Andric NoopInput = Op; 3640b57cec5SDimitry Andric } 3650b57cec5SDimitry Andric // Terminate if we couldn't find anything to look through. 3660b57cec5SDimitry Andric if (!NoopInput) 3670b57cec5SDimitry Andric return V; 3680b57cec5SDimitry Andric 3690b57cec5SDimitry Andric V = NoopInput; 3700b57cec5SDimitry Andric } 3710b57cec5SDimitry Andric } 3720b57cec5SDimitry Andric 3730b57cec5SDimitry Andric /// Return true if this scalar return value only has bits discarded on its path 3740b57cec5SDimitry Andric /// from the "tail call" to the "ret". This includes the obvious noop 3750b57cec5SDimitry Andric /// instructions handled by getNoopInput above as well as free truncations (or 3760b57cec5SDimitry Andric /// extensions prior to the call). 3770b57cec5SDimitry Andric static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal, 3780b57cec5SDimitry Andric SmallVectorImpl<unsigned> &RetIndices, 3790b57cec5SDimitry Andric SmallVectorImpl<unsigned> &CallIndices, 3800b57cec5SDimitry Andric bool AllowDifferingSizes, 3810b57cec5SDimitry Andric const TargetLoweringBase &TLI, 3820b57cec5SDimitry Andric const DataLayout &DL) { 3830b57cec5SDimitry Andric 3840b57cec5SDimitry Andric // Trace the sub-value needed by the return value as far back up the graph as 3850b57cec5SDimitry Andric // possible, in the hope that it will intersect with the value produced by the 3860b57cec5SDimitry Andric // call. In the simple case with no "returned" attribute, the hope is actually 3870b57cec5SDimitry Andric // that we end up back at the tail call instruction itself. 3880b57cec5SDimitry Andric unsigned BitsRequired = UINT_MAX; 3890b57cec5SDimitry Andric RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL); 3900b57cec5SDimitry Andric 3910b57cec5SDimitry Andric // If this slot in the value returned is undef, it doesn't matter what the 3920b57cec5SDimitry Andric // call puts there, it'll be fine. 3930b57cec5SDimitry Andric if (isa<UndefValue>(RetVal)) 3940b57cec5SDimitry Andric return true; 3950b57cec5SDimitry Andric 3960b57cec5SDimitry Andric // Now do a similar search up through the graph to find where the value 3970b57cec5SDimitry Andric // actually returned by the "tail call" comes from. In the simple case without 3980b57cec5SDimitry Andric // a "returned" attribute, the search will be blocked immediately and the loop 3990b57cec5SDimitry Andric // a Noop. 4000b57cec5SDimitry Andric unsigned BitsProvided = UINT_MAX; 4010b57cec5SDimitry Andric CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL); 4020b57cec5SDimitry Andric 4030b57cec5SDimitry Andric // There's no hope if we can't actually trace them to (the same part of!) the 4040b57cec5SDimitry Andric // same value. 4050b57cec5SDimitry Andric if (CallVal != RetVal || CallIndices != RetIndices) 4060b57cec5SDimitry Andric return false; 4070b57cec5SDimitry Andric 4080b57cec5SDimitry Andric // However, intervening truncates may have made the call non-tail. Make sure 4090b57cec5SDimitry Andric // all the bits that are needed by the "ret" have been provided by the "tail 4100b57cec5SDimitry Andric // call". FIXME: with sufficiently cunning bit-tracking, we could look through 4110b57cec5SDimitry Andric // extensions too. 4120b57cec5SDimitry Andric if (BitsProvided < BitsRequired || 4130b57cec5SDimitry Andric (!AllowDifferingSizes && BitsProvided != BitsRequired)) 4140b57cec5SDimitry Andric return false; 4150b57cec5SDimitry Andric 4160b57cec5SDimitry Andric return true; 4170b57cec5SDimitry Andric } 4180b57cec5SDimitry Andric 4190b57cec5SDimitry Andric /// For an aggregate type, determine whether a given index is within bounds or 4200b57cec5SDimitry Andric /// not. 4215ffd83dbSDimitry Andric static bool indexReallyValid(Type *T, unsigned Idx) { 4220b57cec5SDimitry Andric if (ArrayType *AT = dyn_cast<ArrayType>(T)) 4230b57cec5SDimitry Andric return Idx < AT->getNumElements(); 4240b57cec5SDimitry Andric 4250b57cec5SDimitry Andric return Idx < cast<StructType>(T)->getNumElements(); 4260b57cec5SDimitry Andric } 4270b57cec5SDimitry Andric 4280b57cec5SDimitry Andric /// Move the given iterators to the next leaf type in depth first traversal. 4290b57cec5SDimitry Andric /// 4300b57cec5SDimitry Andric /// Performs a depth-first traversal of the type as specified by its arguments, 4310b57cec5SDimitry Andric /// stopping at the next leaf node (which may be a legitimate scalar type or an 4320b57cec5SDimitry Andric /// empty struct or array). 4330b57cec5SDimitry Andric /// 4340b57cec5SDimitry Andric /// @param SubTypes List of the partial components making up the type from 4350b57cec5SDimitry Andric /// outermost to innermost non-empty aggregate. The element currently 4360b57cec5SDimitry Andric /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1). 4370b57cec5SDimitry Andric /// 4380b57cec5SDimitry Andric /// @param Path Set of extractvalue indices leading from the outermost type 4390b57cec5SDimitry Andric /// (SubTypes[0]) to the leaf node currently represented. 4400b57cec5SDimitry Andric /// 4410b57cec5SDimitry Andric /// @returns true if a new type was found, false otherwise. Calling this 4420b57cec5SDimitry Andric /// function again on a finished iterator will repeatedly return 4430b57cec5SDimitry Andric /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty 4440b57cec5SDimitry Andric /// aggregate or a non-aggregate 4455ffd83dbSDimitry Andric static bool advanceToNextLeafType(SmallVectorImpl<Type *> &SubTypes, 4460b57cec5SDimitry Andric SmallVectorImpl<unsigned> &Path) { 4470b57cec5SDimitry Andric // First march back up the tree until we can successfully increment one of the 4480b57cec5SDimitry Andric // coordinates in Path. 4490b57cec5SDimitry Andric while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) { 4500b57cec5SDimitry Andric Path.pop_back(); 4510b57cec5SDimitry Andric SubTypes.pop_back(); 4520b57cec5SDimitry Andric } 4530b57cec5SDimitry Andric 4540b57cec5SDimitry Andric // If we reached the top, then the iterator is done. 4550b57cec5SDimitry Andric if (Path.empty()) 4560b57cec5SDimitry Andric return false; 4570b57cec5SDimitry Andric 4580b57cec5SDimitry Andric // We know there's *some* valid leaf now, so march back down the tree picking 4590b57cec5SDimitry Andric // out the left-most element at each node. 4600b57cec5SDimitry Andric ++Path.back(); 4615ffd83dbSDimitry Andric Type *DeeperType = 4625ffd83dbSDimitry Andric ExtractValueInst::getIndexedType(SubTypes.back(), Path.back()); 4630b57cec5SDimitry Andric while (DeeperType->isAggregateType()) { 4645ffd83dbSDimitry Andric if (!indexReallyValid(DeeperType, 0)) 4650b57cec5SDimitry Andric return true; 4660b57cec5SDimitry Andric 4675ffd83dbSDimitry Andric SubTypes.push_back(DeeperType); 4680b57cec5SDimitry Andric Path.push_back(0); 4690b57cec5SDimitry Andric 4705ffd83dbSDimitry Andric DeeperType = ExtractValueInst::getIndexedType(DeeperType, 0); 4710b57cec5SDimitry Andric } 4720b57cec5SDimitry Andric 4730b57cec5SDimitry Andric return true; 4740b57cec5SDimitry Andric } 4750b57cec5SDimitry Andric 4760b57cec5SDimitry Andric /// Find the first non-empty, scalar-like type in Next and setup the iterator 4770b57cec5SDimitry Andric /// components. 4780b57cec5SDimitry Andric /// 4790b57cec5SDimitry Andric /// Assuming Next is an aggregate of some kind, this function will traverse the 4800b57cec5SDimitry Andric /// tree from left to right (i.e. depth-first) looking for the first 4810b57cec5SDimitry Andric /// non-aggregate type which will play a role in function return. 4820b57cec5SDimitry Andric /// 4830b57cec5SDimitry Andric /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup 4840b57cec5SDimitry Andric /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first 4850b57cec5SDimitry Andric /// i32 in that type. 4865ffd83dbSDimitry Andric static bool firstRealType(Type *Next, SmallVectorImpl<Type *> &SubTypes, 4870b57cec5SDimitry Andric SmallVectorImpl<unsigned> &Path) { 4880b57cec5SDimitry Andric // First initialise the iterator components to the first "leaf" node 4890b57cec5SDimitry Andric // (i.e. node with no valid sub-type at any index, so {} does count as a leaf 4900b57cec5SDimitry Andric // despite nominally being an aggregate). 4915ffd83dbSDimitry Andric while (Type *FirstInner = ExtractValueInst::getIndexedType(Next, 0)) { 4925ffd83dbSDimitry Andric SubTypes.push_back(Next); 4930b57cec5SDimitry Andric Path.push_back(0); 4945ffd83dbSDimitry Andric Next = FirstInner; 4950b57cec5SDimitry Andric } 4960b57cec5SDimitry Andric 4970b57cec5SDimitry Andric // If there's no Path now, Next was originally scalar already (or empty 4980b57cec5SDimitry Andric // leaf). We're done. 4990b57cec5SDimitry Andric if (Path.empty()) 5000b57cec5SDimitry Andric return true; 5010b57cec5SDimitry Andric 5020b57cec5SDimitry Andric // Otherwise, use normal iteration to keep looking through the tree until we 5030b57cec5SDimitry Andric // find a non-aggregate type. 5045ffd83dbSDimitry Andric while (ExtractValueInst::getIndexedType(SubTypes.back(), Path.back()) 5055ffd83dbSDimitry Andric ->isAggregateType()) { 5060b57cec5SDimitry Andric if (!advanceToNextLeafType(SubTypes, Path)) 5070b57cec5SDimitry Andric return false; 5080b57cec5SDimitry Andric } 5090b57cec5SDimitry Andric 5100b57cec5SDimitry Andric return true; 5110b57cec5SDimitry Andric } 5120b57cec5SDimitry Andric 5130b57cec5SDimitry Andric /// Set the iterator data-structures to the next non-empty, non-aggregate 5140b57cec5SDimitry Andric /// subtype. 5155ffd83dbSDimitry Andric static bool nextRealType(SmallVectorImpl<Type *> &SubTypes, 5160b57cec5SDimitry Andric SmallVectorImpl<unsigned> &Path) { 5170b57cec5SDimitry Andric do { 5180b57cec5SDimitry Andric if (!advanceToNextLeafType(SubTypes, Path)) 5190b57cec5SDimitry Andric return false; 5200b57cec5SDimitry Andric 5210b57cec5SDimitry Andric assert(!Path.empty() && "found a leaf but didn't set the path?"); 5225ffd83dbSDimitry Andric } while (ExtractValueInst::getIndexedType(SubTypes.back(), Path.back()) 5235ffd83dbSDimitry Andric ->isAggregateType()); 5240b57cec5SDimitry Andric 5250b57cec5SDimitry Andric return true; 5260b57cec5SDimitry Andric } 5270b57cec5SDimitry Andric 5280b57cec5SDimitry Andric 5290b57cec5SDimitry Andric /// Test if the given instruction is in a position to be optimized 5300b57cec5SDimitry Andric /// with a tail-call. This roughly means that it's in a block with 5310b57cec5SDimitry Andric /// a return and there's nothing that needs to be scheduled 5320b57cec5SDimitry Andric /// between it and the return. 5330b57cec5SDimitry Andric /// 5340b57cec5SDimitry Andric /// This function only tests target-independent requirements. 535*0fca6ea1SDimitry Andric bool llvm::isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, 536*0fca6ea1SDimitry Andric bool ReturnsFirstArg) { 5375ffd83dbSDimitry Andric const BasicBlock *ExitBB = Call.getParent(); 5380b57cec5SDimitry Andric const Instruction *Term = ExitBB->getTerminator(); 5390b57cec5SDimitry Andric const ReturnInst *Ret = dyn_cast<ReturnInst>(Term); 5400b57cec5SDimitry Andric 5410b57cec5SDimitry Andric // The block must end in a return statement or unreachable. 5420b57cec5SDimitry Andric // 5430b57cec5SDimitry Andric // FIXME: Decline tailcall if it's not guaranteed and if the block ends in 5440b57cec5SDimitry Andric // an unreachable, for now. The way tailcall optimization is currently 5450b57cec5SDimitry Andric // implemented means it will add an epilogue followed by a jump. That is 5460b57cec5SDimitry Andric // not profitable. Also, if the callee is a special function (e.g. 5470b57cec5SDimitry Andric // longjmp on x86), it can end up causing miscompilation that has not 5480b57cec5SDimitry Andric // been fully understood. 549fe6060f1SDimitry Andric if (!Ret && ((!TM.Options.GuaranteedTailCallOpt && 550fe6060f1SDimitry Andric Call.getCallingConv() != CallingConv::Tail && 551fe6060f1SDimitry Andric Call.getCallingConv() != CallingConv::SwiftTail) || 552fe6060f1SDimitry Andric !isa<UnreachableInst>(Term))) 5530b57cec5SDimitry Andric return false; 5540b57cec5SDimitry Andric 5550b57cec5SDimitry Andric // If I will have a chain, make sure no other instruction that will have a 5560b57cec5SDimitry Andric // chain interposes between I and the return. 5575ffd83dbSDimitry Andric // Check for all calls including speculatable functions. 5580b57cec5SDimitry Andric for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) { 5595ffd83dbSDimitry Andric if (&*BBI == &Call) 5600b57cec5SDimitry Andric break; 5610b57cec5SDimitry Andric // Debug info intrinsics do not get in the way of tail call optimization. 562e8d8bef9SDimitry Andric // Pseudo probe intrinsics do not block tail call optimization either. 563349cc55cSDimitry Andric if (BBI->isDebugOrPseudoInst()) 564e8d8bef9SDimitry Andric continue; 565e8d8bef9SDimitry Andric // A lifetime end, assume or noalias.decl intrinsic should not stop tail 566e8d8bef9SDimitry Andric // call optimization. 5670b57cec5SDimitry Andric if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI)) 5688bcb0991SDimitry Andric if (II->getIntrinsicID() == Intrinsic::lifetime_end || 569e8d8bef9SDimitry Andric II->getIntrinsicID() == Intrinsic::assume || 570e8d8bef9SDimitry Andric II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl) 5710b57cec5SDimitry Andric continue; 5720b57cec5SDimitry Andric if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() || 5730b57cec5SDimitry Andric !isSafeToSpeculativelyExecute(&*BBI)) 5740b57cec5SDimitry Andric return false; 5750b57cec5SDimitry Andric } 5760b57cec5SDimitry Andric 5770b57cec5SDimitry Andric const Function *F = ExitBB->getParent(); 5780b57cec5SDimitry Andric return returnTypeIsEligibleForTailCall( 579*0fca6ea1SDimitry Andric F, &Call, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering(), 580*0fca6ea1SDimitry Andric ReturnsFirstArg); 5810b57cec5SDimitry Andric } 5820b57cec5SDimitry Andric 5830b57cec5SDimitry Andric bool llvm::attributesPermitTailCall(const Function *F, const Instruction *I, 5840b57cec5SDimitry Andric const ReturnInst *Ret, 5850b57cec5SDimitry Andric const TargetLoweringBase &TLI, 5860b57cec5SDimitry Andric bool *AllowDifferingSizes) { 5870b57cec5SDimitry Andric // ADS may be null, so don't write to it directly. 5880b57cec5SDimitry Andric bool DummyADS; 5890b57cec5SDimitry Andric bool &ADS = AllowDifferingSizes ? *AllowDifferingSizes : DummyADS; 5900b57cec5SDimitry Andric ADS = true; 5910b57cec5SDimitry Andric 59204eeddc0SDimitry Andric AttrBuilder CallerAttrs(F->getContext(), F->getAttributes().getRetAttrs()); 59304eeddc0SDimitry Andric AttrBuilder CalleeAttrs(F->getContext(), 59404eeddc0SDimitry Andric cast<CallInst>(I)->getAttributes().getRetAttrs()); 5950b57cec5SDimitry Andric 596480093f4SDimitry Andric // Following attributes are completely benign as far as calling convention 5970b57cec5SDimitry Andric // goes, they shouldn't affect whether the call is a tail call. 598*0fca6ea1SDimitry Andric for (const auto &Attr : 599*0fca6ea1SDimitry Andric {Attribute::Alignment, Attribute::Dereferenceable, 600fe6060f1SDimitry Andric Attribute::DereferenceableOrNull, Attribute::NoAlias, 601*0fca6ea1SDimitry Andric Attribute::NonNull, Attribute::NoUndef, Attribute::Range}) { 602fe6060f1SDimitry Andric CallerAttrs.removeAttribute(Attr); 603fe6060f1SDimitry Andric CalleeAttrs.removeAttribute(Attr); 604fe6060f1SDimitry Andric } 6050b57cec5SDimitry Andric 6060b57cec5SDimitry Andric if (CallerAttrs.contains(Attribute::ZExt)) { 6070b57cec5SDimitry Andric if (!CalleeAttrs.contains(Attribute::ZExt)) 6080b57cec5SDimitry Andric return false; 6090b57cec5SDimitry Andric 6100b57cec5SDimitry Andric ADS = false; 6110b57cec5SDimitry Andric CallerAttrs.removeAttribute(Attribute::ZExt); 6120b57cec5SDimitry Andric CalleeAttrs.removeAttribute(Attribute::ZExt); 6130b57cec5SDimitry Andric } else if (CallerAttrs.contains(Attribute::SExt)) { 6140b57cec5SDimitry Andric if (!CalleeAttrs.contains(Attribute::SExt)) 6150b57cec5SDimitry Andric return false; 6160b57cec5SDimitry Andric 6170b57cec5SDimitry Andric ADS = false; 6180b57cec5SDimitry Andric CallerAttrs.removeAttribute(Attribute::SExt); 6190b57cec5SDimitry Andric CalleeAttrs.removeAttribute(Attribute::SExt); 6200b57cec5SDimitry Andric } 6210b57cec5SDimitry Andric 6220b57cec5SDimitry Andric // Drop sext and zext return attributes if the result is not used. 6230b57cec5SDimitry Andric // This enables tail calls for code like: 6240b57cec5SDimitry Andric // 6250b57cec5SDimitry Andric // define void @caller() { 6260b57cec5SDimitry Andric // entry: 6270b57cec5SDimitry Andric // %unused_result = tail call zeroext i1 @callee() 6280b57cec5SDimitry Andric // br label %retlabel 6290b57cec5SDimitry Andric // retlabel: 6300b57cec5SDimitry Andric // ret void 6310b57cec5SDimitry Andric // } 6320b57cec5SDimitry Andric if (I->use_empty()) { 6330b57cec5SDimitry Andric CalleeAttrs.removeAttribute(Attribute::SExt); 6340b57cec5SDimitry Andric CalleeAttrs.removeAttribute(Attribute::ZExt); 6350b57cec5SDimitry Andric } 6360b57cec5SDimitry Andric 6370b57cec5SDimitry Andric // If they're still different, there's some facet we don't understand 6380b57cec5SDimitry Andric // (currently only "inreg", but in future who knows). It may be OK but the 6390b57cec5SDimitry Andric // only safe option is to reject the tail call. 6400b57cec5SDimitry Andric return CallerAttrs == CalleeAttrs; 6410b57cec5SDimitry Andric } 6420b57cec5SDimitry Andric 6430b57cec5SDimitry Andric bool llvm::returnTypeIsEligibleForTailCall(const Function *F, 6440b57cec5SDimitry Andric const Instruction *I, 6450b57cec5SDimitry Andric const ReturnInst *Ret, 646*0fca6ea1SDimitry Andric const TargetLoweringBase &TLI, 647*0fca6ea1SDimitry Andric bool ReturnsFirstArg) { 6480b57cec5SDimitry Andric // If the block ends with a void return or unreachable, it doesn't matter 6490b57cec5SDimitry Andric // what the call's return type is. 6500b57cec5SDimitry Andric if (!Ret || Ret->getNumOperands() == 0) return true; 6510b57cec5SDimitry Andric 6520b57cec5SDimitry Andric // If the return value is undef, it doesn't matter what the call's 6530b57cec5SDimitry Andric // return type is. 6540b57cec5SDimitry Andric if (isa<UndefValue>(Ret->getOperand(0))) return true; 6550b57cec5SDimitry Andric 6560b57cec5SDimitry Andric // Make sure the attributes attached to each return are compatible. 6570b57cec5SDimitry Andric bool AllowDifferingSizes; 6580b57cec5SDimitry Andric if (!attributesPermitTailCall(F, I, Ret, TLI, &AllowDifferingSizes)) 6590b57cec5SDimitry Andric return false; 6600b57cec5SDimitry Andric 661*0fca6ea1SDimitry Andric // If the return value is the first argument of the call. 662*0fca6ea1SDimitry Andric if (ReturnsFirstArg) 6630b57cec5SDimitry Andric return true; 6640b57cec5SDimitry Andric 665*0fca6ea1SDimitry Andric const Value *RetVal = Ret->getOperand(0), *CallVal = I; 6660b57cec5SDimitry Andric SmallVector<unsigned, 4> RetPath, CallPath; 6675ffd83dbSDimitry Andric SmallVector<Type *, 4> RetSubTypes, CallSubTypes; 6680b57cec5SDimitry Andric 6690b57cec5SDimitry Andric bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath); 6700b57cec5SDimitry Andric bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath); 6710b57cec5SDimitry Andric 6720b57cec5SDimitry Andric // Nothing's actually returned, it doesn't matter what the callee put there 6730b57cec5SDimitry Andric // it's a valid tail call. 6740b57cec5SDimitry Andric if (RetEmpty) 6750b57cec5SDimitry Andric return true; 6760b57cec5SDimitry Andric 6770b57cec5SDimitry Andric // Iterate pairwise through each of the value types making up the tail call 6780b57cec5SDimitry Andric // and the corresponding return. For each one we want to know whether it's 6790b57cec5SDimitry Andric // essentially going directly from the tail call to the ret, via operations 6800b57cec5SDimitry Andric // that end up not generating any code. 6810b57cec5SDimitry Andric // 6820b57cec5SDimitry Andric // We allow a certain amount of covariance here. For example it's permitted 6830b57cec5SDimitry Andric // for the tail call to define more bits than the ret actually cares about 6840b57cec5SDimitry Andric // (e.g. via a truncate). 6850b57cec5SDimitry Andric do { 6860b57cec5SDimitry Andric if (CallEmpty) { 6870b57cec5SDimitry Andric // We've exhausted the values produced by the tail call instruction, the 6880b57cec5SDimitry Andric // rest are essentially undef. The type doesn't really matter, but we need 6890b57cec5SDimitry Andric // *something*. 6905ffd83dbSDimitry Andric Type *SlotType = 6915ffd83dbSDimitry Andric ExtractValueInst::getIndexedType(RetSubTypes.back(), RetPath.back()); 6920b57cec5SDimitry Andric CallVal = UndefValue::get(SlotType); 6930b57cec5SDimitry Andric } 6940b57cec5SDimitry Andric 6950b57cec5SDimitry Andric // The manipulations performed when we're looking through an insertvalue or 6960b57cec5SDimitry Andric // an extractvalue would happen at the front of the RetPath list, so since 6970b57cec5SDimitry Andric // we have to copy it anyway it's more efficient to create a reversed copy. 6980eae32dcSDimitry Andric SmallVector<unsigned, 4> TmpRetPath(llvm::reverse(RetPath)); 6990eae32dcSDimitry Andric SmallVector<unsigned, 4> TmpCallPath(llvm::reverse(CallPath)); 7000b57cec5SDimitry Andric 7010b57cec5SDimitry Andric // Finally, we can check whether the value produced by the tail call at this 7020b57cec5SDimitry Andric // index is compatible with the value we return. 7030b57cec5SDimitry Andric if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath, 7040b57cec5SDimitry Andric AllowDifferingSizes, TLI, 705*0fca6ea1SDimitry Andric F->getDataLayout())) 7060b57cec5SDimitry Andric return false; 7070b57cec5SDimitry Andric 7080b57cec5SDimitry Andric CallEmpty = !nextRealType(CallSubTypes, CallPath); 7090b57cec5SDimitry Andric } while(nextRealType(RetSubTypes, RetPath)); 7100b57cec5SDimitry Andric 7110b57cec5SDimitry Andric return true; 7120b57cec5SDimitry Andric } 7130b57cec5SDimitry Andric 714*0fca6ea1SDimitry Andric bool llvm::funcReturnsFirstArgOfCall(const CallInst &CI) { 715*0fca6ea1SDimitry Andric const ReturnInst *Ret = dyn_cast<ReturnInst>(CI.getParent()->getTerminator()); 716*0fca6ea1SDimitry Andric Value *RetVal = Ret ? Ret->getReturnValue() : nullptr; 717*0fca6ea1SDimitry Andric bool ReturnsFirstArg = false; 718*0fca6ea1SDimitry Andric if (RetVal && ((RetVal == CI.getArgOperand(0)))) 719*0fca6ea1SDimitry Andric ReturnsFirstArg = true; 720*0fca6ea1SDimitry Andric return ReturnsFirstArg; 721*0fca6ea1SDimitry Andric } 722*0fca6ea1SDimitry Andric 7230b57cec5SDimitry Andric static void collectEHScopeMembers( 7240b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, int> &EHScopeMembership, int EHScope, 7250b57cec5SDimitry Andric const MachineBasicBlock *MBB) { 7260b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 16> Worklist = {MBB}; 7270b57cec5SDimitry Andric while (!Worklist.empty()) { 7280b57cec5SDimitry Andric const MachineBasicBlock *Visiting = Worklist.pop_back_val(); 7290b57cec5SDimitry Andric // Don't follow blocks which start new scopes. 7300b57cec5SDimitry Andric if (Visiting->isEHPad() && Visiting != MBB) 7310b57cec5SDimitry Andric continue; 7320b57cec5SDimitry Andric 7330b57cec5SDimitry Andric // Add this MBB to our scope. 7340b57cec5SDimitry Andric auto P = EHScopeMembership.insert(std::make_pair(Visiting, EHScope)); 7350b57cec5SDimitry Andric 7360b57cec5SDimitry Andric // Don't revisit blocks. 7370b57cec5SDimitry Andric if (!P.second) { 7380b57cec5SDimitry Andric assert(P.first->second == EHScope && "MBB is part of two scopes!"); 7390b57cec5SDimitry Andric continue; 7400b57cec5SDimitry Andric } 7410b57cec5SDimitry Andric 7420b57cec5SDimitry Andric // Returns are boundaries where scope transfer can occur, don't follow 7430b57cec5SDimitry Andric // successors. 7440b57cec5SDimitry Andric if (Visiting->isEHScopeReturnBlock()) 7450b57cec5SDimitry Andric continue; 7460b57cec5SDimitry Andric 747e8d8bef9SDimitry Andric append_range(Worklist, Visiting->successors()); 7480b57cec5SDimitry Andric } 7490b57cec5SDimitry Andric } 7500b57cec5SDimitry Andric 7510b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, int> 7520b57cec5SDimitry Andric llvm::getEHScopeMembership(const MachineFunction &MF) { 7530b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, int> EHScopeMembership; 7540b57cec5SDimitry Andric 7550b57cec5SDimitry Andric // We don't have anything to do if there aren't any EH pads. 7560b57cec5SDimitry Andric if (!MF.hasEHScopes()) 7570b57cec5SDimitry Andric return EHScopeMembership; 7580b57cec5SDimitry Andric 7590b57cec5SDimitry Andric int EntryBBNumber = MF.front().getNumber(); 7600b57cec5SDimitry Andric bool IsSEH = isAsynchronousEHPersonality( 7610b57cec5SDimitry Andric classifyEHPersonality(MF.getFunction().getPersonalityFn())); 7620b57cec5SDimitry Andric 7630b57cec5SDimitry Andric const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7640b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 16> EHScopeBlocks; 7650b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 16> UnreachableBlocks; 7660b57cec5SDimitry Andric SmallVector<const MachineBasicBlock *, 16> SEHCatchPads; 7670b57cec5SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *, int>, 16> CatchRetSuccessors; 7680b57cec5SDimitry Andric for (const MachineBasicBlock &MBB : MF) { 7690b57cec5SDimitry Andric if (MBB.isEHScopeEntry()) { 7700b57cec5SDimitry Andric EHScopeBlocks.push_back(&MBB); 7710b57cec5SDimitry Andric } else if (IsSEH && MBB.isEHPad()) { 7720b57cec5SDimitry Andric SEHCatchPads.push_back(&MBB); 7730b57cec5SDimitry Andric } else if (MBB.pred_empty()) { 7740b57cec5SDimitry Andric UnreachableBlocks.push_back(&MBB); 7750b57cec5SDimitry Andric } 7760b57cec5SDimitry Andric 7770b57cec5SDimitry Andric MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator(); 7780b57cec5SDimitry Andric 7790b57cec5SDimitry Andric // CatchPads are not scopes for SEH so do not consider CatchRet to 7800b57cec5SDimitry Andric // transfer control to another scope. 7810b57cec5SDimitry Andric if (MBBI == MBB.end() || MBBI->getOpcode() != TII->getCatchReturnOpcode()) 7820b57cec5SDimitry Andric continue; 7830b57cec5SDimitry Andric 7840b57cec5SDimitry Andric // FIXME: SEH CatchPads are not necessarily in the parent function: 7850b57cec5SDimitry Andric // they could be inside a finally block. 7860b57cec5SDimitry Andric const MachineBasicBlock *Successor = MBBI->getOperand(0).getMBB(); 7870b57cec5SDimitry Andric const MachineBasicBlock *SuccessorColor = MBBI->getOperand(1).getMBB(); 7880b57cec5SDimitry Andric CatchRetSuccessors.push_back( 7890b57cec5SDimitry Andric {Successor, IsSEH ? EntryBBNumber : SuccessorColor->getNumber()}); 7900b57cec5SDimitry Andric } 7910b57cec5SDimitry Andric 7920b57cec5SDimitry Andric // We don't have anything to do if there aren't any EH pads. 7930b57cec5SDimitry Andric if (EHScopeBlocks.empty()) 7940b57cec5SDimitry Andric return EHScopeMembership; 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric // Identify all the basic blocks reachable from the function entry. 7970b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, &MF.front()); 7980b57cec5SDimitry Andric // All blocks not part of a scope are in the parent function. 7990b57cec5SDimitry Andric for (const MachineBasicBlock *MBB : UnreachableBlocks) 8000b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB); 8010b57cec5SDimitry Andric // Next, identify all the blocks inside the scopes. 8020b57cec5SDimitry Andric for (const MachineBasicBlock *MBB : EHScopeBlocks) 8030b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, MBB->getNumber(), MBB); 8040b57cec5SDimitry Andric // SEH CatchPads aren't really scopes, handle them separately. 8050b57cec5SDimitry Andric for (const MachineBasicBlock *MBB : SEHCatchPads) 8060b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, EntryBBNumber, MBB); 8070b57cec5SDimitry Andric // Finally, identify all the targets of a catchret. 8080b57cec5SDimitry Andric for (std::pair<const MachineBasicBlock *, int> CatchRetPair : 8090b57cec5SDimitry Andric CatchRetSuccessors) 8100b57cec5SDimitry Andric collectEHScopeMembers(EHScopeMembership, CatchRetPair.second, 8110b57cec5SDimitry Andric CatchRetPair.first); 8120b57cec5SDimitry Andric return EHScopeMembership; 8130b57cec5SDimitry Andric } 814