BasicBlock.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
  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 implements the BasicBlock class for the IR library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/BasicBlock.h"
  13. #include "SymbolTableListTraitsImpl.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/IR/CFG.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/Instructions.h"
  18. #include "llvm/IR/IntrinsicInst.h"
  19. #include "llvm/IR/LLVMContext.h"
  20. #include "llvm/IR/Type.h"
  21. #include <algorithm>
  22. using namespace llvm;
  23. ValueSymbolTable *BasicBlock::getValueSymbolTable() {
  24. if (Function *F = getParent())
  25. return F->getValueSymbolTable();
  26. return nullptr;
  27. }
  28. LLVMContext &BasicBlock::getContext() const {
  29. return getType()->getContext();
  30. }
  31. // Explicit instantiation of SymbolTableListTraits since some of the methods
  32. // are not in the public header file...
  33. template class llvm::SymbolTableListTraits<Instruction>;
  34. BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
  35. BasicBlock *InsertBefore)
  36. : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
  37. if (NewParent)
  38. insertInto(NewParent, InsertBefore);
  39. else
  40. assert(!InsertBefore &&
  41. "Cannot insert block before another block with no function!");
  42. setName(Name);
  43. }
  44. void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
  45. assert(NewParent && "Expected a parent");
  46. assert(!Parent && "Already has a parent");
  47. if (InsertBefore)
  48. NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
  49. else
  50. NewParent->getBasicBlockList().push_back(this);
  51. }
  52. BasicBlock::~BasicBlock() {
  53. // If the address of the block is taken and it is being deleted (e.g. because
  54. // it is dead), this means that there is either a dangling constant expr
  55. // hanging off the block, or an undefined use of the block (source code
  56. // expecting the address of a label to keep the block alive even though there
  57. // is no indirect branch). Handle these cases by zapping the BlockAddress
  58. // nodes. There are no other possible uses at this point.
  59. if (hasAddressTaken()) {
  60. assert(!use_empty() && "There should be at least one blockaddress!");
  61. Constant *Replacement =
  62. ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
  63. while (!use_empty()) {
  64. BlockAddress *BA = cast<BlockAddress>(user_back());
  65. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  66. BA->getType()));
  67. BA->destroyConstant();
  68. }
  69. }
  70. assert(getParent() == nullptr && "BasicBlock still linked into the program!");
  71. dropAllReferences();
  72. InstList.clear();
  73. }
  74. void BasicBlock::setParent(Function *parent) {
  75. // Set Parent=parent, updating instruction symtab entries as appropriate.
  76. InstList.setSymTabObject(&Parent, parent);
  77. }
  78. iterator_range<filter_iterator<BasicBlock::const_iterator,
  79. std::function<bool(const Instruction &)>>>
  80. BasicBlock::instructionsWithoutDebug() const {
  81. std::function<bool(const Instruction &)> Fn = [](const Instruction &I) {
  82. return !isa<DbgInfoIntrinsic>(I);
  83. };
  84. return make_filter_range(*this, Fn);
  85. }
  86. iterator_range<filter_iterator<BasicBlock::iterator,
  87. std::function<bool(Instruction &)>>>
  88. BasicBlock::instructionsWithoutDebug() {
  89. std::function<bool(Instruction &)> Fn = [](Instruction &I) {
  90. return !isa<DbgInfoIntrinsic>(I);
  91. };
  92. return make_filter_range(*this, Fn);
  93. }
  94. void BasicBlock::removeFromParent() {
  95. getParent()->getBasicBlockList().remove(getIterator());
  96. }
  97. iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
  98. return getParent()->getBasicBlockList().erase(getIterator());
  99. }
  100. /// Unlink this basic block from its current function and
  101. /// insert it into the function that MovePos lives in, right before MovePos.
  102. void BasicBlock::moveBefore(BasicBlock *MovePos) {
  103. MovePos->getParent()->getBasicBlockList().splice(
  104. MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
  105. }
  106. /// Unlink this basic block from its current function and
  107. /// insert it into the function that MovePos lives in, right after MovePos.
  108. void BasicBlock::moveAfter(BasicBlock *MovePos) {
  109. MovePos->getParent()->getBasicBlockList().splice(
  110. ++MovePos->getIterator(), getParent()->getBasicBlockList(),
  111. getIterator());
  112. }
  113. const Module *BasicBlock::getModule() const {
  114. return getParent()->getParent();
  115. }
  116. const Instruction *BasicBlock::getTerminator() const {
  117. if (InstList.empty() || !InstList.back().isTerminator())
  118. return nullptr;
  119. return &InstList.back();
  120. }
  121. const CallInst *BasicBlock::getTerminatingMustTailCall() const {
  122. if (InstList.empty())
  123. return nullptr;
  124. const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
  125. if (!RI || RI == &InstList.front())
  126. return nullptr;
  127. const Instruction *Prev = RI->getPrevNode();
  128. if (!Prev)
  129. return nullptr;
  130. if (Value *RV = RI->getReturnValue()) {
  131. if (RV != Prev)
  132. return nullptr;
  133. // Look through the optional bitcast.
  134. if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
  135. RV = BI->getOperand(0);
  136. Prev = BI->getPrevNode();
  137. if (!Prev || RV != Prev)
  138. return nullptr;
  139. }
  140. }
  141. if (auto *CI = dyn_cast<CallInst>(Prev)) {
  142. if (CI->isMustTailCall())
  143. return CI;
  144. }
  145. return nullptr;
  146. }
  147. const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
  148. if (InstList.empty())
  149. return nullptr;
  150. auto *RI = dyn_cast<ReturnInst>(&InstList.back());
  151. if (!RI || RI == &InstList.front())
  152. return nullptr;
  153. if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
  154. if (Function *F = CI->getCalledFunction())
  155. if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
  156. return CI;
  157. return nullptr;
  158. }
  159. const Instruction* BasicBlock::getFirstNonPHI() const {
  160. for (const Instruction &I : *this)
  161. if (!isa<PHINode>(I))
  162. return &I;
  163. return nullptr;
  164. }
  165. const Instruction* BasicBlock::getFirstNonPHIOrDbg() const {
  166. for (const Instruction &I : *this)
  167. if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
  168. return &I;
  169. return nullptr;
  170. }
  171. const Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() const {
  172. for (const Instruction &I : *this) {
  173. if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
  174. continue;
  175. if (I.isLifetimeStartOrEnd())
  176. continue;
  177. return &I;
  178. }
  179. return nullptr;
  180. }
  181. BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
  182. const Instruction *FirstNonPHI = getFirstNonPHI();
  183. if (!FirstNonPHI)
  184. return end();
  185. const_iterator InsertPt = FirstNonPHI->getIterator();
  186. if (InsertPt->isEHPad()) ++InsertPt;
  187. return InsertPt;
  188. }
  189. void BasicBlock::dropAllReferences() {
  190. for (Instruction &I : *this)
  191. I.dropAllReferences();
  192. }
  193. /// If this basic block has a single predecessor block,
  194. /// return the block, otherwise return a null pointer.
  195. const BasicBlock *BasicBlock::getSinglePredecessor() const {
  196. const_pred_iterator PI = pred_begin(this), E = pred_end(this);
  197. if (PI == E) return nullptr; // No preds.
  198. const BasicBlock *ThePred = *PI;
  199. ++PI;
  200. return (PI == E) ? ThePred : nullptr /*multiple preds*/;
  201. }
  202. /// If this basic block has a unique predecessor block,
  203. /// return the block, otherwise return a null pointer.
  204. /// Note that unique predecessor doesn't mean single edge, there can be
  205. /// multiple edges from the unique predecessor to this block (for example
  206. /// a switch statement with multiple cases having the same destination).
  207. const BasicBlock *BasicBlock::getUniquePredecessor() const {
  208. const_pred_iterator PI = pred_begin(this), E = pred_end(this);
  209. if (PI == E) return nullptr; // No preds.
  210. const BasicBlock *PredBB = *PI;
  211. ++PI;
  212. for (;PI != E; ++PI) {
  213. if (*PI != PredBB)
  214. return nullptr;
  215. // The same predecessor appears multiple times in the predecessor list.
  216. // This is OK.
  217. }
  218. return PredBB;
  219. }
  220. bool BasicBlock::hasNPredecessors(unsigned N) const {
  221. return hasNItems(pred_begin(this), pred_end(this), N);
  222. }
  223. bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
  224. return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
  225. }
  226. const BasicBlock *BasicBlock::getSingleSuccessor() const {
  227. succ_const_iterator SI = succ_begin(this), E = succ_end(this);
  228. if (SI == E) return nullptr; // no successors
  229. const BasicBlock *TheSucc = *SI;
  230. ++SI;
  231. return (SI == E) ? TheSucc : nullptr /* multiple successors */;
  232. }
  233. const BasicBlock *BasicBlock::getUniqueSuccessor() const {
  234. succ_const_iterator SI = succ_begin(this), E = succ_end(this);
  235. if (SI == E) return nullptr; // No successors
  236. const BasicBlock *SuccBB = *SI;
  237. ++SI;
  238. for (;SI != E; ++SI) {
  239. if (*SI != SuccBB)
  240. return nullptr;
  241. // The same successor appears multiple times in the successor list.
  242. // This is OK.
  243. }
  244. return SuccBB;
  245. }
  246. iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
  247. PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
  248. return make_range<phi_iterator>(P, nullptr);
  249. }
  250. /// This method is used to notify a BasicBlock that the
  251. /// specified Predecessor of the block is no longer able to reach it. This is
  252. /// actually not used to update the Predecessor list, but is actually used to
  253. /// update the PHI nodes that reside in the block. Note that this should be
  254. /// called while the predecessor still refers to this block.
  255. ///
  256. void BasicBlock::removePredecessor(BasicBlock *Pred,
  257. bool KeepOneInputPHIs) {
  258. assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
  259. find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
  260. "removePredecessor: BB is not a predecessor!");
  261. if (InstList.empty()) return;
  262. PHINode *APN = dyn_cast<PHINode>(&front());
  263. if (!APN) return; // Quick exit.
  264. // If there are exactly two predecessors, then we want to nuke the PHI nodes
  265. // altogether. However, we cannot do this, if this in this case:
  266. //
  267. // Loop:
  268. // %x = phi [X, Loop]
  269. // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
  270. // br Loop ;; %x2 does not dominate all uses
  271. //
  272. // This is because the PHI node input is actually taken from the predecessor
  273. // basic block. The only case this can happen is with a self loop, so we
  274. // check for this case explicitly now.
  275. //
  276. unsigned max_idx = APN->getNumIncomingValues();
  277. assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
  278. if (max_idx == 2) {
  279. BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
  280. // Disable PHI elimination!
  281. if (this == Other) max_idx = 3;
  282. }
  283. // <= Two predecessors BEFORE I remove one?
  284. if (max_idx <= 2 && !KeepOneInputPHIs) {
  285. // Yup, loop through and nuke the PHI nodes
  286. while (PHINode *PN = dyn_cast<PHINode>(&front())) {
  287. // Remove the predecessor first.
  288. PN->removeIncomingValue(Pred, !KeepOneInputPHIs);
  289. // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
  290. if (max_idx == 2) {
  291. if (PN->getIncomingValue(0) != PN)
  292. PN->replaceAllUsesWith(PN->getIncomingValue(0));
  293. else
  294. // We are left with an infinite loop with no entries: kill the PHI.
  295. PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
  296. getInstList().pop_front(); // Remove the PHI node
  297. }
  298. // If the PHI node already only had one entry, it got deleted by
  299. // removeIncomingValue.
  300. }
  301. } else {
  302. // Okay, now we know that we need to remove predecessor #pred_idx from all
  303. // PHI nodes. Iterate over each PHI node fixing them up
  304. PHINode *PN;
  305. for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
  306. ++II;
  307. PN->removeIncomingValue(Pred, false);
  308. // If all incoming values to the Phi are the same, we can replace the Phi
  309. // with that value.
  310. Value* PNV = nullptr;
  311. if (!KeepOneInputPHIs && (PNV = PN->hasConstantValue()))
  312. if (PNV != PN) {
  313. PN->replaceAllUsesWith(PNV);
  314. PN->eraseFromParent();
  315. }
  316. }
  317. }
  318. }
  319. bool BasicBlock::canSplitPredecessors() const {
  320. const Instruction *FirstNonPHI = getFirstNonPHI();
  321. if (isa<LandingPadInst>(FirstNonPHI))
  322. return true;
  323. // This is perhaps a little conservative because constructs like
  324. // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors
  325. // cannot handle such things just yet.
  326. if (FirstNonPHI->isEHPad())
  327. return false;
  328. return true;
  329. }
  330. bool BasicBlock::isLegalToHoistInto() const {
  331. auto *Term = getTerminator();
  332. // No terminator means the block is under construction.
  333. if (!Term)
  334. return true;
  335. // If the block has no successors, there can be no instructions to hoist.
  336. assert(Term->getNumSuccessors() > 0);
  337. // Instructions should not be hoisted across exception handling boundaries.
  338. return !Term->isExceptionalTerminator();
  339. }
  340. /// This splits a basic block into two at the specified
  341. /// instruction. Note that all instructions BEFORE the specified iterator stay
  342. /// as part of the original basic block, an unconditional branch is added to
  343. /// the new BB, and the rest of the instructions in the BB are moved to the new
  344. /// BB, including the old terminator. This invalidates the iterator.
  345. ///
  346. /// Note that this only works on well formed basic blocks (must have a
  347. /// terminator), and 'I' must not be the end of instruction list (which would
  348. /// cause a degenerate basic block to be formed, having a terminator inside of
  349. /// the basic block).
  350. ///
  351. BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
  352. assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
  353. assert(I != InstList.end() &&
  354. "Trying to get me to create degenerate basic block!");
  355. BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
  356. this->getNextNode());
  357. // Save DebugLoc of split point before invalidating iterator.
  358. DebugLoc Loc = I->getDebugLoc();
  359. // Move all of the specified instructions from the original basic block into
  360. // the new basic block.
  361. New->getInstList().splice(New->end(), this->getInstList(), I, end());
  362. // Add a branch instruction to the newly formed basic block.
  363. BranchInst *BI = BranchInst::Create(New, this);
  364. BI->setDebugLoc(Loc);
  365. // Now we must loop through all of the successors of the New block (which
  366. // _were_ the successors of the 'this' block), and update any PHI nodes in
  367. // successors. If there were PHI nodes in the successors, then they need to
  368. // know that incoming branches will be from New, not from Old (this).
  369. //
  370. New->replaceSuccessorsPhiUsesWith(this, New);
  371. return New;
  372. }
  373. void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
  374. // N.B. This might not be a complete BasicBlock, so don't assume
  375. // that it ends with a non-phi instruction.
  376. for (iterator II = begin(), IE = end(); II != IE; ++II) {
  377. PHINode *PN = dyn_cast<PHINode>(II);
  378. if (!PN)
  379. break;
  380. PN->replaceIncomingBlockWith(Old, New);
  381. }
  382. }
  383. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
  384. BasicBlock *New) {
  385. Instruction *TI = getTerminator();
  386. if (!TI)
  387. // Cope with being called on a BasicBlock that doesn't have a terminator
  388. // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
  389. return;
  390. llvm::for_each(successors(TI), [Old, New](BasicBlock *Succ) {
  391. Succ->replacePhiUsesWith(Old, New);
  392. });
  393. }
  394. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
  395. this->replaceSuccessorsPhiUsesWith(this, New);
  396. }
  397. /// Return true if this basic block is a landing pad. I.e., it's
  398. /// the destination of the 'unwind' edge of an invoke instruction.
  399. bool BasicBlock::isLandingPad() const {
  400. return isa<LandingPadInst>(getFirstNonPHI());
  401. }
  402. /// Return the landingpad instruction associated with the landing pad.
  403. const LandingPadInst *BasicBlock::getLandingPadInst() const {
  404. return dyn_cast<LandingPadInst>(getFirstNonPHI());
  405. }
  406. Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
  407. const Instruction *TI = getTerminator();
  408. if (MDNode *MDIrrLoopHeader =
  409. TI->getMetadata(LLVMContext::MD_irr_loop)) {
  410. MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
  411. if (MDName->getString().equals("loop_header_weight")) {
  412. auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
  413. return Optional<uint64_t>(CI->getValue().getZExtValue());
  414. }
  415. }
  416. return Optional<uint64_t>();
  417. }
  418. BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
  419. while (isa<DbgInfoIntrinsic>(It))
  420. ++It;
  421. return It;
  422. }