blob: 375924360dda8321e2b8518b7382037eab679ab3 [file] [log] [blame]
Chris Lattnerd1e693f2002-09-08 18:59:35 +00001//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chandler Carruthc2c50cd2013-01-02 09:10:48 +000010// This file implements the BasicBlock class for the IR library.
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000014#include "llvm/IR/BasicBlock.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "SymbolTableListTraitsImpl.h"
16#include "llvm/ADT/STLExtras.h"
Chandler Carruth03e36d72014-03-04 11:45:46 +000017#include "llvm/IR/CFG.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/Constants.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/IR/IntrinsicInst.h"
21#include "llvm/IR/LLVMContext.h"
22#include "llvm/IR/Type.h"
Chris Lattner7e708292002-06-25 16:13:24 +000023#include <algorithm>
Hans Wennborg4d651e42015-10-06 23:24:35 +000024
Chris Lattner108e4ab2003-11-21 16:52:05 +000025using namespace llvm;
Chris Lattner00950542001-06-06 20:29:01 +000026
Gabor Greif0dd2a6a2009-03-07 12:33:24 +000027ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28 if (Function *F = getParent())
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +000029 return F->getValueSymbolTable();
Craig Topperec0f0bc2014-04-09 06:08:46 +000030 return nullptr;
Chris Lattner17fcdd52007-04-17 03:26:42 +000031}
32
Owen Andersone922c022009-07-22 00:24:57 +000033LLVMContext &BasicBlock::getContext() const {
34 return getType()->getContext();
Owen Anderson0a205a42009-07-05 22:41:43 +000035}
36
Chris Lattner7e708292002-06-25 16:13:24 +000037// Explicit instantiation of SymbolTableListTraits since some of the methods
38// are not in the public header file...
Duncan P. N. Exon Smith2a8bcfa2015-10-07 20:05:10 +000039template class llvm::SymbolTableListTraits<Instruction>;
Chris Lattner7e708292002-06-25 16:13:24 +000040
Owen Anderson1d0be152009-08-13 21:58:54 +000041BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
Nick Lewycky280a6e62008-04-25 16:53:59 +000042 BasicBlock *InsertBefore)
Craig Topperec0f0bc2014-04-09 06:08:46 +000043 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
Chris Lattner0a1a8742002-09-26 05:03:22 +000044
Duncan P. N. Exon Smith865919d2014-08-01 21:22:04 +000045 if (NewParent)
46 insertInto(NewParent, InsertBefore);
47 else
48 assert(!InsertBefore &&
Chris Lattner4f056112004-02-04 03:57:50 +000049 "Cannot insert block before another block with no function!");
NAKAMURA Takumi8fc9b3d2011-08-09 23:12:56 +000050
Chris Lattnerdec628e2007-02-12 05:18:08 +000051 setName(Name);
Chris Lattner0a1a8742002-09-26 05:03:22 +000052}
53
Duncan P. N. Exon Smith865919d2014-08-01 21:22:04 +000054void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
55 assert(NewParent && "Expected a parent");
56 assert(!Parent && "Already has a parent");
57
58 if (InsertBefore)
Duncan P. N. Exon Smitheac30952015-10-08 23:49:46 +000059 NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
Duncan P. N. Exon Smith865919d2014-08-01 21:22:04 +000060 else
61 NewParent->getBasicBlockList().push_back(this);
62}
Bill Wendling5d7a5a42011-04-10 23:18:04 +000063
Gordon Henriksenafba8fe662007-12-10 02:14:30 +000064BasicBlock::~BasicBlock() {
Chris Lattnerdac8bde2009-10-30 22:39:36 +000065 // If the address of the block is taken and it is being deleted (e.g. because
66 // it is dead), this means that there is either a dangling constant expr
67 // hanging off the block, or an undefined use of the block (source code
68 // expecting the address of a label to keep the block alive even though there
69 // is no indirect branch). Handle these cases by zapping the BlockAddress
Chris Lattnercdfc9402009-11-01 01:27:45 +000070 // nodes. There are no other possible uses at this point.
Chris Lattnerdac8bde2009-10-30 22:39:36 +000071 if (hasAddressTaken()) {
72 assert(!use_empty() && "There should be at least one blockaddress!");
Chris Lattnercdfc9402009-11-01 01:27:45 +000073 Constant *Replacement =
74 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
Chris Lattnerdac8bde2009-10-30 22:39:36 +000075 while (!use_empty()) {
Chandler Carruth36b699f2014-03-09 03:16:01 +000076 BlockAddress *BA = cast<BlockAddress>(user_back());
Chris Lattnercdfc9402009-11-01 01:27:45 +000077 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
78 BA->getType()));
Chris Lattnerdac8bde2009-10-30 22:39:36 +000079 BA->destroyConstant();
80 }
81 }
NAKAMURA Takumi8fc9b3d2011-08-09 23:12:56 +000082
Craig Topper0b6cb712014-04-15 06:32:26 +000083 assert(getParent() == nullptr && "BasicBlock still linked into the program!");
Gordon Henriksenafba8fe662007-12-10 02:14:30 +000084 dropAllReferences();
85 InstList.clear();
Chris Lattner00950542001-06-06 20:29:01 +000086}
87
Chris Lattnerbded1322002-09-06 21:33:15 +000088void BasicBlock::setParent(Function *parent) {
Chris Lattner17fcdd52007-04-17 03:26:42 +000089 // Set Parent=parent, updating instruction symtab entries as appropriate.
90 InstList.setSymTabObject(&Parent, parent);
Chris Lattnerbded1322002-09-06 21:33:15 +000091}
92
Florian Hahn848303c2018-04-19 09:48:07 +000093iterator_range<filter_iterator<BasicBlock::const_iterator,
94 std::function<bool(const Instruction &)>>>
95BasicBlock::instructionsWithoutDebug() const {
96 std::function<bool(const Instruction &)> Fn = [](const Instruction &I) {
97 return !isa<DbgInfoIntrinsic>(I);
98 };
99 return make_filter_range(*this, Fn);
100}
101
102iterator_range<filter_iterator<BasicBlock::iterator,
103 std::function<bool(Instruction &)>>>
104BasicBlock::instructionsWithoutDebug() {
105 std::function<bool(Instruction &)> Fn = [](Instruction &I) {
106 return !isa<DbgInfoIntrinsic>(I);
107 };
108 return make_filter_range(*this, Fn);
109}
110
Chris Lattner4b833802004-10-11 22:21:39 +0000111void BasicBlock::removeFromParent() {
Duncan P. N. Exon Smitheac30952015-10-08 23:49:46 +0000112 getParent()->getBasicBlockList().remove(getIterator());
Chris Lattner4b833802004-10-11 22:21:39 +0000113}
114
Daniel Berlincc6ce082015-04-03 01:20:33 +0000115iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
Duncan P. N. Exon Smitheac30952015-10-08 23:49:46 +0000116 return getParent()->getBasicBlockList().erase(getIterator());
Chris Lattner4b833802004-10-11 22:21:39 +0000117}
118
Sanjay Patel4ed780a2015-02-27 18:07:41 +0000119/// Unlink this basic block from its current function and
Chris Lattnera71965b2006-09-23 04:03:45 +0000120/// insert it into the function that MovePos lives in, right before MovePos.
Chris Lattner6a13aed2005-08-12 22:14:06 +0000121void BasicBlock::moveBefore(BasicBlock *MovePos) {
Duncan P. N. Exon Smitheac30952015-10-08 23:49:46 +0000122 MovePos->getParent()->getBasicBlockList().splice(
123 MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
Chris Lattner6a13aed2005-08-12 22:14:06 +0000124}
125
Sanjay Patel4ed780a2015-02-27 18:07:41 +0000126/// Unlink this basic block from its current function and
Chris Lattnera71965b2006-09-23 04:03:45 +0000127/// insert it into the function that MovePos lives in, right after MovePos.
128void BasicBlock::moveAfter(BasicBlock *MovePos) {
Duncan P. N. Exon Smitheac30952015-10-08 23:49:46 +0000129 MovePos->getParent()->getBasicBlockList().splice(
130 ++MovePos->getIterator(), getParent()->getBasicBlockList(),
131 getIterator());
Chris Lattnera71965b2006-09-23 04:03:45 +0000132}
133
Craig Topper170b7612017-03-27 02:38:17 +0000134const Module *BasicBlock::getModule() const {
Philip Reamesd59f9702015-05-26 21:03:23 +0000135 return getParent()->getParent();
136}
137
Chandler Carruthd8d83712018-10-15 10:42:50 +0000138const Instruction *BasicBlock::getTerminator() const {
139 if (InstList.empty() || !InstList.back().isTerminator())
140 return nullptr;
141 return &InstList.back();
Chris Lattner00950542001-06-06 20:29:01 +0000142}
143
Craig Topper170b7612017-03-27 02:38:17 +0000144const CallInst *BasicBlock::getTerminatingMustTailCall() const {
Reid Kleckner29706772014-08-12 00:05:15 +0000145 if (InstList.empty())
146 return nullptr;
Craig Topper170b7612017-03-27 02:38:17 +0000147 const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
Reid Kleckner29706772014-08-12 00:05:15 +0000148 if (!RI || RI == &InstList.front())
149 return nullptr;
150
Craig Topper170b7612017-03-27 02:38:17 +0000151 const Instruction *Prev = RI->getPrevNode();
Reid Kleckner29706772014-08-12 00:05:15 +0000152 if (!Prev)
153 return nullptr;
154
155 if (Value *RV = RI->getReturnValue()) {
156 if (RV != Prev)
157 return nullptr;
158
159 // Look through the optional bitcast.
160 if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
161 RV = BI->getOperand(0);
162 Prev = BI->getPrevNode();
163 if (!Prev || RV != Prev)
164 return nullptr;
165 }
166 }
167
168 if (auto *CI = dyn_cast<CallInst>(Prev)) {
169 if (CI->isMustTailCall())
170 return CI;
171 }
172 return nullptr;
173}
174
Craig Topper170b7612017-03-27 02:38:17 +0000175const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
Sanjoy Dasf9e72192016-03-11 19:08:34 +0000176 if (InstList.empty())
177 return nullptr;
178 auto *RI = dyn_cast<ReturnInst>(&InstList.back());
179 if (!RI || RI == &InstList.front())
180 return nullptr;
181
182 if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
183 if (Function *F = CI->getCalledFunction())
184 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
185 return CI;
186
187 return nullptr;
188}
189
Craig Topper170b7612017-03-27 02:38:17 +0000190const Instruction* BasicBlock::getFirstNonPHI() const {
191 for (const Instruction &I : *this)
David Majnemer0148a4c2015-07-07 18:49:41 +0000192 if (!isa<PHINode>(I))
193 return &I;
194 return nullptr;
Vladimir Prusdd49dbf2006-06-08 15:46:18 +0000195}
196
Craig Topper170b7612017-03-27 02:38:17 +0000197const Instruction* BasicBlock::getFirstNonPHIOrDbg() const {
198 for (const Instruction &I : *this)
David Majnemer0148a4c2015-07-07 18:49:41 +0000199 if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
200 return &I;
201 return nullptr;
Dale Johannesen7249ef02010-04-02 21:49:27 +0000202}
203
Craig Topper170b7612017-03-27 02:38:17 +0000204const Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() const {
205 for (const Instruction &I : *this) {
David Majnemer0148a4c2015-07-07 18:49:41 +0000206 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
Rafael Espindola77a2c372011-06-30 20:14:24 +0000207 continue;
208
Vedant Kumareeb19712018-12-21 21:49:40 +0000209 if (I.isLifetimeStartOrEnd())
210 continue;
David Majnemer0148a4c2015-07-07 18:49:41 +0000211
212 return &I;
Rafael Espindola77a2c372011-06-30 20:14:24 +0000213 }
David Majnemer0148a4c2015-07-07 18:49:41 +0000214 return nullptr;
Rafael Espindola77a2c372011-06-30 20:14:24 +0000215}
216
Craig Topper170b7612017-03-27 02:38:17 +0000217BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
218 const Instruction *FirstNonPHI = getFirstNonPHI();
David Majnemer0148a4c2015-07-07 18:49:41 +0000219 if (!FirstNonPHI)
220 return end();
221
Craig Topper170b7612017-03-27 02:38:17 +0000222 const_iterator InsertPt = FirstNonPHI->getIterator();
David Majnemer4a45f082015-07-31 17:58:14 +0000223 if (InsertPt->isEHPad()) ++InsertPt;
Bill Wendlingd2e103d2011-08-16 20:42:52 +0000224 return InsertPt;
225}
226
Chris Lattner00950542001-06-06 20:29:01 +0000227void BasicBlock::dropAllReferences() {
Benjamin Kramere96e21f2016-06-26 14:10:56 +0000228 for (Instruction &I : *this)
229 I.dropAllReferences();
Chris Lattner00950542001-06-06 20:29:01 +0000230}
231
Sanjay Patel4ed780a2015-02-27 18:07:41 +0000232/// If this basic block has a single predecessor block,
Chris Lattnerad993cb2005-02-24 02:37:26 +0000233/// return the block, otherwise return a null pointer.
Craig Topper170b7612017-03-27 02:38:17 +0000234const BasicBlock *BasicBlock::getSinglePredecessor() const {
235 const_pred_iterator PI = pred_begin(this), E = pred_end(this);
Craig Topperec0f0bc2014-04-09 06:08:46 +0000236 if (PI == E) return nullptr; // No preds.
Craig Topper170b7612017-03-27 02:38:17 +0000237 const BasicBlock *ThePred = *PI;
Chris Lattnerad993cb2005-02-24 02:37:26 +0000238 ++PI;
Craig Topperec0f0bc2014-04-09 06:08:46 +0000239 return (PI == E) ? ThePred : nullptr /*multiple preds*/;
Chris Lattnerad993cb2005-02-24 02:37:26 +0000240}
241
Sanjay Patel4ed780a2015-02-27 18:07:41 +0000242/// If this basic block has a unique predecessor block,
Torok Edwin87f1e772008-12-11 10:36:07 +0000243/// return the block, otherwise return a null pointer.
NAKAMURA Takumi8fc9b3d2011-08-09 23:12:56 +0000244/// Note that unique predecessor doesn't mean single edge, there can be
245/// multiple edges from the unique predecessor to this block (for example
Torok Edwin9053a732008-12-11 11:44:49 +0000246/// a switch statement with multiple cases having the same destination).
Craig Topper170b7612017-03-27 02:38:17 +0000247const BasicBlock *BasicBlock::getUniquePredecessor() const {
248 const_pred_iterator PI = pred_begin(this), E = pred_end(this);
Craig Topperec0f0bc2014-04-09 06:08:46 +0000249 if (PI == E) return nullptr; // No preds.
Craig Topper170b7612017-03-27 02:38:17 +0000250 const BasicBlock *PredBB = *PI;
Torok Edwin87f1e772008-12-11 10:36:07 +0000251 ++PI;
252 for (;PI != E; ++PI) {
253 if (*PI != PredBB)
Craig Topperec0f0bc2014-04-09 06:08:46 +0000254 return nullptr;
Torok Edwin9053a732008-12-11 11:44:49 +0000255 // The same predecessor appears multiple times in the predecessor list.
256 // This is OK.
Torok Edwin87f1e772008-12-11 10:36:07 +0000257 }
258 return PredBB;
259}
260
Vedant Kumar94a229e2018-11-19 19:54:27 +0000261bool BasicBlock::hasNPredecessors(unsigned N) const {
262 return hasNItems(pred_begin(this), pred_end(this), N);
263}
264
265bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
266 return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
267}
268
Craig Topper170b7612017-03-27 02:38:17 +0000269const BasicBlock *BasicBlock::getSingleSuccessor() const {
270 succ_const_iterator SI = succ_begin(this), E = succ_end(this);
Jingyue Wu85e632d2015-05-15 17:54:48 +0000271 if (SI == E) return nullptr; // no successors
Craig Topper170b7612017-03-27 02:38:17 +0000272 const BasicBlock *TheSucc = *SI;
Jingyue Wu85e632d2015-05-15 17:54:48 +0000273 ++SI;
274 return (SI == E) ? TheSucc : nullptr /* multiple successors */;
275}
276
Craig Topper170b7612017-03-27 02:38:17 +0000277const BasicBlock *BasicBlock::getUniqueSuccessor() const {
278 succ_const_iterator SI = succ_begin(this), E = succ_end(this);
Hans Wennborg4d651e42015-10-06 23:24:35 +0000279 if (SI == E) return nullptr; // No successors
Craig Topper170b7612017-03-27 02:38:17 +0000280 const BasicBlock *SuccBB = *SI;
Philip Reames2e38beb2015-02-04 00:37:33 +0000281 ++SI;
282 for (;SI != E; ++SI) {
283 if (*SI != SuccBB)
Hans Wennborg4d651e42015-10-06 23:24:35 +0000284 return nullptr;
Philip Reames2e38beb2015-02-04 00:37:33 +0000285 // The same successor appears multiple times in the successor list.
286 // This is OK.
287 }
288 return SuccBB;
289}
290
Chandler Carrutha1a0cf02017-05-26 03:10:00 +0000291iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
Matt Arsenault05983472017-12-29 19:25:53 +0000292 PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
293 return make_range<phi_iterator>(P, nullptr);
Chandler Carrutha1a0cf02017-05-26 03:10:00 +0000294}
295
Sanjay Patel4ed780a2015-02-27 18:07:41 +0000296/// This method is used to notify a BasicBlock that the
Chris Lattner566f6002005-04-21 16:06:03 +0000297/// specified Predecessor of the block is no longer able to reach it. This is
Misha Brukmanfd939082005-04-21 23:48:37 +0000298/// actually not used to update the Predecessor list, but is actually used to
Chris Lattner566f6002005-04-21 16:06:03 +0000299/// update the PHI nodes that reside in the block. Note that this should be
300/// called while the predecessor still refers to this block.
301///
Chris Lattner34645472005-04-12 18:52:14 +0000302void BasicBlock::removePredecessor(BasicBlock *Pred,
Nick Lewycky280a6e62008-04-25 16:53:59 +0000303 bool DontDeleteUselessPHIs) {
Chris Lattner1f21ef12005-02-23 16:53:04 +0000304 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
Chris Lattner35f0aec2005-02-23 07:09:08 +0000305 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
Jeff Cohen9d809302005-04-23 21:38:35 +0000306 "removePredecessor: BB is not a predecessor!");
Chris Lattner35f0aec2005-02-23 07:09:08 +0000307
Chris Lattnerf23586c2004-12-11 22:10:29 +0000308 if (InstList.empty()) return;
Chris Lattnera9e77812004-07-06 17:44:17 +0000309 PHINode *APN = dyn_cast<PHINode>(&front());
310 if (!APN) return; // Quick exit.
Chris Lattnerb47af252001-06-29 05:25:23 +0000311
312 // If there are exactly two predecessors, then we want to nuke the PHI nodes
Chris Lattnera9e77812004-07-06 17:44:17 +0000313 // altogether. However, we cannot do this, if this in this case:
Chris Lattner87a09b12002-05-21 19:52:49 +0000314 //
315 // Loop:
316 // %x = phi [X, Loop]
317 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
318 // br Loop ;; %x2 does not dominate all uses
319 //
320 // This is because the PHI node input is actually taken from the predecessor
Misha Brukmanfd939082005-04-21 23:48:37 +0000321 // basic block. The only case this can happen is with a self loop, so we
Chris Lattner87a09b12002-05-21 19:52:49 +0000322 // check for this case explicitly now.
Misha Brukmanfd939082005-04-21 23:48:37 +0000323 //
Chris Lattnera9e77812004-07-06 17:44:17 +0000324 unsigned max_idx = APN->getNumIncomingValues();
Chris Lattnerb47af252001-06-29 05:25:23 +0000325 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
Chris Lattner87a09b12002-05-21 19:52:49 +0000326 if (max_idx == 2) {
Chris Lattnera9e77812004-07-06 17:44:17 +0000327 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
Chris Lattner87a09b12002-05-21 19:52:49 +0000328
329 // Disable PHI elimination!
330 if (this == Other) max_idx = 3;
331 }
332
Chris Lattner34645472005-04-12 18:52:14 +0000333 // <= Two predecessors BEFORE I remove one?
334 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000335 // Yup, loop through and nuke the PHI nodes
Chris Lattner7e708292002-06-25 16:13:24 +0000336 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
Chris Lattner34645472005-04-12 18:52:14 +0000337 // Remove the predecessor first.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000338 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
Chris Lattnerb47af252001-06-29 05:25:23 +0000339
340 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
Chris Lattnerdee430d2002-10-08 21:36:34 +0000341 if (max_idx == 2) {
Jay Foadc1371202011-06-20 14:18:48 +0000342 if (PN->getIncomingValue(0) != PN)
343 PN->replaceAllUsesWith(PN->getIncomingValue(0));
Chris Lattner02a78cf2003-04-25 23:14:19 +0000344 else
345 // We are left with an infinite loop with no entries: kill the PHI.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000346 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattnerdee430d2002-10-08 21:36:34 +0000347 getInstList().pop_front(); // Remove the PHI node
348 }
349
350 // If the PHI node already only had one entry, it got deleted by
351 // removeIncomingValue.
Chris Lattnerb47af252001-06-29 05:25:23 +0000352 }
353 } else {
354 // Okay, now we know that we need to remove predecessor #pred_idx from all
355 // PHI nodes. Iterate over each PHI node fixing them up
Chris Lattnerf8782182004-06-05 00:11:27 +0000356 PHINode *PN;
Chris Lattner80f4d882005-08-05 15:34:10 +0000357 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
358 ++II;
Nick Lewycky280a6e62008-04-25 16:53:59 +0000359 PN->removeIncomingValue(Pred, false);
Nate Begemana83ba0f2005-08-04 23:24:19 +0000360 // If all incoming values to the Phi are the same, we can replace the Phi
361 // with that value.
Craig Topperec0f0bc2014-04-09 06:08:46 +0000362 Value* PNV = nullptr;
Duncan Sands23a19572010-11-17 10:23:23 +0000363 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
364 if (PNV != PN) {
365 PN->replaceAllUsesWith(PNV);
366 PN->eraseFromParent();
367 }
Nate Begemana83ba0f2005-08-04 23:24:19 +0000368 }
Chris Lattnerb47af252001-06-29 05:25:23 +0000369 }
370}
371
David Majnemer4a45f082015-07-31 17:58:14 +0000372bool BasicBlock::canSplitPredecessors() const {
373 const Instruction *FirstNonPHI = getFirstNonPHI();
374 if (isa<LandingPadInst>(FirstNonPHI))
375 return true;
376 // This is perhaps a little conservative because constructs like
377 // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors
378 // cannot handle such things just yet.
379 if (FirstNonPHI->isEHPad())
380 return false;
381 return true;
382}
Chris Lattner00950542001-06-06 20:29:01 +0000383
Andrew Kaylorc539eea2017-06-22 23:27:16 +0000384bool BasicBlock::isLegalToHoistInto() const {
385 auto *Term = getTerminator();
386 // No terminator means the block is under construction.
387 if (!Term)
388 return true;
389
390 // If the block has no successors, there can be no instructions to hoist.
391 assert(Term->getNumSuccessors() > 0);
392
393 // Instructions should not be hoisted across exception handling boundaries.
Chandler Carruthacc248f2018-08-26 08:56:42 +0000394 return !Term->isExceptionalTerminator();
Andrew Kaylorc539eea2017-06-22 23:27:16 +0000395}
396
Sanjay Patel4ed780a2015-02-27 18:07:41 +0000397/// This splits a basic block into two at the specified
Chris Lattner0f67dd62005-04-21 16:04:49 +0000398/// instruction. Note that all instructions BEFORE the specified iterator stay
Misha Brukmanfd939082005-04-21 23:48:37 +0000399/// as part of the original basic block, an unconditional branch is added to
Chris Lattner0f67dd62005-04-21 16:04:49 +0000400/// the new BB, and the rest of the instructions in the BB are moved to the new
401/// BB, including the old terminator. This invalidates the iterator.
402///
Misha Brukmanfd939082005-04-21 23:48:37 +0000403/// Note that this only works on well formed basic blocks (must have a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000404/// terminator), and 'I' must not be the end of instruction list (which would
405/// cause a degenerate basic block to be formed, having a terminator inside of
Misha Brukmanfd939082005-04-21 23:48:37 +0000406/// the basic block).
Chris Lattner0f67dd62005-04-21 16:04:49 +0000407///
Daniel Dunbar6e0d1cb2009-07-25 04:41:11 +0000408BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
Chris Lattner00950542001-06-06 20:29:01 +0000409 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000410 assert(I != InstList.end() &&
Jeff Cohen9d809302005-04-23 21:38:35 +0000411 "Trying to get me to create degenerate basic block!");
Chris Lattner00950542001-06-06 20:29:01 +0000412
Duncan P. N. Exon Smith14147ed2016-02-21 19:52:15 +0000413 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
414 this->getNextNode());
Chris Lattner00950542001-06-06 20:29:01 +0000415
Alexey Samsonovbc482282015-06-11 18:25:54 +0000416 // Save DebugLoc of split point before invalidating iterator.
417 DebugLoc Loc = I->getDebugLoc();
Chris Lattnerf2c31062004-02-03 23:11:21 +0000418 // Move all of the specified instructions from the original basic block into
419 // the new basic block.
420 New->getInstList().splice(New->end(), this->getInstList(), I, end());
Chris Lattner00950542001-06-06 20:29:01 +0000421
422 // Add a branch instruction to the newly formed basic block.
Alexey Samsonovbc482282015-06-11 18:25:54 +0000423 BranchInst *BI = BranchInst::Create(New, this);
424 BI->setDebugLoc(Loc);
Chris Lattnere8e320d2002-02-25 00:35:07 +0000425
426 // Now we must loop through all of the successors of the New block (which
427 // _were_ the successors of the 'this' block), and update any PHI nodes in
428 // successors. If there were PHI nodes in the successors, then they need to
429 // know that incoming branches will be from New, not from Old.
430 //
Duncan P. N. Exon Smithfacdfc62014-07-21 17:06:51 +0000431 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
Chris Lattnere8e320d2002-02-25 00:35:07 +0000432 // Loop over any phi nodes in the basic block, updating the BB field of
433 // incoming values...
Duncan P. N. Exon Smithfacdfc62014-07-21 17:06:51 +0000434 BasicBlock *Successor = *I;
Chandler Carrutha1a0cf02017-05-26 03:10:00 +0000435 for (auto &PN : Successor->phis()) {
436 int Idx = PN.getBasicBlockIndex(this);
437 while (Idx != -1) {
438 PN.setIncomingBlock((unsigned)Idx, New);
439 Idx = PN.getBasicBlockIndex(this);
Chris Lattnere8e320d2002-02-25 00:35:07 +0000440 }
441 }
442 }
Chris Lattner00950542001-06-06 20:29:01 +0000443 return New;
444}
Dan Gohmaneeb8ef12009-10-29 00:09:08 +0000445
Jay Foad95c3e482011-06-23 09:09:15 +0000446void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
Chandler Carruth2aaf7222018-10-15 10:04:59 +0000447 Instruction *TI = getTerminator();
Jay Foad95c3e482011-06-23 09:09:15 +0000448 if (!TI)
449 // Cope with being called on a BasicBlock that doesn't have a terminator
450 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
451 return;
Chandler Carruth5eb83c52018-08-26 08:41:15 +0000452 for (BasicBlock *Succ : successors(TI)) {
NAKAMURA Takumi77c71402011-08-09 23:13:05 +0000453 // N.B. Succ might not be a complete BasicBlock, so don't assume
454 // that it ends with a non-phi instruction.
455 for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
456 PHINode *PN = dyn_cast<PHINode>(II);
457 if (!PN)
458 break;
Jay Foad95c3e482011-06-23 09:09:15 +0000459 int i;
460 while ((i = PN->getBasicBlockIndex(this)) >= 0)
461 PN->setIncomingBlock(i, New);
462 }
463 }
464}
Bill Wendlinge6e88262011-08-12 20:24:12 +0000465
Sanjay Patel4ed780a2015-02-27 18:07:41 +0000466/// Return true if this basic block is a landing pad. I.e., it's
Bill Wendlinge6e88262011-08-12 20:24:12 +0000467/// the destination of the 'unwind' edge of an invoke instruction.
468bool BasicBlock::isLandingPad() const {
469 return isa<LandingPadInst>(getFirstNonPHI());
470}
471
Sanjay Patel4ed780a2015-02-27 18:07:41 +0000472/// Return the landingpad instruction associated with the landing pad.
Bill Wendling7750c3f2012-01-31 00:26:24 +0000473const LandingPadInst *BasicBlock::getLandingPadInst() const {
474 return dyn_cast<LandingPadInst>(getFirstNonPHI());
475}
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000476
477Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
Chandler Carruth2aaf7222018-10-15 10:04:59 +0000478 const Instruction *TI = getTerminator();
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000479 if (MDNode *MDIrrLoopHeader =
480 TI->getMetadata(LLVMContext::MD_irr_loop)) {
481 MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
482 if (MDName->getString().equals("loop_header_weight")) {
483 auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
484 return Optional<uint64_t>(CI->getValue().getZExtValue());
485 }
486 }
487 return Optional<uint64_t>();
488}
Vedant Kumar83a64512018-06-19 23:42:17 +0000489
Vedant Kumarab0a33b2018-06-26 21:16:59 +0000490BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
Vedant Kumar83a64512018-06-19 23:42:17 +0000491 while (isa<DbgInfoIntrinsic>(It))
492 ++It;
493 return It;
494}