Analysis.cpp 33 KB

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