Analysis.cpp 32 KB

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