1139f7f9bSDimitry Andric //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2139f7f9bSDimitry Andric //
3139f7f9bSDimitry Andric //                     The LLVM Compiler Infrastructure
4139f7f9bSDimitry Andric //
5139f7f9bSDimitry Andric // This file is distributed under the University of Illinois Open Source
6139f7f9bSDimitry Andric // License. See LICENSE.TXT for details.
7139f7f9bSDimitry Andric //
8139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
9139f7f9bSDimitry Andric //
10139f7f9bSDimitry Andric // This file implements the BasicBlock class for the IR library.
11139f7f9bSDimitry Andric //
12139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
13139f7f9bSDimitry Andric 
14139f7f9bSDimitry Andric #include "llvm/IR/BasicBlock.h"
15139f7f9bSDimitry Andric #include "SymbolTableListTraitsImpl.h"
16139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h"
1791bc56edSDimitry Andric #include "llvm/IR/CFG.h"
18139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
19139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
20139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
21139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
22139f7f9bSDimitry Andric #include "llvm/IR/Type.h"
23139f7f9bSDimitry Andric #include <algorithm>
247d523365SDimitry Andric 
25139f7f9bSDimitry Andric using namespace llvm;
26139f7f9bSDimitry Andric 
getValueSymbolTable()27139f7f9bSDimitry Andric ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28139f7f9bSDimitry Andric   if (Function *F = getParent())
29d88c1a5aSDimitry Andric     return F->getValueSymbolTable();
3091bc56edSDimitry Andric   return nullptr;
3191bc56edSDimitry Andric }
3291bc56edSDimitry Andric 
getContext() const33139f7f9bSDimitry Andric LLVMContext &BasicBlock::getContext() const {
34139f7f9bSDimitry Andric   return getType()->getContext();
35139f7f9bSDimitry Andric }
36139f7f9bSDimitry Andric 
37139f7f9bSDimitry Andric // Explicit instantiation of SymbolTableListTraits since some of the methods
38139f7f9bSDimitry Andric // are not in the public header file...
397d523365SDimitry Andric template class llvm::SymbolTableListTraits<Instruction>;
40139f7f9bSDimitry Andric 
BasicBlock(LLVMContext & C,const Twine & Name,Function * NewParent,BasicBlock * InsertBefore)41139f7f9bSDimitry Andric BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
42139f7f9bSDimitry Andric                        BasicBlock *InsertBefore)
4391bc56edSDimitry Andric   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
44139f7f9bSDimitry Andric 
4539d628a0SDimitry Andric   if (NewParent)
4639d628a0SDimitry Andric     insertInto(NewParent, InsertBefore);
4739d628a0SDimitry Andric   else
4839d628a0SDimitry Andric     assert(!InsertBefore &&
49139f7f9bSDimitry Andric            "Cannot insert block before another block with no function!");
50139f7f9bSDimitry Andric 
51139f7f9bSDimitry Andric   setName(Name);
52139f7f9bSDimitry Andric }
53139f7f9bSDimitry Andric 
insertInto(Function * NewParent,BasicBlock * InsertBefore)5439d628a0SDimitry Andric void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
5539d628a0SDimitry Andric   assert(NewParent && "Expected a parent");
5639d628a0SDimitry Andric   assert(!Parent && "Already has a parent");
5739d628a0SDimitry Andric 
5839d628a0SDimitry Andric   if (InsertBefore)
597d523365SDimitry Andric     NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
6039d628a0SDimitry Andric   else
6139d628a0SDimitry Andric     NewParent->getBasicBlockList().push_back(this);
6239d628a0SDimitry Andric }
63139f7f9bSDimitry Andric 
~BasicBlock()64139f7f9bSDimitry Andric BasicBlock::~BasicBlock() {
65139f7f9bSDimitry Andric   // If the address of the block is taken and it is being deleted (e.g. because
66139f7f9bSDimitry Andric   // it is dead), this means that there is either a dangling constant expr
67139f7f9bSDimitry Andric   // hanging off the block, or an undefined use of the block (source code
68139f7f9bSDimitry Andric   // expecting the address of a label to keep the block alive even though there
69139f7f9bSDimitry Andric   // is no indirect branch).  Handle these cases by zapping the BlockAddress
70139f7f9bSDimitry Andric   // nodes.  There are no other possible uses at this point.
71139f7f9bSDimitry Andric   if (hasAddressTaken()) {
72139f7f9bSDimitry Andric     assert(!use_empty() && "There should be at least one blockaddress!");
73139f7f9bSDimitry Andric     Constant *Replacement =
74139f7f9bSDimitry Andric       ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
75139f7f9bSDimitry Andric     while (!use_empty()) {
7691bc56edSDimitry Andric       BlockAddress *BA = cast<BlockAddress>(user_back());
77139f7f9bSDimitry Andric       BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
78139f7f9bSDimitry Andric                                                        BA->getType()));
79139f7f9bSDimitry Andric       BA->destroyConstant();
80139f7f9bSDimitry Andric     }
81139f7f9bSDimitry Andric   }
82139f7f9bSDimitry Andric 
8391bc56edSDimitry Andric   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
84139f7f9bSDimitry Andric   dropAllReferences();
85139f7f9bSDimitry Andric   InstList.clear();
86139f7f9bSDimitry Andric }
87139f7f9bSDimitry Andric 
setParent(Function * parent)88139f7f9bSDimitry Andric void BasicBlock::setParent(Function *parent) {
89139f7f9bSDimitry Andric   // Set Parent=parent, updating instruction symtab entries as appropriate.
90139f7f9bSDimitry Andric   InstList.setSymTabObject(&Parent, parent);
91139f7f9bSDimitry Andric }
92139f7f9bSDimitry Andric 
934ba319b5SDimitry Andric iterator_range<filter_iterator<BasicBlock::const_iterator,
944ba319b5SDimitry Andric                                std::function<bool(const Instruction &)>>>
instructionsWithoutDebug() const954ba319b5SDimitry Andric BasicBlock::instructionsWithoutDebug() const {
964ba319b5SDimitry Andric   std::function<bool(const Instruction &)> Fn = [](const Instruction &I) {
974ba319b5SDimitry Andric     return !isa<DbgInfoIntrinsic>(I);
984ba319b5SDimitry Andric   };
994ba319b5SDimitry Andric   return make_filter_range(*this, Fn);
1004ba319b5SDimitry Andric }
1014ba319b5SDimitry Andric 
1024ba319b5SDimitry Andric iterator_range<filter_iterator<BasicBlock::iterator,
1034ba319b5SDimitry Andric                                std::function<bool(Instruction &)>>>
instructionsWithoutDebug()1044ba319b5SDimitry Andric BasicBlock::instructionsWithoutDebug() {
1054ba319b5SDimitry Andric   std::function<bool(Instruction &)> Fn = [](Instruction &I) {
1064ba319b5SDimitry Andric     return !isa<DbgInfoIntrinsic>(I);
1074ba319b5SDimitry Andric   };
1084ba319b5SDimitry Andric   return make_filter_range(*this, Fn);
1094ba319b5SDimitry Andric }
1104ba319b5SDimitry Andric 
removeFromParent()111139f7f9bSDimitry Andric void BasicBlock::removeFromParent() {
1127d523365SDimitry Andric   getParent()->getBasicBlockList().remove(getIterator());
113139f7f9bSDimitry Andric }
114139f7f9bSDimitry Andric 
eraseFromParent()115ff0cc061SDimitry Andric iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
1167d523365SDimitry Andric   return getParent()->getBasicBlockList().erase(getIterator());
117139f7f9bSDimitry Andric }
118139f7f9bSDimitry Andric 
119ff0cc061SDimitry Andric /// Unlink this basic block from its current function and
120139f7f9bSDimitry Andric /// insert it into the function that MovePos lives in, right before MovePos.
moveBefore(BasicBlock * MovePos)121139f7f9bSDimitry Andric void BasicBlock::moveBefore(BasicBlock *MovePos) {
1227d523365SDimitry Andric   MovePos->getParent()->getBasicBlockList().splice(
1237d523365SDimitry Andric       MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
124139f7f9bSDimitry Andric }
125139f7f9bSDimitry Andric 
126ff0cc061SDimitry Andric /// Unlink this basic block from its current function and
127139f7f9bSDimitry Andric /// insert it into the function that MovePos lives in, right after MovePos.
moveAfter(BasicBlock * MovePos)128139f7f9bSDimitry Andric void BasicBlock::moveAfter(BasicBlock *MovePos) {
1297d523365SDimitry Andric   MovePos->getParent()->getBasicBlockList().splice(
1307d523365SDimitry Andric       ++MovePos->getIterator(), getParent()->getBasicBlockList(),
1317d523365SDimitry Andric       getIterator());
132139f7f9bSDimitry Andric }
133139f7f9bSDimitry Andric 
getModule() const134ff0cc061SDimitry Andric const Module *BasicBlock::getModule() const {
135ff0cc061SDimitry Andric   return getParent()->getParent();
136ff0cc061SDimitry Andric }
137ff0cc061SDimitry Andric 
getTerminator() const138*b5893f02SDimitry Andric const Instruction *BasicBlock::getTerminator() const {
139*b5893f02SDimitry Andric   if (InstList.empty() || !InstList.back().isTerminator())
140*b5893f02SDimitry Andric     return nullptr;
141*b5893f02SDimitry Andric   return &InstList.back();
142139f7f9bSDimitry Andric }
143139f7f9bSDimitry Andric 
getTerminatingMustTailCall() const1447a7e6055SDimitry Andric const CallInst *BasicBlock::getTerminatingMustTailCall() const {
14539d628a0SDimitry Andric   if (InstList.empty())
14639d628a0SDimitry Andric     return nullptr;
1477a7e6055SDimitry Andric   const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
14839d628a0SDimitry Andric   if (!RI || RI == &InstList.front())
14939d628a0SDimitry Andric     return nullptr;
15039d628a0SDimitry Andric 
1517a7e6055SDimitry Andric   const Instruction *Prev = RI->getPrevNode();
15239d628a0SDimitry Andric   if (!Prev)
15339d628a0SDimitry Andric     return nullptr;
15439d628a0SDimitry Andric 
15539d628a0SDimitry Andric   if (Value *RV = RI->getReturnValue()) {
15639d628a0SDimitry Andric     if (RV != Prev)
15739d628a0SDimitry Andric       return nullptr;
15839d628a0SDimitry Andric 
15939d628a0SDimitry Andric     // Look through the optional bitcast.
16039d628a0SDimitry Andric     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
16139d628a0SDimitry Andric       RV = BI->getOperand(0);
16239d628a0SDimitry Andric       Prev = BI->getPrevNode();
16339d628a0SDimitry Andric       if (!Prev || RV != Prev)
16439d628a0SDimitry Andric         return nullptr;
16539d628a0SDimitry Andric     }
16639d628a0SDimitry Andric   }
16739d628a0SDimitry Andric 
16839d628a0SDimitry Andric   if (auto *CI = dyn_cast<CallInst>(Prev)) {
16939d628a0SDimitry Andric     if (CI->isMustTailCall())
17039d628a0SDimitry Andric       return CI;
17139d628a0SDimitry Andric   }
17239d628a0SDimitry Andric   return nullptr;
17339d628a0SDimitry Andric }
17439d628a0SDimitry Andric 
getTerminatingDeoptimizeCall() const1757a7e6055SDimitry Andric const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
1763ca95b02SDimitry Andric   if (InstList.empty())
1773ca95b02SDimitry Andric     return nullptr;
1783ca95b02SDimitry Andric   auto *RI = dyn_cast<ReturnInst>(&InstList.back());
1793ca95b02SDimitry Andric   if (!RI || RI == &InstList.front())
1803ca95b02SDimitry Andric     return nullptr;
1813ca95b02SDimitry Andric 
1823ca95b02SDimitry Andric   if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
1833ca95b02SDimitry Andric     if (Function *F = CI->getCalledFunction())
1843ca95b02SDimitry Andric       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1853ca95b02SDimitry Andric         return CI;
1863ca95b02SDimitry Andric 
1873ca95b02SDimitry Andric   return nullptr;
1883ca95b02SDimitry Andric }
1893ca95b02SDimitry Andric 
getFirstNonPHI() const1907a7e6055SDimitry Andric const Instruction* BasicBlock::getFirstNonPHI() const {
1917a7e6055SDimitry Andric   for (const Instruction &I : *this)
192875ed548SDimitry Andric     if (!isa<PHINode>(I))
193875ed548SDimitry Andric       return &I;
194875ed548SDimitry Andric   return nullptr;
195139f7f9bSDimitry Andric }
196139f7f9bSDimitry Andric 
getFirstNonPHIOrDbg() const1977a7e6055SDimitry Andric const Instruction* BasicBlock::getFirstNonPHIOrDbg() const {
1987a7e6055SDimitry Andric   for (const Instruction &I : *this)
199875ed548SDimitry Andric     if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
200875ed548SDimitry Andric       return &I;
201875ed548SDimitry Andric   return nullptr;
202139f7f9bSDimitry Andric }
203139f7f9bSDimitry Andric 
getFirstNonPHIOrDbgOrLifetime() const2047a7e6055SDimitry Andric const Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() const {
2057a7e6055SDimitry Andric   for (const Instruction &I : *this) {
206875ed548SDimitry Andric     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
207139f7f9bSDimitry Andric       continue;
208139f7f9bSDimitry Andric 
209*b5893f02SDimitry Andric     if (I.isLifetimeStartOrEnd())
210875ed548SDimitry Andric       continue;
211875ed548SDimitry Andric 
212875ed548SDimitry Andric     return &I;
213139f7f9bSDimitry Andric   }
214875ed548SDimitry Andric   return nullptr;
215139f7f9bSDimitry Andric }
216139f7f9bSDimitry Andric 
getFirstInsertionPt() const2177a7e6055SDimitry Andric BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
2187a7e6055SDimitry Andric   const Instruction *FirstNonPHI = getFirstNonPHI();
219875ed548SDimitry Andric   if (!FirstNonPHI)
220875ed548SDimitry Andric     return end();
221875ed548SDimitry Andric 
2227a7e6055SDimitry Andric   const_iterator InsertPt = FirstNonPHI->getIterator();
2237d523365SDimitry Andric   if (InsertPt->isEHPad()) ++InsertPt;
224139f7f9bSDimitry Andric   return InsertPt;
225139f7f9bSDimitry Andric }
226139f7f9bSDimitry Andric 
dropAllReferences()227139f7f9bSDimitry Andric void BasicBlock::dropAllReferences() {
2283ca95b02SDimitry Andric   for (Instruction &I : *this)
2293ca95b02SDimitry Andric     I.dropAllReferences();
230139f7f9bSDimitry Andric }
231139f7f9bSDimitry Andric 
232ff0cc061SDimitry Andric /// If this basic block has a single predecessor block,
233139f7f9bSDimitry Andric /// return the block, otherwise return a null pointer.
getSinglePredecessor() const2347a7e6055SDimitry Andric const BasicBlock *BasicBlock::getSinglePredecessor() const {
2357a7e6055SDimitry Andric   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
23691bc56edSDimitry Andric   if (PI == E) return nullptr;         // No preds.
2377a7e6055SDimitry Andric   const BasicBlock *ThePred = *PI;
238139f7f9bSDimitry Andric   ++PI;
23991bc56edSDimitry Andric   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
240139f7f9bSDimitry Andric }
241139f7f9bSDimitry Andric 
242ff0cc061SDimitry Andric /// If this basic block has a unique predecessor block,
243139f7f9bSDimitry Andric /// return the block, otherwise return a null pointer.
244139f7f9bSDimitry Andric /// Note that unique predecessor doesn't mean single edge, there can be
245139f7f9bSDimitry Andric /// multiple edges from the unique predecessor to this block (for example
246139f7f9bSDimitry Andric /// a switch statement with multiple cases having the same destination).
getUniquePredecessor() const2477a7e6055SDimitry Andric const BasicBlock *BasicBlock::getUniquePredecessor() const {
2487a7e6055SDimitry Andric   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
24991bc56edSDimitry Andric   if (PI == E) return nullptr; // No preds.
2507a7e6055SDimitry Andric   const BasicBlock *PredBB = *PI;
251139f7f9bSDimitry Andric   ++PI;
252139f7f9bSDimitry Andric   for (;PI != E; ++PI) {
253139f7f9bSDimitry Andric     if (*PI != PredBB)
25491bc56edSDimitry Andric       return nullptr;
255139f7f9bSDimitry Andric     // The same predecessor appears multiple times in the predecessor list.
256139f7f9bSDimitry Andric     // This is OK.
257139f7f9bSDimitry Andric   }
258139f7f9bSDimitry Andric   return PredBB;
259139f7f9bSDimitry Andric }
260139f7f9bSDimitry Andric 
hasNPredecessors(unsigned N) const261*b5893f02SDimitry Andric bool BasicBlock::hasNPredecessors(unsigned N) const {
262*b5893f02SDimitry Andric   return hasNItems(pred_begin(this), pred_end(this), N);
263*b5893f02SDimitry Andric }
264*b5893f02SDimitry Andric 
hasNPredecessorsOrMore(unsigned N) const265*b5893f02SDimitry Andric bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
266*b5893f02SDimitry Andric   return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
267*b5893f02SDimitry Andric }
268*b5893f02SDimitry Andric 
getSingleSuccessor() const2697a7e6055SDimitry Andric const BasicBlock *BasicBlock::getSingleSuccessor() const {
2707a7e6055SDimitry Andric   succ_const_iterator SI = succ_begin(this), E = succ_end(this);
271ff0cc061SDimitry Andric   if (SI == E) return nullptr; // no successors
2727a7e6055SDimitry Andric   const BasicBlock *TheSucc = *SI;
273ff0cc061SDimitry Andric   ++SI;
274ff0cc061SDimitry Andric   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
275ff0cc061SDimitry Andric }
276ff0cc061SDimitry Andric 
getUniqueSuccessor() const2777a7e6055SDimitry Andric const BasicBlock *BasicBlock::getUniqueSuccessor() const {
2787a7e6055SDimitry Andric   succ_const_iterator SI = succ_begin(this), E = succ_end(this);
2797d523365SDimitry Andric   if (SI == E) return nullptr; // No successors
2807a7e6055SDimitry Andric   const BasicBlock *SuccBB = *SI;
281ff0cc061SDimitry Andric   ++SI;
282ff0cc061SDimitry Andric   for (;SI != E; ++SI) {
283ff0cc061SDimitry Andric     if (*SI != SuccBB)
2847d523365SDimitry Andric       return nullptr;
285ff0cc061SDimitry Andric     // The same successor appears multiple times in the successor list.
286ff0cc061SDimitry Andric     // This is OK.
287ff0cc061SDimitry Andric   }
288ff0cc061SDimitry Andric   return SuccBB;
289ff0cc061SDimitry Andric }
290ff0cc061SDimitry Andric 
phis()291302affcbSDimitry Andric iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
29230785c0eSDimitry Andric   PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
29330785c0eSDimitry Andric   return make_range<phi_iterator>(P, nullptr);
294302affcbSDimitry Andric }
295302affcbSDimitry Andric 
296ff0cc061SDimitry Andric /// This method is used to notify a BasicBlock that the
297139f7f9bSDimitry Andric /// specified Predecessor of the block is no longer able to reach it.  This is
298139f7f9bSDimitry Andric /// actually not used to update the Predecessor list, but is actually used to
299139f7f9bSDimitry Andric /// update the PHI nodes that reside in the block.  Note that this should be
300139f7f9bSDimitry Andric /// called while the predecessor still refers to this block.
301139f7f9bSDimitry Andric ///
removePredecessor(BasicBlock * Pred,bool DontDeleteUselessPHIs)302139f7f9bSDimitry Andric void BasicBlock::removePredecessor(BasicBlock *Pred,
303139f7f9bSDimitry Andric                                    bool DontDeleteUselessPHIs) {
304139f7f9bSDimitry Andric   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
305139f7f9bSDimitry Andric           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
306139f7f9bSDimitry Andric          "removePredecessor: BB is not a predecessor!");
307139f7f9bSDimitry Andric 
308139f7f9bSDimitry Andric   if (InstList.empty()) return;
309139f7f9bSDimitry Andric   PHINode *APN = dyn_cast<PHINode>(&front());
310139f7f9bSDimitry Andric   if (!APN) return;   // Quick exit.
311139f7f9bSDimitry Andric 
312139f7f9bSDimitry Andric   // If there are exactly two predecessors, then we want to nuke the PHI nodes
313139f7f9bSDimitry Andric   // altogether.  However, we cannot do this, if this in this case:
314139f7f9bSDimitry Andric   //
315139f7f9bSDimitry Andric   //  Loop:
316139f7f9bSDimitry Andric   //    %x = phi [X, Loop]
317139f7f9bSDimitry Andric   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
318139f7f9bSDimitry Andric   //    br Loop                 ;; %x2 does not dominate all uses
319139f7f9bSDimitry Andric   //
320139f7f9bSDimitry Andric   // This is because the PHI node input is actually taken from the predecessor
321139f7f9bSDimitry Andric   // basic block.  The only case this can happen is with a self loop, so we
322139f7f9bSDimitry Andric   // check for this case explicitly now.
323139f7f9bSDimitry Andric   //
324139f7f9bSDimitry Andric   unsigned max_idx = APN->getNumIncomingValues();
325139f7f9bSDimitry Andric   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
326139f7f9bSDimitry Andric   if (max_idx == 2) {
327139f7f9bSDimitry Andric     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
328139f7f9bSDimitry Andric 
329139f7f9bSDimitry Andric     // Disable PHI elimination!
330139f7f9bSDimitry Andric     if (this == Other) max_idx = 3;
331139f7f9bSDimitry Andric   }
332139f7f9bSDimitry Andric 
333139f7f9bSDimitry Andric   // <= Two predecessors BEFORE I remove one?
334139f7f9bSDimitry Andric   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
335139f7f9bSDimitry Andric     // Yup, loop through and nuke the PHI nodes
336139f7f9bSDimitry Andric     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
337139f7f9bSDimitry Andric       // Remove the predecessor first.
338139f7f9bSDimitry Andric       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
339139f7f9bSDimitry Andric 
340139f7f9bSDimitry Andric       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
341139f7f9bSDimitry Andric       if (max_idx == 2) {
342139f7f9bSDimitry Andric         if (PN->getIncomingValue(0) != PN)
343139f7f9bSDimitry Andric           PN->replaceAllUsesWith(PN->getIncomingValue(0));
344139f7f9bSDimitry Andric         else
345139f7f9bSDimitry Andric           // We are left with an infinite loop with no entries: kill the PHI.
346139f7f9bSDimitry Andric           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
347139f7f9bSDimitry Andric         getInstList().pop_front();    // Remove the PHI node
348139f7f9bSDimitry Andric       }
349139f7f9bSDimitry Andric 
350139f7f9bSDimitry Andric       // If the PHI node already only had one entry, it got deleted by
351139f7f9bSDimitry Andric       // removeIncomingValue.
352139f7f9bSDimitry Andric     }
353139f7f9bSDimitry Andric   } else {
354139f7f9bSDimitry Andric     // Okay, now we know that we need to remove predecessor #pred_idx from all
355139f7f9bSDimitry Andric     // PHI nodes.  Iterate over each PHI node fixing them up
356139f7f9bSDimitry Andric     PHINode *PN;
357139f7f9bSDimitry Andric     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
358139f7f9bSDimitry Andric       ++II;
359139f7f9bSDimitry Andric       PN->removeIncomingValue(Pred, false);
360139f7f9bSDimitry Andric       // If all incoming values to the Phi are the same, we can replace the Phi
361139f7f9bSDimitry Andric       // with that value.
36291bc56edSDimitry Andric       Value* PNV = nullptr;
363139f7f9bSDimitry Andric       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
364139f7f9bSDimitry Andric         if (PNV != PN) {
365139f7f9bSDimitry Andric           PN->replaceAllUsesWith(PNV);
366139f7f9bSDimitry Andric           PN->eraseFromParent();
367139f7f9bSDimitry Andric         }
368139f7f9bSDimitry Andric     }
369139f7f9bSDimitry Andric   }
370139f7f9bSDimitry Andric }
371139f7f9bSDimitry Andric 
canSplitPredecessors() const3727d523365SDimitry Andric bool BasicBlock::canSplitPredecessors() const {
3737d523365SDimitry Andric   const Instruction *FirstNonPHI = getFirstNonPHI();
3747d523365SDimitry Andric   if (isa<LandingPadInst>(FirstNonPHI))
3757d523365SDimitry Andric     return true;
3767d523365SDimitry Andric   // This is perhaps a little conservative because constructs like
3777d523365SDimitry Andric   // CleanupBlockInst are pretty easy to split.  However, SplitBlockPredecessors
3787d523365SDimitry Andric   // cannot handle such things just yet.
3797d523365SDimitry Andric   if (FirstNonPHI->isEHPad())
3807d523365SDimitry Andric     return false;
3817d523365SDimitry Andric   return true;
3827d523365SDimitry Andric }
383139f7f9bSDimitry Andric 
isLegalToHoistInto() const384edd7eaddSDimitry Andric bool BasicBlock::isLegalToHoistInto() const {
385edd7eaddSDimitry Andric   auto *Term = getTerminator();
386edd7eaddSDimitry Andric   // No terminator means the block is under construction.
387edd7eaddSDimitry Andric   if (!Term)
388edd7eaddSDimitry Andric     return true;
389edd7eaddSDimitry Andric 
390edd7eaddSDimitry Andric   // If the block has no successors, there can be no instructions to hoist.
391edd7eaddSDimitry Andric   assert(Term->getNumSuccessors() > 0);
392edd7eaddSDimitry Andric 
393edd7eaddSDimitry Andric   // Instructions should not be hoisted across exception handling boundaries.
394*b5893f02SDimitry Andric   return !Term->isExceptionalTerminator();
395edd7eaddSDimitry Andric }
396edd7eaddSDimitry Andric 
397ff0cc061SDimitry Andric /// This splits a basic block into two at the specified
398139f7f9bSDimitry Andric /// instruction.  Note that all instructions BEFORE the specified iterator stay
399139f7f9bSDimitry Andric /// as part of the original basic block, an unconditional branch is added to
400139f7f9bSDimitry Andric /// the new BB, and the rest of the instructions in the BB are moved to the new
401139f7f9bSDimitry Andric /// BB, including the old terminator.  This invalidates the iterator.
402139f7f9bSDimitry Andric ///
403139f7f9bSDimitry Andric /// Note that this only works on well formed basic blocks (must have a
404139f7f9bSDimitry Andric /// terminator), and 'I' must not be the end of instruction list (which would
405139f7f9bSDimitry Andric /// cause a degenerate basic block to be formed, having a terminator inside of
406139f7f9bSDimitry Andric /// the basic block).
407139f7f9bSDimitry Andric ///
splitBasicBlock(iterator I,const Twine & BBName)408139f7f9bSDimitry Andric BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
409139f7f9bSDimitry Andric   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
410139f7f9bSDimitry Andric   assert(I != InstList.end() &&
411139f7f9bSDimitry Andric          "Trying to get me to create degenerate basic block!");
412139f7f9bSDimitry Andric 
4133ca95b02SDimitry Andric   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
4143ca95b02SDimitry Andric                                        this->getNextNode());
415139f7f9bSDimitry Andric 
4168f0fd8f6SDimitry Andric   // Save DebugLoc of split point before invalidating iterator.
4178f0fd8f6SDimitry Andric   DebugLoc Loc = I->getDebugLoc();
418139f7f9bSDimitry Andric   // Move all of the specified instructions from the original basic block into
419139f7f9bSDimitry Andric   // the new basic block.
420139f7f9bSDimitry Andric   New->getInstList().splice(New->end(), this->getInstList(), I, end());
421139f7f9bSDimitry Andric 
422139f7f9bSDimitry Andric   // Add a branch instruction to the newly formed basic block.
4238f0fd8f6SDimitry Andric   BranchInst *BI = BranchInst::Create(New, this);
4248f0fd8f6SDimitry Andric   BI->setDebugLoc(Loc);
425139f7f9bSDimitry Andric 
426139f7f9bSDimitry Andric   // Now we must loop through all of the successors of the New block (which
427139f7f9bSDimitry Andric   // _were_ the successors of the 'this' block), and update any PHI nodes in
428139f7f9bSDimitry Andric   // successors.  If there were PHI nodes in the successors, then they need to
429139f7f9bSDimitry Andric   // know that incoming branches will be from New, not from Old.
430139f7f9bSDimitry Andric   //
431139f7f9bSDimitry Andric   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
432139f7f9bSDimitry Andric     // Loop over any phi nodes in the basic block, updating the BB field of
433139f7f9bSDimitry Andric     // incoming values...
434139f7f9bSDimitry Andric     BasicBlock *Successor = *I;
435302affcbSDimitry Andric     for (auto &PN : Successor->phis()) {
436302affcbSDimitry Andric       int Idx = PN.getBasicBlockIndex(this);
437302affcbSDimitry Andric       while (Idx != -1) {
438302affcbSDimitry Andric         PN.setIncomingBlock((unsigned)Idx, New);
439302affcbSDimitry Andric         Idx = PN.getBasicBlockIndex(this);
440139f7f9bSDimitry Andric       }
441139f7f9bSDimitry Andric     }
442139f7f9bSDimitry Andric   }
443139f7f9bSDimitry Andric   return New;
444139f7f9bSDimitry Andric }
445139f7f9bSDimitry Andric 
replaceSuccessorsPhiUsesWith(BasicBlock * New)446139f7f9bSDimitry Andric void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
447*b5893f02SDimitry Andric   Instruction *TI = getTerminator();
448139f7f9bSDimitry Andric   if (!TI)
449139f7f9bSDimitry Andric     // Cope with being called on a BasicBlock that doesn't have a terminator
450139f7f9bSDimitry Andric     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
451139f7f9bSDimitry Andric     return;
452*b5893f02SDimitry Andric   for (BasicBlock *Succ : successors(TI)) {
453139f7f9bSDimitry Andric     // N.B. Succ might not be a complete BasicBlock, so don't assume
454139f7f9bSDimitry Andric     // that it ends with a non-phi instruction.
455139f7f9bSDimitry Andric     for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
456139f7f9bSDimitry Andric       PHINode *PN = dyn_cast<PHINode>(II);
457139f7f9bSDimitry Andric       if (!PN)
458139f7f9bSDimitry Andric         break;
459139f7f9bSDimitry Andric       int i;
460139f7f9bSDimitry Andric       while ((i = PN->getBasicBlockIndex(this)) >= 0)
461139f7f9bSDimitry Andric         PN->setIncomingBlock(i, New);
462139f7f9bSDimitry Andric     }
463139f7f9bSDimitry Andric   }
464139f7f9bSDimitry Andric }
465139f7f9bSDimitry Andric 
466ff0cc061SDimitry Andric /// Return true if this basic block is a landing pad. I.e., it's
467139f7f9bSDimitry Andric /// the destination of the 'unwind' edge of an invoke instruction.
isLandingPad() const468139f7f9bSDimitry Andric bool BasicBlock::isLandingPad() const {
469139f7f9bSDimitry Andric   return isa<LandingPadInst>(getFirstNonPHI());
470139f7f9bSDimitry Andric }
471139f7f9bSDimitry Andric 
472ff0cc061SDimitry Andric /// Return the landingpad instruction associated with the landing pad.
getLandingPadInst() const473139f7f9bSDimitry Andric const LandingPadInst *BasicBlock::getLandingPadInst() const {
474139f7f9bSDimitry Andric   return dyn_cast<LandingPadInst>(getFirstNonPHI());
475139f7f9bSDimitry Andric }
4762cab237bSDimitry Andric 
getIrrLoopHeaderWeight() const4772cab237bSDimitry Andric Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
478*b5893f02SDimitry Andric   const Instruction *TI = getTerminator();
4792cab237bSDimitry Andric   if (MDNode *MDIrrLoopHeader =
4802cab237bSDimitry Andric       TI->getMetadata(LLVMContext::MD_irr_loop)) {
4812cab237bSDimitry Andric     MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
4822cab237bSDimitry Andric     if (MDName->getString().equals("loop_header_weight")) {
4832cab237bSDimitry Andric       auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
4842cab237bSDimitry Andric       return Optional<uint64_t>(CI->getValue().getZExtValue());
4852cab237bSDimitry Andric     }
4862cab237bSDimitry Andric   }
4872cab237bSDimitry Andric   return Optional<uint64_t>();
4882cab237bSDimitry Andric }
4894ba319b5SDimitry Andric 
skipDebugIntrinsics(BasicBlock::iterator It)4904ba319b5SDimitry Andric BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
4914ba319b5SDimitry Andric   while (isa<DbgInfoIntrinsic>(It))
4924ba319b5SDimitry Andric     ++It;
4934ba319b5SDimitry Andric   return It;
4944ba319b5SDimitry Andric }
495