2
0

Analysis.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines several CodeGen-specific LLVM IR analysis utilities.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/Analysis.h"
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/CodeGen/MachineFunction.h"
  16. #include "llvm/CodeGen/SelectionDAG.h"
  17. #include "llvm/IR/DataLayout.h"
  18. #include "llvm/IR/DerivedTypes.h"
  19. #include "llvm/IR/Function.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/IntrinsicInst.h"
  22. #include "llvm/IR/LLVMContext.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/MathExtras.h"
  26. #include "llvm/Target/TargetLowering.h"
  27. #include "llvm/Target/TargetSubtargetInfo.h"
  28. #include "llvm/Transforms/Utils/GlobalStatus.h"
  29. using namespace llvm;
  30. /// Compute the linearized index of a member in a nested aggregate/struct/array
  31. /// by recursing and accumulating CurIndex as long as there are indices in the
  32. /// index list.
  33. unsigned llvm::ComputeLinearIndex(Type *Ty,
  34. const unsigned *Indices,
  35. const unsigned *IndicesEnd,
  36. unsigned CurIndex) {
  37. // Base case: We're done.
  38. if (Indices && Indices == IndicesEnd)
  39. return CurIndex;
  40. // Given a struct type, recursively traverse the elements.
  41. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  42. for (StructType::element_iterator EB = STy->element_begin(),
  43. EI = EB,
  44. EE = STy->element_end();
  45. EI != EE; ++EI) {
  46. if (Indices && *Indices == unsigned(EI - EB))
  47. return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
  48. CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
  49. }
  50. assert(!Indices && "Unexpected out of bound");
  51. return CurIndex;
  52. }
  53. // Given an array type, recursively traverse the elements.
  54. else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  55. Type *EltTy = ATy->getElementType();
  56. unsigned NumElts = ATy->getNumElements();
  57. // Compute the Linear offset when jumping one element of the array
  58. unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
  59. if (Indices) {
  60. assert(*Indices < NumElts && "Unexpected out of bound");
  61. // If the indice is inside the array, compute the index to the requested
  62. // elt and recurse inside the element with the end of the indices list
  63. CurIndex += EltLinearOffset* *Indices;
  64. return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
  65. }
  66. CurIndex += EltLinearOffset*NumElts;
  67. return CurIndex;
  68. }
  69. // We haven't found the type we're looking for, so keep searching.
  70. return CurIndex + 1;
  71. }
  72. /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
  73. /// EVTs that represent all the individual underlying
  74. /// non-aggregate types that comprise it.
  75. ///
  76. /// If Offsets is non-null, it points to a vector to be filled in
  77. /// with the in-memory offsets of each of the individual values.
  78. ///
  79. void llvm::ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL,
  80. Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
  81. SmallVectorImpl<uint64_t> *Offsets,
  82. uint64_t StartingOffset) {
  83. // Given a struct type, recursively traverse the elements.
  84. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  85. const StructLayout *SL = DL.getStructLayout(STy);
  86. for (StructType::element_iterator EB = STy->element_begin(),
  87. EI = EB,
  88. EE = STy->element_end();
  89. EI != EE; ++EI)
  90. ComputeValueVTs(TLI, DL, *EI, ValueVTs, Offsets,
  91. StartingOffset + SL->getElementOffset(EI - EB));
  92. return;
  93. }
  94. // Given an array type, recursively traverse the elements.
  95. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  96. Type *EltTy = ATy->getElementType();
  97. uint64_t EltSize = DL.getTypeAllocSize(EltTy);
  98. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
  99. ComputeValueVTs(TLI, DL, EltTy, ValueVTs, Offsets,
  100. StartingOffset + i * EltSize);
  101. return;
  102. }
  103. // Interpret void as zero return values.
  104. if (Ty->isVoidTy())
  105. return;
  106. // Base case: we can get an EVT for this LLVM IR type.
  107. ValueVTs.push_back(TLI.getValueType(DL, Ty));
  108. if (Offsets)
  109. Offsets->push_back(StartingOffset);
  110. }
  111. /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
  112. GlobalValue *llvm::ExtractTypeInfo(Value *V) {
  113. V = V->stripPointerCasts();
  114. GlobalValue *GV = dyn_cast<GlobalValue>(V);
  115. GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
  116. if (Var && Var->getName() == "llvm.eh.catch.all.value") {
  117. assert(Var->hasInitializer() &&
  118. "The EH catch-all value must have an initializer");
  119. Value *Init = Var->getInitializer();
  120. GV = dyn_cast<GlobalValue>(Init);
  121. if (!GV) V = cast<ConstantPointerNull>(Init);
  122. }
  123. assert((GV || isa<ConstantPointerNull>(V)) &&
  124. "TypeInfo must be a global variable or NULL");
  125. return GV;
  126. }
  127. /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
  128. /// processed uses a memory 'm' constraint.
  129. bool
  130. llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
  131. const TargetLowering &TLI) {
  132. for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
  133. InlineAsm::ConstraintInfo &CI = CInfos[i];
  134. for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
  135. TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
  136. if (CType == TargetLowering::C_Memory)
  137. return true;
  138. }
  139. // Indirect operand accesses access memory.
  140. if (CI.isIndirect)
  141. return true;
  142. }
  143. return false;
  144. }
  145. /// getFCmpCondCode - Return the ISD condition code corresponding to
  146. /// the given LLVM IR floating-point condition code. This includes
  147. /// consideration of global floating-point math flags.
  148. ///
  149. ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
  150. switch (Pred) {
  151. case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
  152. case FCmpInst::FCMP_OEQ: return ISD::SETOEQ;
  153. case FCmpInst::FCMP_OGT: return ISD::SETOGT;
  154. case FCmpInst::FCMP_OGE: return ISD::SETOGE;
  155. case FCmpInst::FCMP_OLT: return ISD::SETOLT;
  156. case FCmpInst::FCMP_OLE: return ISD::SETOLE;
  157. case FCmpInst::FCMP_ONE: return ISD::SETONE;
  158. case FCmpInst::FCMP_ORD: return ISD::SETO;
  159. case FCmpInst::FCMP_UNO: return ISD::SETUO;
  160. case FCmpInst::FCMP_UEQ: return ISD::SETUEQ;
  161. case FCmpInst::FCMP_UGT: return ISD::SETUGT;
  162. case FCmpInst::FCMP_UGE: return ISD::SETUGE;
  163. case FCmpInst::FCMP_ULT: return ISD::SETULT;
  164. case FCmpInst::FCMP_ULE: return ISD::SETULE;
  165. case FCmpInst::FCMP_UNE: return ISD::SETUNE;
  166. case FCmpInst::FCMP_TRUE: return ISD::SETTRUE;
  167. default: llvm_unreachable("Invalid FCmp predicate opcode!");
  168. }
  169. }
  170. ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
  171. switch (CC) {
  172. case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
  173. case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
  174. case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
  175. case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
  176. case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
  177. case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
  178. default: return CC;
  179. }
  180. }
  181. /// getICmpCondCode - Return the ISD condition code corresponding to
  182. /// the given LLVM IR integer condition code.
  183. ///
  184. ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
  185. switch (Pred) {
  186. case ICmpInst::ICMP_EQ: return ISD::SETEQ;
  187. case ICmpInst::ICMP_NE: return ISD::SETNE;
  188. case ICmpInst::ICMP_SLE: return ISD::SETLE;
  189. case ICmpInst::ICMP_ULE: return ISD::SETULE;
  190. case ICmpInst::ICMP_SGE: return ISD::SETGE;
  191. case ICmpInst::ICMP_UGE: return ISD::SETUGE;
  192. case ICmpInst::ICMP_SLT: return ISD::SETLT;
  193. case ICmpInst::ICMP_ULT: return ISD::SETULT;
  194. case ICmpInst::ICMP_SGT: return ISD::SETGT;
  195. case ICmpInst::ICMP_UGT: return ISD::SETUGT;
  196. default:
  197. llvm_unreachable("Invalid ICmp predicate opcode!");
  198. }
  199. }
  200. static bool isNoopBitcast(Type *T1, Type *T2,
  201. const TargetLoweringBase& TLI) {
  202. return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
  203. (isa<VectorType>(T1) && isa<VectorType>(T2) &&
  204. TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
  205. }
  206. /// Look through operations that will be free to find the earliest source of
  207. /// this value.
  208. ///
  209. /// @param ValLoc If V has aggegate type, we will be interested in a particular
  210. /// scalar component. This records its address; the reverse of this list gives a
  211. /// sequence of indices appropriate for an extractvalue to locate the important
  212. /// value. This value is updated during the function and on exit will indicate
  213. /// similar information for the Value returned.
  214. ///
  215. /// @param DataBits If this function looks through truncate instructions, this
  216. /// will record the smallest size attained.
  217. static const Value *getNoopInput(const Value *V,
  218. SmallVectorImpl<unsigned> &ValLoc,
  219. unsigned &DataBits,
  220. const TargetLoweringBase &TLI,
  221. const DataLayout &DL) {
  222. while (true) {
  223. // Try to look through V1; if V1 is not an instruction, it can't be looked
  224. // through.
  225. const Instruction *I = dyn_cast<Instruction>(V);
  226. if (!I || I->getNumOperands() == 0) return V;
  227. const Value *NoopInput = nullptr;
  228. Value *Op = I->getOperand(0);
  229. if (isa<BitCastInst>(I)) {
  230. // Look through truly no-op bitcasts.
  231. if (isNoopBitcast(Op->getType(), I->getType(), TLI))
  232. NoopInput = Op;
  233. } else if (isa<GetElementPtrInst>(I)) {
  234. // Look through getelementptr
  235. if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
  236. NoopInput = Op;
  237. } else if (isa<IntToPtrInst>(I)) {
  238. // Look through inttoptr.
  239. // Make sure this isn't a truncating or extending cast. We could
  240. // support this eventually, but don't bother for now.
  241. if (!isa<VectorType>(I->getType()) &&
  242. DL.getPointerSizeInBits() ==
  243. cast<IntegerType>(Op->getType())->getBitWidth())
  244. NoopInput = Op;
  245. } else if (isa<PtrToIntInst>(I)) {
  246. // Look through ptrtoint.
  247. // Make sure this isn't a truncating or extending cast. We could
  248. // support this eventually, but don't bother for now.
  249. if (!isa<VectorType>(I->getType()) &&
  250. DL.getPointerSizeInBits() ==
  251. cast<IntegerType>(I->getType())->getBitWidth())
  252. NoopInput = Op;
  253. } else if (isa<TruncInst>(I) &&
  254. TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
  255. DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
  256. NoopInput = Op;
  257. } else if (isa<CallInst>(I)) {
  258. // Look through call (skipping callee)
  259. for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1;
  260. i != e; ++i) {
  261. unsigned attrInd = i - I->op_begin() + 1;
  262. if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
  263. isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
  264. NoopInput = *i;
  265. break;
  266. }
  267. }
  268. } else if (isa<InvokeInst>(I)) {
  269. // Look through invoke (skipping BB, BB, Callee)
  270. for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3;
  271. i != e; ++i) {
  272. unsigned attrInd = i - I->op_begin() + 1;
  273. if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
  274. isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
  275. NoopInput = *i;
  276. break;
  277. }
  278. }
  279. } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
  280. // Value may come from either the aggregate or the scalar
  281. ArrayRef<unsigned> InsertLoc = IVI->getIndices();
  282. if (ValLoc.size() >= InsertLoc.size() &&
  283. std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
  284. // The type being inserted is a nested sub-type of the aggregate; we
  285. // have to remove those initial indices to get the location we're
  286. // interested in for the operand.
  287. ValLoc.resize(ValLoc.size() - InsertLoc.size());
  288. NoopInput = IVI->getInsertedValueOperand();
  289. } else {
  290. // The struct we're inserting into has the value we're interested in, no
  291. // change of address.
  292. NoopInput = Op;
  293. }
  294. } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
  295. // The part we're interested in will inevitably be some sub-section of the
  296. // previous aggregate. Combine the two paths to obtain the true address of
  297. // our element.
  298. ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
  299. ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
  300. NoopInput = Op;
  301. }
  302. // Terminate if we couldn't find anything to look through.
  303. if (!NoopInput)
  304. return V;
  305. V = NoopInput;
  306. }
  307. }
  308. /// Return true if this scalar return value only has bits discarded on its path
  309. /// from the "tail call" to the "ret". This includes the obvious noop
  310. /// instructions handled by getNoopInput above as well as free truncations (or
  311. /// extensions prior to the call).
  312. static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
  313. SmallVectorImpl<unsigned> &RetIndices,
  314. SmallVectorImpl<unsigned> &CallIndices,
  315. bool AllowDifferingSizes,
  316. const TargetLoweringBase &TLI,
  317. const DataLayout &DL) {
  318. // Trace the sub-value needed by the return value as far back up the graph as
  319. // possible, in the hope that it will intersect with the value produced by the
  320. // call. In the simple case with no "returned" attribute, the hope is actually
  321. // that we end up back at the tail call instruction itself.
  322. unsigned BitsRequired = UINT_MAX;
  323. RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI, DL);
  324. // If this slot in the value returned is undef, it doesn't matter what the
  325. // call puts there, it'll be fine.
  326. if (isa<UndefValue>(RetVal))
  327. return true;
  328. // Now do a similar search up through the graph to find where the value
  329. // actually returned by the "tail call" comes from. In the simple case without
  330. // a "returned" attribute, the search will be blocked immediately and the loop
  331. // a Noop.
  332. unsigned BitsProvided = UINT_MAX;
  333. CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI, DL);
  334. // There's no hope if we can't actually trace them to (the same part of!) the
  335. // same value.
  336. if (CallVal != RetVal || CallIndices != RetIndices)
  337. return false;
  338. // However, intervening truncates may have made the call non-tail. Make sure
  339. // all the bits that are needed by the "ret" have been provided by the "tail
  340. // call". FIXME: with sufficiently cunning bit-tracking, we could look through
  341. // extensions too.
  342. if (BitsProvided < BitsRequired ||
  343. (!AllowDifferingSizes && BitsProvided != BitsRequired))
  344. return false;
  345. return true;
  346. }
  347. /// For an aggregate type, determine whether a given index is within bounds or
  348. /// not.
  349. static bool indexReallyValid(CompositeType *T, unsigned Idx) {
  350. if (ArrayType *AT = dyn_cast<ArrayType>(T))
  351. return Idx < AT->getNumElements();
  352. return Idx < cast<StructType>(T)->getNumElements();
  353. }
  354. /// Move the given iterators to the next leaf type in depth first traversal.
  355. ///
  356. /// Performs a depth-first traversal of the type as specified by its arguments,
  357. /// stopping at the next leaf node (which may be a legitimate scalar type or an
  358. /// empty struct or array).
  359. ///
  360. /// @param SubTypes List of the partial components making up the type from
  361. /// outermost to innermost non-empty aggregate. The element currently
  362. /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1).
  363. ///
  364. /// @param Path Set of extractvalue indices leading from the outermost type
  365. /// (SubTypes[0]) to the leaf node currently represented.
  366. ///
  367. /// @returns true if a new type was found, false otherwise. Calling this
  368. /// function again on a finished iterator will repeatedly return
  369. /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty
  370. /// aggregate or a non-aggregate
  371. static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
  372. SmallVectorImpl<unsigned> &Path) {
  373. // First march back up the tree until we can successfully increment one of the
  374. // coordinates in Path.
  375. while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
  376. Path.pop_back();
  377. SubTypes.pop_back();
  378. }
  379. // If we reached the top, then the iterator is done.
  380. if (Path.empty())
  381. return false;
  382. // We know there's *some* valid leaf now, so march back down the tree picking
  383. // out the left-most element at each node.
  384. ++Path.back();
  385. Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
  386. while (DeeperType->isAggregateType()) {
  387. CompositeType *CT = cast<CompositeType>(DeeperType);
  388. if (!indexReallyValid(CT, 0))
  389. return true;
  390. SubTypes.push_back(CT);
  391. Path.push_back(0);
  392. DeeperType = CT->getTypeAtIndex(0U);
  393. }
  394. return true;
  395. }
  396. /// Find the first non-empty, scalar-like type in Next and setup the iterator
  397. /// components.
  398. ///
  399. /// Assuming Next is an aggregate of some kind, this function will traverse the
  400. /// tree from left to right (i.e. depth-first) looking for the first
  401. /// non-aggregate type which will play a role in function return.
  402. ///
  403. /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup
  404. /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first
  405. /// i32 in that type.
  406. static bool firstRealType(Type *Next,
  407. SmallVectorImpl<CompositeType *> &SubTypes,
  408. SmallVectorImpl<unsigned> &Path) {
  409. // First initialise the iterator components to the first "leaf" node
  410. // (i.e. node with no valid sub-type at any index, so {} does count as a leaf
  411. // despite nominally being an aggregate).
  412. while (Next->isAggregateType() &&
  413. indexReallyValid(cast<CompositeType>(Next), 0)) {
  414. SubTypes.push_back(cast<CompositeType>(Next));
  415. Path.push_back(0);
  416. Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
  417. }
  418. // If there's no Path now, Next was originally scalar already (or empty
  419. // leaf). We're done.
  420. if (Path.empty())
  421. return true;
  422. // Otherwise, use normal iteration to keep looking through the tree until we
  423. // find a non-aggregate type.
  424. while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
  425. if (!advanceToNextLeafType(SubTypes, Path))
  426. return false;
  427. }
  428. return true;
  429. }
  430. /// Set the iterator data-structures to the next non-empty, non-aggregate
  431. /// subtype.
  432. static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
  433. SmallVectorImpl<unsigned> &Path) {
  434. do {
  435. if (!advanceToNextLeafType(SubTypes, Path))
  436. return false;
  437. assert(!Path.empty() && "found a leaf but didn't set the path?");
  438. } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
  439. return true;
  440. }
  441. /// Test if the given instruction is in a position to be optimized
  442. /// with a tail-call. This roughly means that it's in a block with
  443. /// a return and there's nothing that needs to be scheduled
  444. /// between it and the return.
  445. ///
  446. /// This function only tests target-independent requirements.
  447. bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) {
  448. const Instruction *I = CS.getInstruction();
  449. const BasicBlock *ExitBB = I->getParent();
  450. const TerminatorInst *Term = ExitBB->getTerminator();
  451. const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
  452. // The block must end in a return statement or unreachable.
  453. //
  454. // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
  455. // an unreachable, for now. The way tailcall optimization is currently
  456. // implemented means it will add an epilogue followed by a jump. That is
  457. // not profitable. Also, if the callee is a special function (e.g.
  458. // longjmp on x86), it can end up causing miscompilation that has not
  459. // been fully understood.
  460. if (!Ret &&
  461. (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
  462. return false;
  463. // If I will have a chain, make sure no other instruction that will have a
  464. // chain interposes between I and the return.
  465. if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
  466. !isSafeToSpeculativelyExecute(I))
  467. for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
  468. if (&*BBI == I)
  469. break;
  470. // Debug info intrinsics do not get in the way of tail call optimization.
  471. if (isa<DbgInfoIntrinsic>(BBI))
  472. continue;
  473. if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
  474. !isSafeToSpeculativelyExecute(BBI))
  475. return false;
  476. }
  477. const Function *F = ExitBB->getParent();
  478. return returnTypeIsEligibleForTailCall(
  479. F, I, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering());
  480. }
  481. bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
  482. const Instruction *I,
  483. const ReturnInst *Ret,
  484. const TargetLoweringBase &TLI) {
  485. // If the block ends with a void return or unreachable, it doesn't matter
  486. // what the call's return type is.
  487. if (!Ret || Ret->getNumOperands() == 0) return true;
  488. // If the return value is undef, it doesn't matter what the call's
  489. // return type is.
  490. if (isa<UndefValue>(Ret->getOperand(0))) return true;
  491. // Make sure the attributes attached to each return are compatible.
  492. AttrBuilder CallerAttrs(F->getAttributes(),
  493. AttributeSet::ReturnIndex);
  494. AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
  495. AttributeSet::ReturnIndex);
  496. // Noalias is completely benign as far as calling convention goes, it
  497. // shouldn't affect whether the call is a tail call.
  498. CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias);
  499. CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias);
  500. bool AllowDifferingSizes = true;
  501. if (CallerAttrs.contains(Attribute::ZExt)) {
  502. if (!CalleeAttrs.contains(Attribute::ZExt))
  503. return false;
  504. AllowDifferingSizes = false;
  505. CallerAttrs.removeAttribute(Attribute::ZExt);
  506. CalleeAttrs.removeAttribute(Attribute::ZExt);
  507. } else if (CallerAttrs.contains(Attribute::SExt)) {
  508. if (!CalleeAttrs.contains(Attribute::SExt))
  509. return false;
  510. AllowDifferingSizes = false;
  511. CallerAttrs.removeAttribute(Attribute::SExt);
  512. CalleeAttrs.removeAttribute(Attribute::SExt);
  513. }
  514. // If they're still different, there's some facet we don't understand
  515. // (currently only "inreg", but in future who knows). It may be OK but the
  516. // only safe option is to reject the tail call.
  517. if (CallerAttrs != CalleeAttrs)
  518. return false;
  519. const Value *RetVal = Ret->getOperand(0), *CallVal = I;
  520. SmallVector<unsigned, 4> RetPath, CallPath;
  521. SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
  522. bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
  523. bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
  524. // Nothing's actually returned, it doesn't matter what the callee put there
  525. // it's a valid tail call.
  526. if (RetEmpty)
  527. return true;
  528. // Iterate pairwise through each of the value types making up the tail call
  529. // and the corresponding return. For each one we want to know whether it's
  530. // essentially going directly from the tail call to the ret, via operations
  531. // that end up not generating any code.
  532. //
  533. // We allow a certain amount of covariance here. For example it's permitted
  534. // for the tail call to define more bits than the ret actually cares about
  535. // (e.g. via a truncate).
  536. do {
  537. if (CallEmpty) {
  538. // We've exhausted the values produced by the tail call instruction, the
  539. // rest are essentially undef. The type doesn't really matter, but we need
  540. // *something*.
  541. Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
  542. CallVal = UndefValue::get(SlotType);
  543. }
  544. // The manipulations performed when we're looking through an insertvalue or
  545. // an extractvalue would happen at the front of the RetPath list, so since
  546. // we have to copy it anyway it's more efficient to create a reversed copy.
  547. SmallVector<unsigned, 4> TmpRetPath(RetPath.rbegin(), RetPath.rend());
  548. SmallVector<unsigned, 4> TmpCallPath(CallPath.rbegin(), CallPath.rend());
  549. // Finally, we can check whether the value produced by the tail call at this
  550. // index is compatible with the value we return.
  551. if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
  552. AllowDifferingSizes, TLI,
  553. F->getParent()->getDataLayout()))
  554. return false;
  555. CallEmpty = !nextRealType(CallSubTypes, CallPath);
  556. } while(nextRealType(RetSubTypes, RetPath));
  557. return true;
  558. }
  559. bool llvm::canBeOmittedFromSymbolTable(const GlobalValue *GV) {
  560. if (!GV->hasLinkOnceODRLinkage())
  561. return false;
  562. if (GV->hasUnnamedAddr())
  563. return true;
  564. // If it is a non constant variable, it needs to be uniqued across shared
  565. // objects.
  566. if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
  567. if (!Var->isConstant())
  568. return false;
  569. }
  570. // An alias can point to a variable. We could try to resolve the alias to
  571. // decide, but for now just don't hide them.
  572. if (isa<GlobalAlias>(GV))
  573. return false;
  574. GlobalStatus GS;
  575. if (GlobalStatus::analyzeGlobal(GV, GS))
  576. return false;
  577. return !GS.IsCompared;
  578. }