BasicBlock.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {
  32. BB->invalidateOrders();
  33. }
  34. // Explicit instantiation of SymbolTableListTraits since some of the methods
  35. // are not in the public header file...
  36. template class llvm::SymbolTableListTraits<Instruction>;
  37. BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
  38. BasicBlock *InsertBefore)
  39. : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
  40. if (NewParent)
  41. insertInto(NewParent, InsertBefore);
  42. else
  43. assert(!InsertBefore &&
  44. "Cannot insert block before another block with no function!");
  45. setName(Name);
  46. }
  47. void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
  48. assert(NewParent && "Expected a parent");
  49. assert(!Parent && "Already has a parent");
  50. if (InsertBefore)
  51. NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
  52. else
  53. NewParent->getBasicBlockList().push_back(this);
  54. }
  55. BasicBlock::~BasicBlock() {
  56. validateInstrOrdering();
  57. // If the address of the block is taken and it is being deleted (e.g. because
  58. // it is dead), this means that there is either a dangling constant expr
  59. // hanging off the block, or an undefined use of the block (source code
  60. // expecting the address of a label to keep the block alive even though there
  61. // is no indirect branch). Handle these cases by zapping the BlockAddress
  62. // nodes. There are no other possible uses at this point.
  63. if (hasAddressTaken()) {
  64. assert(!use_empty() && "There should be at least one blockaddress!");
  65. Constant *Replacement =
  66. ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
  67. while (!use_empty()) {
  68. BlockAddress *BA = cast<BlockAddress>(user_back());
  69. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  70. BA->getType()));
  71. BA->destroyConstant();
  72. }
  73. }
  74. assert(getParent() == nullptr && "BasicBlock still linked into the program!");
  75. dropAllReferences();
  76. InstList.clear();
  77. }
  78. void BasicBlock::setParent(Function *parent) {
  79. // Set Parent=parent, updating instruction symtab entries as appropriate.
  80. InstList.setSymTabObject(&Parent, parent);
  81. }
  82. iterator_range<filter_iterator<BasicBlock::const_iterator,
  83. std::function<bool(const Instruction &)>>>
  84. BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const {
  85. std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) {
  86. return !isa<DbgInfoIntrinsic>(I) &&
  87. !(SkipPseudoOp && isa<PseudoProbeInst>(I));
  88. };
  89. return make_filter_range(*this, Fn);
  90. }
  91. iterator_range<
  92. filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
  93. BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) {
  94. std::function<bool(Instruction &)> Fn = [=](Instruction &I) {
  95. return !isa<DbgInfoIntrinsic>(I) &&
  96. !(SkipPseudoOp && isa<PseudoProbeInst>(I));
  97. };
  98. return make_filter_range(*this, Fn);
  99. }
  100. filter_iterator<BasicBlock::const_iterator,
  101. std::function<bool(const Instruction &)>>::difference_type
  102. BasicBlock::sizeWithoutDebug() const {
  103. return std::distance(instructionsWithoutDebug().begin(),
  104. instructionsWithoutDebug().end());
  105. }
  106. void BasicBlock::removeFromParent() {
  107. getParent()->getBasicBlockList().remove(getIterator());
  108. }
  109. iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
  110. return getParent()->getBasicBlockList().erase(getIterator());
  111. }
  112. void BasicBlock::moveBefore(BasicBlock *MovePos) {
  113. MovePos->getParent()->getBasicBlockList().splice(
  114. MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
  115. }
  116. void BasicBlock::moveAfter(BasicBlock *MovePos) {
  117. MovePos->getParent()->getBasicBlockList().splice(
  118. ++MovePos->getIterator(), getParent()->getBasicBlockList(),
  119. getIterator());
  120. }
  121. const Module *BasicBlock::getModule() const {
  122. return getParent()->getParent();
  123. }
  124. const Instruction *BasicBlock::getTerminator() const {
  125. if (InstList.empty() || !InstList.back().isTerminator())
  126. return nullptr;
  127. return &InstList.back();
  128. }
  129. const CallInst *BasicBlock::getTerminatingMustTailCall() const {
  130. if (InstList.empty())
  131. return nullptr;
  132. const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
  133. if (!RI || RI == &InstList.front())
  134. return nullptr;
  135. const Instruction *Prev = RI->getPrevNode();
  136. if (!Prev)
  137. return nullptr;
  138. if (Value *RV = RI->getReturnValue()) {
  139. if (RV != Prev)
  140. return nullptr;
  141. // Look through the optional bitcast.
  142. if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
  143. RV = BI->getOperand(0);
  144. Prev = BI->getPrevNode();
  145. if (!Prev || RV != Prev)
  146. return nullptr;
  147. }
  148. }
  149. if (auto *CI = dyn_cast<CallInst>(Prev)) {
  150. if (CI->isMustTailCall())
  151. return CI;
  152. }
  153. return nullptr;
  154. }
  155. const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
  156. if (InstList.empty())
  157. return nullptr;
  158. auto *RI = dyn_cast<ReturnInst>(&InstList.back());
  159. if (!RI || RI == &InstList.front())
  160. return nullptr;
  161. if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
  162. if (Function *F = CI->getCalledFunction())
  163. if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
  164. return CI;
  165. return nullptr;
  166. }
  167. const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
  168. const BasicBlock* BB = this;
  169. SmallPtrSet<const BasicBlock *, 8> Visited;
  170. Visited.insert(BB);
  171. while (auto *Succ = BB->getUniqueSuccessor()) {
  172. if (!Visited.insert(Succ).second)
  173. return nullptr;
  174. BB = Succ;
  175. }
  176. return BB->getTerminatingDeoptimizeCall();
  177. }
  178. const Instruction* BasicBlock::getFirstNonPHI() const {
  179. for (const Instruction &I : *this)
  180. if (!isa<PHINode>(I))
  181. return &I;
  182. return nullptr;
  183. }
  184. const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {
  185. for (const Instruction &I : *this) {
  186. if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
  187. continue;
  188. if (SkipPseudoOp && isa<PseudoProbeInst>(I))
  189. continue;
  190. return &I;
  191. }
  192. return nullptr;
  193. }
  194. const Instruction *
  195. BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {
  196. for (const Instruction &I : *this) {
  197. if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
  198. continue;
  199. if (I.isLifetimeStartOrEnd())
  200. continue;
  201. if (SkipPseudoOp && isa<PseudoProbeInst>(I))
  202. continue;
  203. return &I;
  204. }
  205. return nullptr;
  206. }
  207. BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
  208. const Instruction *FirstNonPHI = getFirstNonPHI();
  209. if (!FirstNonPHI)
  210. return end();
  211. const_iterator InsertPt = FirstNonPHI->getIterator();
  212. if (InsertPt->isEHPad()) ++InsertPt;
  213. return InsertPt;
  214. }
  215. void BasicBlock::dropAllReferences() {
  216. for (Instruction &I : *this)
  217. I.dropAllReferences();
  218. }
  219. const BasicBlock *BasicBlock::getSinglePredecessor() const {
  220. const_pred_iterator PI = pred_begin(this), E = pred_end(this);
  221. if (PI == E) return nullptr; // No preds.
  222. const BasicBlock *ThePred = *PI;
  223. ++PI;
  224. return (PI == E) ? ThePred : nullptr /*multiple preds*/;
  225. }
  226. const BasicBlock *BasicBlock::getUniquePredecessor() const {
  227. const_pred_iterator PI = pred_begin(this), E = pred_end(this);
  228. if (PI == E) return nullptr; // No preds.
  229. const BasicBlock *PredBB = *PI;
  230. ++PI;
  231. for (;PI != E; ++PI) {
  232. if (*PI != PredBB)
  233. return nullptr;
  234. // The same predecessor appears multiple times in the predecessor list.
  235. // This is OK.
  236. }
  237. return PredBB;
  238. }
  239. bool BasicBlock::hasNPredecessors(unsigned N) const {
  240. return hasNItems(pred_begin(this), pred_end(this), N);
  241. }
  242. bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
  243. return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
  244. }
  245. const BasicBlock *BasicBlock::getSingleSuccessor() const {
  246. const_succ_iterator SI = succ_begin(this), E = succ_end(this);
  247. if (SI == E) return nullptr; // no successors
  248. const BasicBlock *TheSucc = *SI;
  249. ++SI;
  250. return (SI == E) ? TheSucc : nullptr /* multiple successors */;
  251. }
  252. const BasicBlock *BasicBlock::getUniqueSuccessor() const {
  253. const_succ_iterator SI = succ_begin(this), E = succ_end(this);
  254. if (SI == E) return nullptr; // No successors
  255. const BasicBlock *SuccBB = *SI;
  256. ++SI;
  257. for (;SI != E; ++SI) {
  258. if (*SI != SuccBB)
  259. return nullptr;
  260. // The same successor appears multiple times in the successor list.
  261. // This is OK.
  262. }
  263. return SuccBB;
  264. }
  265. iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
  266. PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
  267. return make_range<phi_iterator>(P, nullptr);
  268. }
  269. void BasicBlock::removePredecessor(BasicBlock *Pred,
  270. bool KeepOneInputPHIs) {
  271. // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
  272. assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
  273. "Pred is not a predecessor!");
  274. // Return early if there are no PHI nodes to update.
  275. if (empty() || !isa<PHINode>(begin()))
  276. return;
  277. unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
  278. for (PHINode &Phi : make_early_inc_range(phis())) {
  279. Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
  280. if (KeepOneInputPHIs)
  281. continue;
  282. // If we have a single predecessor, removeIncomingValue may have erased the
  283. // PHI node itself.
  284. if (NumPreds == 1)
  285. continue;
  286. // Try to replace the PHI node with a constant value.
  287. if (Value *PhiConstant = Phi.hasConstantValue()) {
  288. Phi.replaceAllUsesWith(PhiConstant);
  289. Phi.eraseFromParent();
  290. }
  291. }
  292. }
  293. bool BasicBlock::canSplitPredecessors() const {
  294. const Instruction *FirstNonPHI = getFirstNonPHI();
  295. if (isa<LandingPadInst>(FirstNonPHI))
  296. return true;
  297. // This is perhaps a little conservative because constructs like
  298. // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors
  299. // cannot handle such things just yet.
  300. if (FirstNonPHI->isEHPad())
  301. return false;
  302. return true;
  303. }
  304. bool BasicBlock::isLegalToHoistInto() const {
  305. auto *Term = getTerminator();
  306. // No terminator means the block is under construction.
  307. if (!Term)
  308. return true;
  309. // If the block has no successors, there can be no instructions to hoist.
  310. assert(Term->getNumSuccessors() > 0);
  311. // Instructions should not be hoisted across exception handling boundaries.
  312. return !Term->isExceptionalTerminator();
  313. }
  314. BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,
  315. bool Before) {
  316. if (Before)
  317. return splitBasicBlockBefore(I, BBName);
  318. assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
  319. assert(I != InstList.end() &&
  320. "Trying to get me to create degenerate basic block!");
  321. BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
  322. this->getNextNode());
  323. // Save DebugLoc of split point before invalidating iterator.
  324. DebugLoc Loc = I->getDebugLoc();
  325. // Move all of the specified instructions from the original basic block into
  326. // the new basic block.
  327. New->getInstList().splice(New->end(), this->getInstList(), I, end());
  328. // Add a branch instruction to the newly formed basic block.
  329. BranchInst *BI = BranchInst::Create(New, this);
  330. BI->setDebugLoc(Loc);
  331. // Now we must loop through all of the successors of the New block (which
  332. // _were_ the successors of the 'this' block), and update any PHI nodes in
  333. // successors. If there were PHI nodes in the successors, then they need to
  334. // know that incoming branches will be from New, not from Old (this).
  335. //
  336. New->replaceSuccessorsPhiUsesWith(this, New);
  337. return New;
  338. }
  339. BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
  340. assert(getTerminator() &&
  341. "Can't use splitBasicBlockBefore on degenerate BB!");
  342. assert(I != InstList.end() &&
  343. "Trying to get me to create degenerate basic block!");
  344. assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&
  345. "cannot split on multi incoming phis");
  346. BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);
  347. // Save DebugLoc of split point before invalidating iterator.
  348. DebugLoc Loc = I->getDebugLoc();
  349. // Move all of the specified instructions from the original basic block into
  350. // the new basic block.
  351. New->getInstList().splice(New->end(), this->getInstList(), begin(), I);
  352. // Loop through all of the predecessors of the 'this' block (which will be the
  353. // predecessors of the New block), replace the specified successor 'this'
  354. // block to point at the New block and update any PHI nodes in 'this' block.
  355. // If there were PHI nodes in 'this' block, the PHI nodes are updated
  356. // to reflect that the incoming branches will be from the New block and not
  357. // from predecessors of the 'this' block.
  358. for (BasicBlock *Pred : predecessors(this)) {
  359. Instruction *TI = Pred->getTerminator();
  360. TI->replaceSuccessorWith(this, New);
  361. this->replacePhiUsesWith(Pred, New);
  362. }
  363. // Add a branch instruction from "New" to "this" Block.
  364. BranchInst *BI = BranchInst::Create(this, New);
  365. BI->setDebugLoc(Loc);
  366. return New;
  367. }
  368. void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
  369. // N.B. This might not be a complete BasicBlock, so don't assume
  370. // that it ends with a non-phi instruction.
  371. for (iterator II = begin(), IE = end(); II != IE; ++II) {
  372. PHINode *PN = dyn_cast<PHINode>(II);
  373. if (!PN)
  374. break;
  375. PN->replaceIncomingBlockWith(Old, New);
  376. }
  377. }
  378. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
  379. BasicBlock *New) {
  380. Instruction *TI = getTerminator();
  381. if (!TI)
  382. // Cope with being called on a BasicBlock that doesn't have a terminator
  383. // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
  384. return;
  385. llvm::for_each(successors(TI), [Old, New](BasicBlock *Succ) {
  386. Succ->replacePhiUsesWith(Old, New);
  387. });
  388. }
  389. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
  390. this->replaceSuccessorsPhiUsesWith(this, New);
  391. }
  392. bool BasicBlock::isLandingPad() const {
  393. return isa<LandingPadInst>(getFirstNonPHI());
  394. }
  395. const LandingPadInst *BasicBlock::getLandingPadInst() const {
  396. return dyn_cast<LandingPadInst>(getFirstNonPHI());
  397. }
  398. Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
  399. const Instruction *TI = getTerminator();
  400. if (MDNode *MDIrrLoopHeader =
  401. TI->getMetadata(LLVMContext::MD_irr_loop)) {
  402. MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
  403. if (MDName->getString().equals("loop_header_weight")) {
  404. auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
  405. return Optional<uint64_t>(CI->getValue().getZExtValue());
  406. }
  407. }
  408. return Optional<uint64_t>();
  409. }
  410. BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
  411. while (isa<DbgInfoIntrinsic>(It))
  412. ++It;
  413. return It;
  414. }
  415. void BasicBlock::renumberInstructions() {
  416. unsigned Order = 0;
  417. for (Instruction &I : *this)
  418. I.Order = Order++;
  419. // Set the bit to indicate that the instruction order valid and cached.
  420. BasicBlockBits Bits = getBasicBlockBits();
  421. Bits.InstrOrderValid = true;
  422. setBasicBlockBits(Bits);
  423. }
  424. #ifndef NDEBUG
  425. /// In asserts builds, this checks the numbering. In non-asserts builds, it
  426. /// is defined as a no-op inline function in BasicBlock.h.
  427. void BasicBlock::validateInstrOrdering() const {
  428. if (!isInstrOrderValid())
  429. return;
  430. const Instruction *Prev = nullptr;
  431. for (const Instruction &I : *this) {
  432. assert((!Prev || Prev->comesBefore(&I)) &&
  433. "cached instruction ordering is incorrect");
  434. Prev = &I;
  435. }
  436. }
  437. #endif