Analysis.cpp 29 KB

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