LLVM API Documentation

CodeGen/Analysis.cpp
Go to the documentation of this file.
00001 //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines several CodeGen-specific LLVM IR analysis utilities.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/Analysis.h"
00015 #include "llvm/Analysis/ValueTracking.h"
00016 #include "llvm/CodeGen/MachineFunction.h"
00017 #include "llvm/CodeGen/SelectionDAG.h"
00018 #include "llvm/IR/DataLayout.h"
00019 #include "llvm/IR/DerivedTypes.h"
00020 #include "llvm/IR/Function.h"
00021 #include "llvm/IR/Instructions.h"
00022 #include "llvm/IR/IntrinsicInst.h"
00023 #include "llvm/IR/LLVMContext.h"
00024 #include "llvm/IR/Module.h"
00025 #include "llvm/Support/ErrorHandling.h"
00026 #include "llvm/Support/MathExtras.h"
00027 #include "llvm/Target/TargetLowering.h"
00028 #include "llvm/Target/TargetSubtargetInfo.h"
00029 #include "llvm/Transforms/Utils/GlobalStatus.h"
00030 
00031 using namespace llvm;
00032 
00033 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
00034 /// of insertvalue or extractvalue indices that identify a member, return
00035 /// the linearized index of the start of the member.
00036 ///
00037 unsigned llvm::ComputeLinearIndex(Type *Ty,
00038                                   const unsigned *Indices,
00039                                   const unsigned *IndicesEnd,
00040                                   unsigned CurIndex) {
00041   // Base case: We're done.
00042   if (Indices && Indices == IndicesEnd)
00043     return CurIndex;
00044 
00045   // Given a struct type, recursively traverse the elements.
00046   if (StructType *STy = dyn_cast<StructType>(Ty)) {
00047     for (StructType::element_iterator EB = STy->element_begin(),
00048                                       EI = EB,
00049                                       EE = STy->element_end();
00050         EI != EE; ++EI) {
00051       if (Indices && *Indices == unsigned(EI - EB))
00052         return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
00053       CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
00054     }
00055     return CurIndex;
00056   }
00057   // Given an array type, recursively traverse the elements.
00058   else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00059     Type *EltTy = ATy->getElementType();
00060     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
00061       if (Indices && *Indices == i)
00062         return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
00063       CurIndex = ComputeLinearIndex(EltTy, nullptr, nullptr, CurIndex);
00064     }
00065     return CurIndex;
00066   }
00067   // We haven't found the type we're looking for, so keep searching.
00068   return CurIndex + 1;
00069 }
00070 
00071 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
00072 /// EVTs that represent all the individual underlying
00073 /// non-aggregate types that comprise it.
00074 ///
00075 /// If Offsets is non-null, it points to a vector to be filled in
00076 /// with the in-memory offsets of each of the individual values.
00077 ///
00078 void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
00079                            SmallVectorImpl<EVT> &ValueVTs,
00080                            SmallVectorImpl<uint64_t> *Offsets,
00081                            uint64_t StartingOffset) {
00082   // Given a struct type, recursively traverse the elements.
00083   if (StructType *STy = dyn_cast<StructType>(Ty)) {
00084     const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy);
00085     for (StructType::element_iterator EB = STy->element_begin(),
00086                                       EI = EB,
00087                                       EE = STy->element_end();
00088          EI != EE; ++EI)
00089       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
00090                       StartingOffset + SL->getElementOffset(EI - EB));
00091     return;
00092   }
00093   // Given an array type, recursively traverse the elements.
00094   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00095     Type *EltTy = ATy->getElementType();
00096     uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy);
00097     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
00098       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
00099                       StartingOffset + i * EltSize);
00100     return;
00101   }
00102   // Interpret void as zero return values.
00103   if (Ty->isVoidTy())
00104     return;
00105   // Base case: we can get an EVT for this LLVM IR type.
00106   ValueVTs.push_back(TLI.getValueType(Ty));
00107   if (Offsets)
00108     Offsets->push_back(StartingOffset);
00109 }
00110 
00111 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
00112 GlobalValue *llvm::ExtractTypeInfo(Value *V) {
00113   V = V->stripPointerCasts();
00114   GlobalValue *GV = dyn_cast<GlobalValue>(V);
00115   GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
00116 
00117   if (Var && Var->getName() == "llvm.eh.catch.all.value") {
00118     assert(Var->hasInitializer() &&
00119            "The EH catch-all value must have an initializer");
00120     Value *Init = Var->getInitializer();
00121     GV = dyn_cast<GlobalValue>(Init);
00122     if (!GV) V = cast<ConstantPointerNull>(Init);
00123   }
00124 
00125   assert((GV || isa<ConstantPointerNull>(V)) &&
00126          "TypeInfo must be a global variable or NULL");
00127   return GV;
00128 }
00129 
00130 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
00131 /// processed uses a memory 'm' constraint.
00132 bool
00133 llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
00134                                 const TargetLowering &TLI) {
00135   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
00136     InlineAsm::ConstraintInfo &CI = CInfos[i];
00137     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
00138       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
00139       if (CType == TargetLowering::C_Memory)
00140         return true;
00141     }
00142 
00143     // Indirect operand accesses access memory.
00144     if (CI.isIndirect)
00145       return true;
00146   }
00147 
00148   return false;
00149 }
00150 
00151 /// getFCmpCondCode - Return the ISD condition code corresponding to
00152 /// the given LLVM IR floating-point condition code.  This includes
00153 /// consideration of global floating-point math flags.
00154 ///
00155 ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
00156   switch (Pred) {
00157   case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
00158   case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
00159   case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
00160   case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
00161   case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
00162   case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
00163   case FCmpInst::FCMP_ONE:   return ISD::SETONE;
00164   case FCmpInst::FCMP_ORD:   return ISD::SETO;
00165   case FCmpInst::FCMP_UNO:   return ISD::SETUO;
00166   case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
00167   case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
00168   case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
00169   case FCmpInst::FCMP_ULT:   return ISD::SETULT;
00170   case FCmpInst::FCMP_ULE:   return ISD::SETULE;
00171   case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
00172   case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
00173   default: llvm_unreachable("Invalid FCmp predicate opcode!");
00174   }
00175 }
00176 
00177 ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
00178   switch (CC) {
00179     case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
00180     case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
00181     case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
00182     case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
00183     case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
00184     case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
00185     default: return CC;
00186   }
00187 }
00188 
00189 /// getICmpCondCode - Return the ISD condition code corresponding to
00190 /// the given LLVM IR integer condition code.
00191 ///
00192 ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
00193   switch (Pred) {
00194   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
00195   case ICmpInst::ICMP_NE:  return ISD::SETNE;
00196   case ICmpInst::ICMP_SLE: return ISD::SETLE;
00197   case ICmpInst::ICMP_ULE: return ISD::SETULE;
00198   case ICmpInst::ICMP_SGE: return ISD::SETGE;
00199   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
00200   case ICmpInst::ICMP_SLT: return ISD::SETLT;
00201   case ICmpInst::ICMP_ULT: return ISD::SETULT;
00202   case ICmpInst::ICMP_SGT: return ISD::SETGT;
00203   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
00204   default:
00205     llvm_unreachable("Invalid ICmp predicate opcode!");
00206   }
00207 }
00208 
00209 static bool isNoopBitcast(Type *T1, Type *T2,
00210                           const TargetLoweringBase& TLI) {
00211   return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
00212          (isa<VectorType>(T1) && isa<VectorType>(T2) &&
00213           TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
00214 }
00215 
00216 /// Look through operations that will be free to find the earliest source of
00217 /// this value.
00218 ///
00219 /// @param ValLoc If V has aggegate type, we will be interested in a particular
00220 /// scalar component. This records its address; the reverse of this list gives a
00221 /// sequence of indices appropriate for an extractvalue to locate the important
00222 /// value. This value is updated during the function and on exit will indicate
00223 /// similar information for the Value returned.
00224 ///
00225 /// @param DataBits If this function looks through truncate instructions, this
00226 /// will record the smallest size attained.
00227 static const Value *getNoopInput(const Value *V,
00228                                  SmallVectorImpl<unsigned> &ValLoc,
00229                                  unsigned &DataBits,
00230                                  const TargetLoweringBase &TLI) {
00231   while (true) {
00232     // Try to look through V1; if V1 is not an instruction, it can't be looked
00233     // through.
00234     const Instruction *I = dyn_cast<Instruction>(V);
00235     if (!I || I->getNumOperands() == 0) return V;
00236     const Value *NoopInput = nullptr;
00237 
00238     Value *Op = I->getOperand(0);
00239     if (isa<BitCastInst>(I)) {
00240       // Look through truly no-op bitcasts.
00241       if (isNoopBitcast(Op->getType(), I->getType(), TLI))
00242         NoopInput = Op;
00243     } else if (isa<GetElementPtrInst>(I)) {
00244       // Look through getelementptr
00245       if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
00246         NoopInput = Op;
00247     } else if (isa<IntToPtrInst>(I)) {
00248       // Look through inttoptr.
00249       // Make sure this isn't a truncating or extending cast.  We could
00250       // support this eventually, but don't bother for now.
00251       if (!isa<VectorType>(I->getType()) &&
00252           TLI.getPointerTy().getSizeInBits() ==
00253           cast<IntegerType>(Op->getType())->getBitWidth())
00254         NoopInput = Op;
00255     } else if (isa<PtrToIntInst>(I)) {
00256       // Look through ptrtoint.
00257       // Make sure this isn't a truncating or extending cast.  We could
00258       // support this eventually, but don't bother for now.
00259       if (!isa<VectorType>(I->getType()) &&
00260           TLI.getPointerTy().getSizeInBits() ==
00261           cast<IntegerType>(I->getType())->getBitWidth())
00262         NoopInput = Op;
00263     } else if (isa<TruncInst>(I) &&
00264                TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
00265       DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
00266       NoopInput = Op;
00267     } else if (isa<CallInst>(I)) {
00268       // Look through call (skipping callee)
00269       for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1;
00270            i != e; ++i) {
00271         unsigned attrInd = i - I->op_begin() + 1;
00272         if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
00273             isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
00274           NoopInput = *i;
00275           break;
00276         }
00277       }
00278     } else if (isa<InvokeInst>(I)) {
00279       // Look through invoke (skipping BB, BB, Callee)
00280       for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3;
00281            i != e; ++i) {
00282         unsigned attrInd = i - I->op_begin() + 1;
00283         if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
00284             isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
00285           NoopInput = *i;
00286           break;
00287         }
00288       }
00289     } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
00290       // Value may come from either the aggregate or the scalar
00291       ArrayRef<unsigned> InsertLoc = IVI->getIndices();
00292       if (std::equal(InsertLoc.rbegin(), InsertLoc.rend(),
00293                      ValLoc.rbegin())) {
00294         // The type being inserted is a nested sub-type of the aggregate; we
00295         // have to remove those initial indices to get the location we're
00296         // interested in for the operand.
00297         ValLoc.resize(ValLoc.size() - InsertLoc.size());
00298         NoopInput = IVI->getInsertedValueOperand();
00299       } else {
00300         // The struct we're inserting into has the value we're interested in, no
00301         // change of address.
00302         NoopInput = Op;
00303       }
00304     } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
00305       // The part we're interested in will inevitably be some sub-section of the
00306       // previous aggregate. Combine the two paths to obtain the true address of
00307       // our element.
00308       ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
00309       std::copy(ExtractLoc.rbegin(), ExtractLoc.rend(),
00310                 std::back_inserter(ValLoc));
00311       NoopInput = Op;
00312     }
00313     // Terminate if we couldn't find anything to look through.
00314     if (!NoopInput)
00315       return V;
00316 
00317     V = NoopInput;
00318   }
00319 }
00320 
00321 /// Return true if this scalar return value only has bits discarded on its path
00322 /// from the "tail call" to the "ret". This includes the obvious noop
00323 /// instructions handled by getNoopInput above as well as free truncations (or
00324 /// extensions prior to the call).
00325 static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
00326                                  SmallVectorImpl<unsigned> &RetIndices,
00327                                  SmallVectorImpl<unsigned> &CallIndices,
00328                                  bool AllowDifferingSizes,
00329                                  const TargetLoweringBase &TLI) {
00330 
00331   // Trace the sub-value needed by the return value as far back up the graph as
00332   // possible, in the hope that it will intersect with the value produced by the
00333   // call. In the simple case with no "returned" attribute, the hope is actually
00334   // that we end up back at the tail call instruction itself.
00335   unsigned BitsRequired = UINT_MAX;
00336   RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI);
00337 
00338   // If this slot in the value returned is undef, it doesn't matter what the
00339   // call puts there, it'll be fine.
00340   if (isa<UndefValue>(RetVal))
00341     return true;
00342 
00343   // Now do a similar search up through the graph to find where the value
00344   // actually returned by the "tail call" comes from. In the simple case without
00345   // a "returned" attribute, the search will be blocked immediately and the loop
00346   // a Noop.
00347   unsigned BitsProvided = UINT_MAX;
00348   CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI);
00349 
00350   // There's no hope if we can't actually trace them to (the same part of!) the
00351   // same value.
00352   if (CallVal != RetVal || CallIndices != RetIndices)
00353     return false;
00354 
00355   // However, intervening truncates may have made the call non-tail. Make sure
00356   // all the bits that are needed by the "ret" have been provided by the "tail
00357   // call". FIXME: with sufficiently cunning bit-tracking, we could look through
00358   // extensions too.
00359   if (BitsProvided < BitsRequired ||
00360       (!AllowDifferingSizes && BitsProvided != BitsRequired))
00361     return false;
00362 
00363   return true;
00364 }
00365 
00366 /// For an aggregate type, determine whether a given index is within bounds or
00367 /// not.
00368 static bool indexReallyValid(CompositeType *T, unsigned Idx) {
00369   if (ArrayType *AT = dyn_cast<ArrayType>(T))
00370     return Idx < AT->getNumElements();
00371 
00372   return Idx < cast<StructType>(T)->getNumElements();
00373 }
00374 
00375 /// Move the given iterators to the next leaf type in depth first traversal.
00376 ///
00377 /// Performs a depth-first traversal of the type as specified by its arguments,
00378 /// stopping at the next leaf node (which may be a legitimate scalar type or an
00379 /// empty struct or array).
00380 ///
00381 /// @param SubTypes List of the partial components making up the type from
00382 /// outermost to innermost non-empty aggregate. The element currently
00383 /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
00384 ///
00385 /// @param Path Set of extractvalue indices leading from the outermost type
00386 /// (SubTypes[0]) to the leaf node currently represented.
00387 ///
00388 /// @returns true if a new type was found, false otherwise. Calling this
00389 /// function again on a finished iterator will repeatedly return
00390 /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
00391 /// aggregate or a non-aggregate
00392 static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
00393                                   SmallVectorImpl<unsigned> &Path) {
00394   // First march back up the tree until we can successfully increment one of the
00395   // coordinates in Path.
00396   while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
00397     Path.pop_back();
00398     SubTypes.pop_back();
00399   }
00400 
00401   // If we reached the top, then the iterator is done.
00402   if (Path.empty())
00403     return false;
00404 
00405   // We know there's *some* valid leaf now, so march back down the tree picking
00406   // out the left-most element at each node.
00407   ++Path.back();
00408   Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
00409   while (DeeperType->isAggregateType()) {
00410     CompositeType *CT = cast<CompositeType>(DeeperType);
00411     if (!indexReallyValid(CT, 0))
00412       return true;
00413 
00414     SubTypes.push_back(CT);
00415     Path.push_back(0);
00416 
00417     DeeperType = CT->getTypeAtIndex(0U);
00418   }
00419 
00420   return true;
00421 }
00422 
00423 /// Find the first non-empty, scalar-like type in Next and setup the iterator
00424 /// components.
00425 ///
00426 /// Assuming Next is an aggregate of some kind, this function will traverse the
00427 /// tree from left to right (i.e. depth-first) looking for the first
00428 /// non-aggregate type which will play a role in function return.
00429 ///
00430 /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
00431 /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
00432 /// i32 in that type.
00433 static bool firstRealType(Type *Next,
00434                           SmallVectorImpl<CompositeType *> &SubTypes,
00435                           SmallVectorImpl<unsigned> &Path) {
00436   // First initialise the iterator components to the first "leaf" node
00437   // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
00438   // despite nominally being an aggregate).
00439   while (Next->isAggregateType() &&
00440          indexReallyValid(cast<CompositeType>(Next), 0)) {
00441     SubTypes.push_back(cast<CompositeType>(Next));
00442     Path.push_back(0);
00443     Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
00444   }
00445 
00446   // If there's no Path now, Next was originally scalar already (or empty
00447   // leaf). We're done.
00448   if (Path.empty())
00449     return true;
00450 
00451   // Otherwise, use normal iteration to keep looking through the tree until we
00452   // find a non-aggregate type.
00453   while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
00454     if (!advanceToNextLeafType(SubTypes, Path))
00455       return false;
00456   }
00457 
00458   return true;
00459 }
00460 
00461 /// Set the iterator data-structures to the next non-empty, non-aggregate
00462 /// subtype.
00463 static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
00464                          SmallVectorImpl<unsigned> &Path) {
00465   do {
00466     if (!advanceToNextLeafType(SubTypes, Path))
00467       return false;
00468 
00469     assert(!Path.empty() && "found a leaf but didn't set the path?");
00470   } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
00471 
00472   return true;
00473 }
00474 
00475 
00476 /// Test if the given instruction is in a position to be optimized
00477 /// with a tail-call. This roughly means that it's in a block with
00478 /// a return and there's nothing that needs to be scheduled
00479 /// between it and the return.
00480 ///
00481 /// This function only tests target-independent requirements.
00482 bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) {
00483   const Instruction *I = CS.getInstruction();
00484   const BasicBlock *ExitBB = I->getParent();
00485   const TerminatorInst *Term = ExitBB->getTerminator();
00486   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
00487 
00488   // The block must end in a return statement or unreachable.
00489   //
00490   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
00491   // an unreachable, for now. The way tailcall optimization is currently
00492   // implemented means it will add an epilogue followed by a jump. That is
00493   // not profitable. Also, if the callee is a special function (e.g.
00494   // longjmp on x86), it can end up causing miscompilation that has not
00495   // been fully understood.
00496   if (!Ret &&
00497       (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
00498     return false;
00499 
00500   // If I will have a chain, make sure no other instruction that will have a
00501   // chain interposes between I and the return.
00502   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
00503       !isSafeToSpeculativelyExecute(I))
00504     for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
00505       if (&*BBI == I)
00506         break;
00507       // Debug info intrinsics do not get in the way of tail call optimization.
00508       if (isa<DbgInfoIntrinsic>(BBI))
00509         continue;
00510       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
00511           !isSafeToSpeculativelyExecute(BBI))
00512         return false;
00513     }
00514 
00515   return returnTypeIsEligibleForTailCall(
00516       ExitBB->getParent(), I, Ret, *TM.getSubtargetImpl()->getTargetLowering());
00517 }
00518 
00519 bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
00520                                            const Instruction *I,
00521                                            const ReturnInst *Ret,
00522                                            const TargetLoweringBase &TLI) {
00523   // If the block ends with a void return or unreachable, it doesn't matter
00524   // what the call's return type is.
00525   if (!Ret || Ret->getNumOperands() == 0) return true;
00526 
00527   // If the return value is undef, it doesn't matter what the call's
00528   // return type is.
00529   if (isa<UndefValue>(Ret->getOperand(0))) return true;
00530 
00531   // Make sure the attributes attached to each return are compatible.
00532   AttrBuilder CallerAttrs(F->getAttributes(),
00533                           AttributeSet::ReturnIndex);
00534   AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
00535                           AttributeSet::ReturnIndex);
00536 
00537   // Noalias is completely benign as far as calling convention goes, it
00538   // shouldn't affect whether the call is a tail call.
00539   CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias);
00540   CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias);
00541 
00542   bool AllowDifferingSizes = true;
00543   if (CallerAttrs.contains(Attribute::ZExt)) {
00544     if (!CalleeAttrs.contains(Attribute::ZExt))
00545       return false;
00546 
00547     AllowDifferingSizes = false;
00548     CallerAttrs.removeAttribute(Attribute::ZExt);
00549     CalleeAttrs.removeAttribute(Attribute::ZExt);
00550   } else if (CallerAttrs.contains(Attribute::SExt)) {
00551     if (!CalleeAttrs.contains(Attribute::SExt))
00552       return false;
00553 
00554     AllowDifferingSizes = false;
00555     CallerAttrs.removeAttribute(Attribute::SExt);
00556     CalleeAttrs.removeAttribute(Attribute::SExt);
00557   }
00558 
00559   // If they're still different, there's some facet we don't understand
00560   // (currently only "inreg", but in future who knows). It may be OK but the
00561   // only safe option is to reject the tail call.
00562   if (CallerAttrs != CalleeAttrs)
00563     return false;
00564 
00565   const Value *RetVal = Ret->getOperand(0), *CallVal = I;
00566   SmallVector<unsigned, 4> RetPath, CallPath;
00567   SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
00568 
00569   bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
00570   bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
00571 
00572   // Nothing's actually returned, it doesn't matter what the callee put there
00573   // it's a valid tail call.
00574   if (RetEmpty)
00575     return true;
00576 
00577   // Iterate pairwise through each of the value types making up the tail call
00578   // and the corresponding return. For each one we want to know whether it's
00579   // essentially going directly from the tail call to the ret, via operations
00580   // that end up not generating any code.
00581   //
00582   // We allow a certain amount of covariance here. For example it's permitted
00583   // for the tail call to define more bits than the ret actually cares about
00584   // (e.g. via a truncate).
00585   do {
00586     if (CallEmpty) {
00587       // We've exhausted the values produced by the tail call instruction, the
00588       // rest are essentially undef. The type doesn't really matter, but we need
00589       // *something*.
00590       Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
00591       CallVal = UndefValue::get(SlotType);
00592     }
00593 
00594     // The manipulations performed when we're looking through an insertvalue or
00595     // an extractvalue would happen at the front of the RetPath list, so since
00596     // we have to copy it anyway it's more efficient to create a reversed copy.
00597     using std::copy;
00598     SmallVector<unsigned, 4> TmpRetPath, TmpCallPath;
00599     copy(RetPath.rbegin(), RetPath.rend(), std::back_inserter(TmpRetPath));
00600     copy(CallPath.rbegin(), CallPath.rend(), std::back_inserter(TmpCallPath));
00601 
00602     // Finally, we can check whether the value produced by the tail call at this
00603     // index is compatible with the value we return.
00604     if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
00605                               AllowDifferingSizes, TLI))
00606       return false;
00607 
00608     CallEmpty  = !nextRealType(CallSubTypes, CallPath);
00609   } while(nextRealType(RetSubTypes, RetPath));
00610 
00611   return true;
00612 }
00613 
00614 bool llvm::canBeOmittedFromSymbolTable(const GlobalValue *GV) {
00615   if (!GV->hasLinkOnceODRLinkage())
00616     return false;
00617 
00618   if (GV->hasUnnamedAddr())
00619     return true;
00620 
00621   // If it is a non constant variable, it needs to be uniqued across shared
00622   // objects.
00623   if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
00624     if (!Var->isConstant())
00625       return false;
00626   }
00627 
00628   // An alias can point to a variable. We could try to resolve the alias to
00629   // decide, but for now just don't hide them.
00630   if (isa<GlobalAlias>(GV))
00631     return false;
00632 
00633   GlobalStatus GS;
00634   if (GlobalStatus::analyzeGlobal(GV, GS))
00635     return false;
00636 
00637   return !GS.IsCompared;
00638 }