1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the BasicBlock class for the IR library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/BasicBlock.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/IR/CFG.h"
18 #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"
23 #include <algorithm>
24
25 using namespace llvm;
26
getValueSymbolTable()27 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28 if (Function *F = getParent())
29 return F->getValueSymbolTable();
30 return nullptr;
31 }
32
getContext() const33 LLVMContext &BasicBlock::getContext() const {
34 return getType()->getContext();
35 }
36
37 // Explicit instantiation of SymbolTableListTraits since some of the methods
38 // are not in the public header file...
39 template class llvm::SymbolTableListTraits<Instruction>;
40
BasicBlock(LLVMContext & C,const Twine & Name,Function * NewParent,BasicBlock * InsertBefore)41 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
42 BasicBlock *InsertBefore)
43 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
44
45 if (NewParent)
46 insertInto(NewParent, InsertBefore);
47 else
48 assert(!InsertBefore &&
49 "Cannot insert block before another block with no function!");
50
51 setName(Name);
52 }
53
insertInto(Function * NewParent,BasicBlock * InsertBefore)54 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
55 assert(NewParent && "Expected a parent");
56 assert(!Parent && "Already has a parent");
57
58 if (InsertBefore)
59 NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
60 else
61 NewParent->getBasicBlockList().push_back(this);
62 }
63
~BasicBlock()64 BasicBlock::~BasicBlock() {
65 // 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
70 // nodes. There are no other possible uses at this point.
71 if (hasAddressTaken()) {
72 assert(!use_empty() && "There should be at least one blockaddress!");
73 Constant *Replacement =
74 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
75 while (!use_empty()) {
76 BlockAddress *BA = cast<BlockAddress>(user_back());
77 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
78 BA->getType()));
79 BA->destroyConstant();
80 }
81 }
82
83 assert(getParent() == nullptr && "BasicBlock still linked into the program!");
84 dropAllReferences();
85 InstList.clear();
86 }
87
setParent(Function * parent)88 void BasicBlock::setParent(Function *parent) {
89 // Set Parent=parent, updating instruction symtab entries as appropriate.
90 InstList.setSymTabObject(&Parent, parent);
91 }
92
93 iterator_range<filter_iterator<BasicBlock::const_iterator,
94 std::function<bool(const Instruction &)>>>
instructionsWithoutDebug() const95 BasicBlock::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
102 iterator_range<filter_iterator<BasicBlock::iterator,
103 std::function<bool(Instruction &)>>>
instructionsWithoutDebug()104 BasicBlock::instructionsWithoutDebug() {
105 std::function<bool(Instruction &)> Fn = [](Instruction &I) {
106 return !isa<DbgInfoIntrinsic>(I);
107 };
108 return make_filter_range(*this, Fn);
109 }
110
removeFromParent()111 void BasicBlock::removeFromParent() {
112 getParent()->getBasicBlockList().remove(getIterator());
113 }
114
eraseFromParent()115 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
116 return getParent()->getBasicBlockList().erase(getIterator());
117 }
118
119 /// Unlink this basic block from its current function and
120 /// insert it into the function that MovePos lives in, right before MovePos.
moveBefore(BasicBlock * MovePos)121 void BasicBlock::moveBefore(BasicBlock *MovePos) {
122 MovePos->getParent()->getBasicBlockList().splice(
123 MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
124 }
125
126 /// Unlink this basic block from its current function and
127 /// insert it into the function that MovePos lives in, right after MovePos.
moveAfter(BasicBlock * MovePos)128 void BasicBlock::moveAfter(BasicBlock *MovePos) {
129 MovePos->getParent()->getBasicBlockList().splice(
130 ++MovePos->getIterator(), getParent()->getBasicBlockList(),
131 getIterator());
132 }
133
getModule() const134 const Module *BasicBlock::getModule() const {
135 return getParent()->getParent();
136 }
137
getTerminator() const138 const Instruction *BasicBlock::getTerminator() const {
139 if (InstList.empty() || !InstList.back().isTerminator())
140 return nullptr;
141 return &InstList.back();
142 }
143
getTerminatingMustTailCall() const144 const CallInst *BasicBlock::getTerminatingMustTailCall() const {
145 if (InstList.empty())
146 return nullptr;
147 const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
148 if (!RI || RI == &InstList.front())
149 return nullptr;
150
151 const Instruction *Prev = RI->getPrevNode();
152 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
getTerminatingDeoptimizeCall() const175 const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
176 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
getFirstNonPHI() const190 const Instruction* BasicBlock::getFirstNonPHI() const {
191 for (const Instruction &I : *this)
192 if (!isa<PHINode>(I))
193 return &I;
194 return nullptr;
195 }
196
getFirstNonPHIOrDbg() const197 const Instruction* BasicBlock::getFirstNonPHIOrDbg() const {
198 for (const Instruction &I : *this)
199 if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
200 return &I;
201 return nullptr;
202 }
203
getFirstNonPHIOrDbgOrLifetime() const204 const Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() const {
205 for (const Instruction &I : *this) {
206 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
207 continue;
208
209 if (I.isLifetimeStartOrEnd())
210 continue;
211
212 return &I;
213 }
214 return nullptr;
215 }
216
getFirstInsertionPt() const217 BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
218 const Instruction *FirstNonPHI = getFirstNonPHI();
219 if (!FirstNonPHI)
220 return end();
221
222 const_iterator InsertPt = FirstNonPHI->getIterator();
223 if (InsertPt->isEHPad()) ++InsertPt;
224 return InsertPt;
225 }
226
dropAllReferences()227 void BasicBlock::dropAllReferences() {
228 for (Instruction &I : *this)
229 I.dropAllReferences();
230 }
231
232 /// If this basic block has a single predecessor block,
233 /// return the block, otherwise return a null pointer.
getSinglePredecessor() const234 const BasicBlock *BasicBlock::getSinglePredecessor() const {
235 const_pred_iterator PI = pred_begin(this), E = pred_end(this);
236 if (PI == E) return nullptr; // No preds.
237 const BasicBlock *ThePred = *PI;
238 ++PI;
239 return (PI == E) ? ThePred : nullptr /*multiple preds*/;
240 }
241
242 /// If this basic block has a unique predecessor block,
243 /// return the block, otherwise return a null pointer.
244 /// Note that unique predecessor doesn't mean single edge, there can be
245 /// multiple edges from the unique predecessor to this block (for example
246 /// a switch statement with multiple cases having the same destination).
getUniquePredecessor() const247 const BasicBlock *BasicBlock::getUniquePredecessor() const {
248 const_pred_iterator PI = pred_begin(this), E = pred_end(this);
249 if (PI == E) return nullptr; // No preds.
250 const BasicBlock *PredBB = *PI;
251 ++PI;
252 for (;PI != E; ++PI) {
253 if (*PI != PredBB)
254 return nullptr;
255 // The same predecessor appears multiple times in the predecessor list.
256 // This is OK.
257 }
258 return PredBB;
259 }
260
hasNPredecessors(unsigned N) const261 bool BasicBlock::hasNPredecessors(unsigned N) const {
262 return hasNItems(pred_begin(this), pred_end(this), N);
263 }
264
hasNPredecessorsOrMore(unsigned N) const265 bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
266 return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
267 }
268
getSingleSuccessor() const269 const BasicBlock *BasicBlock::getSingleSuccessor() const {
270 succ_const_iterator SI = succ_begin(this), E = succ_end(this);
271 if (SI == E) return nullptr; // no successors
272 const BasicBlock *TheSucc = *SI;
273 ++SI;
274 return (SI == E) ? TheSucc : nullptr /* multiple successors */;
275 }
276
getUniqueSuccessor() const277 const BasicBlock *BasicBlock::getUniqueSuccessor() const {
278 succ_const_iterator SI = succ_begin(this), E = succ_end(this);
279 if (SI == E) return nullptr; // No successors
280 const BasicBlock *SuccBB = *SI;
281 ++SI;
282 for (;SI != E; ++SI) {
283 if (*SI != SuccBB)
284 return nullptr;
285 // The same successor appears multiple times in the successor list.
286 // This is OK.
287 }
288 return SuccBB;
289 }
290
phis()291 iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
292 PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
293 return make_range<phi_iterator>(P, nullptr);
294 }
295
296 /// This method is used to notify a BasicBlock that the
297 /// specified Predecessor of the block is no longer able to reach it. This is
298 /// actually not used to update the Predecessor list, but is actually used to
299 /// 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 ///
removePredecessor(BasicBlock * Pred,bool DontDeleteUselessPHIs)302 void BasicBlock::removePredecessor(BasicBlock *Pred,
303 bool DontDeleteUselessPHIs) {
304 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
305 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
306 "removePredecessor: BB is not a predecessor!");
307
308 if (InstList.empty()) return;
309 PHINode *APN = dyn_cast<PHINode>(&front());
310 if (!APN) return; // Quick exit.
311
312 // If there are exactly two predecessors, then we want to nuke the PHI nodes
313 // altogether. However, we cannot do this, if this in this case:
314 //
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
321 // basic block. The only case this can happen is with a self loop, so we
322 // check for this case explicitly now.
323 //
324 unsigned max_idx = APN->getNumIncomingValues();
325 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
326 if (max_idx == 2) {
327 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
328
329 // Disable PHI elimination!
330 if (this == Other) max_idx = 3;
331 }
332
333 // <= Two predecessors BEFORE I remove one?
334 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
335 // Yup, loop through and nuke the PHI nodes
336 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
337 // Remove the predecessor first.
338 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
339
340 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
341 if (max_idx == 2) {
342 if (PN->getIncomingValue(0) != PN)
343 PN->replaceAllUsesWith(PN->getIncomingValue(0));
344 else
345 // We are left with an infinite loop with no entries: kill the PHI.
346 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
347 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.
352 }
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
356 PHINode *PN;
357 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
358 ++II;
359 PN->removeIncomingValue(Pred, false);
360 // If all incoming values to the Phi are the same, we can replace the Phi
361 // with that value.
362 Value* PNV = nullptr;
363 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
364 if (PNV != PN) {
365 PN->replaceAllUsesWith(PNV);
366 PN->eraseFromParent();
367 }
368 }
369 }
370 }
371
canSplitPredecessors() const372 bool 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 }
383
isLegalToHoistInto() const384 bool 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.
394 return !Term->isExceptionalTerminator();
395 }
396
397 /// This splits a basic block into two at the specified
398 /// instruction. Note that all instructions BEFORE the specified iterator stay
399 /// as part of the original basic block, an unconditional branch is added to
400 /// 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 ///
403 /// Note that this only works on well formed basic blocks (must have a
404 /// 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
406 /// the basic block).
407 ///
splitBasicBlock(iterator I,const Twine & BBName)408 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
409 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
410 assert(I != InstList.end() &&
411 "Trying to get me to create degenerate basic block!");
412
413 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
414 this->getNextNode());
415
416 // Save DebugLoc of split point before invalidating iterator.
417 DebugLoc Loc = I->getDebugLoc();
418 // 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());
421
422 // Add a branch instruction to the newly formed basic block.
423 BranchInst *BI = BranchInst::Create(New, this);
424 BI->setDebugLoc(Loc);
425
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 //
431 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
432 // Loop over any phi nodes in the basic block, updating the BB field of
433 // incoming values...
434 BasicBlock *Successor = *I;
435 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);
440 }
441 }
442 }
443 return New;
444 }
445
replaceSuccessorsPhiUsesWith(BasicBlock * New)446 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
447 Instruction *TI = getTerminator();
448 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;
452 for (BasicBlock *Succ : successors(TI)) {
453 // 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;
459 int i;
460 while ((i = PN->getBasicBlockIndex(this)) >= 0)
461 PN->setIncomingBlock(i, New);
462 }
463 }
464 }
465
466 /// Return true if this basic block is a landing pad. I.e., it's
467 /// the destination of the 'unwind' edge of an invoke instruction.
isLandingPad() const468 bool BasicBlock::isLandingPad() const {
469 return isa<LandingPadInst>(getFirstNonPHI());
470 }
471
472 /// Return the landingpad instruction associated with the landing pad.
getLandingPadInst() const473 const LandingPadInst *BasicBlock::getLandingPadInst() const {
474 return dyn_cast<LandingPadInst>(getFirstNonPHI());
475 }
476
getIrrLoopHeaderWeight() const477 Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
478 const Instruction *TI = getTerminator();
479 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 }
489
skipDebugIntrinsics(BasicBlock::iterator It)490 BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
491 while (isa<DbgInfoIntrinsic>(It))
492 ++It;
493 return It;
494 }
495