LLVM  3.7.0
BasicBlock.cpp
Go to the documentation of this file.
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"
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 using namespace llvm;
25 
27  if (Function *F = getParent())
28  return &F->getValueSymbolTable();
29  return nullptr;
30 }
31 
33  return getType()->getContext();
34 }
35 
36 // Explicit instantiation of SymbolTableListTraits since some of the methods
37 // are not in the public header file...
39 
40 
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 
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, this);
60  else
61  NewParent->getBasicBlockList().push_back(this);
62 }
63 
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 =
75  while (!use_empty()) {
76  BlockAddress *BA = cast<BlockAddress>(user_back());
78  BA->getType()));
79  BA->destroyConstant();
80  }
81  }
82 
83  assert(getParent() == nullptr && "BasicBlock still linked into the program!");
85  InstList.clear();
86 }
87 
88 void BasicBlock::setParent(Function *parent) {
89  // Set Parent=parent, updating instruction symtab entries as appropriate.
90  InstList.setSymTabObject(&Parent, parent);
91 }
92 
95 }
96 
98  return getParent()->getBasicBlockList().erase(this);
99 }
100 
101 /// Unlink this basic block from its current function and
102 /// insert it into the function that MovePos lives in, right before MovePos.
104  MovePos->getParent()->getBasicBlockList().splice(MovePos,
105  getParent()->getBasicBlockList(), this);
106 }
107 
108 /// Unlink this basic block from its current function and
109 /// insert it into the function that MovePos lives in, right after MovePos.
111  Function::iterator I = MovePos;
112  MovePos->getParent()->getBasicBlockList().splice(++I,
113  getParent()->getBasicBlockList(), this);
114 }
115 
117  return getParent()->getParent();
118 }
119 
121  return getParent()->getParent();
122 }
123 
125  if (InstList.empty()) return nullptr;
126  return dyn_cast<TerminatorInst>(&InstList.back());
127 }
128 
130  if (InstList.empty()) return nullptr;
131  return dyn_cast<TerminatorInst>(&InstList.back());
132 }
133 
135  if (InstList.empty())
136  return nullptr;
137  ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
138  if (!RI || RI == &InstList.front())
139  return nullptr;
140 
141  Instruction *Prev = RI->getPrevNode();
142  if (!Prev)
143  return nullptr;
144 
145  if (Value *RV = RI->getReturnValue()) {
146  if (RV != Prev)
147  return nullptr;
148 
149  // Look through the optional bitcast.
150  if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
151  RV = BI->getOperand(0);
152  Prev = BI->getPrevNode();
153  if (!Prev || RV != Prev)
154  return nullptr;
155  }
156  }
157 
158  if (auto *CI = dyn_cast<CallInst>(Prev)) {
159  if (CI->isMustTailCall())
160  return CI;
161  }
162  return nullptr;
163 }
164 
166  for (Instruction &I : *this)
167  if (!isa<PHINode>(I))
168  return &I;
169  return nullptr;
170 }
171 
173  for (Instruction &I : *this)
174  if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
175  return &I;
176  return nullptr;
177 }
178 
180  for (Instruction &I : *this) {
181  if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
182  continue;
183 
184  if (auto *II = dyn_cast<IntrinsicInst>(&I))
185  if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
186  II->getIntrinsicID() == Intrinsic::lifetime_end)
187  continue;
188 
189  return &I;
190  }
191  return nullptr;
192 }
193 
195  Instruction *FirstNonPHI = getFirstNonPHI();
196  if (!FirstNonPHI)
197  return end();
198 
199  iterator InsertPt = FirstNonPHI;
200  if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
201  return InsertPt;
202 }
203 
205  for(iterator I = begin(), E = end(); I != E; ++I)
206  I->dropAllReferences();
207 }
208 
209 /// If this basic block has a single predecessor block,
210 /// return the block, otherwise return a null pointer.
212  pred_iterator PI = pred_begin(this), E = pred_end(this);
213  if (PI == E) return nullptr; // No preds.
214  BasicBlock *ThePred = *PI;
215  ++PI;
216  return (PI == E) ? ThePred : nullptr /*multiple preds*/;
217 }
218 
219 /// If this basic block has a unique predecessor block,
220 /// return the block, otherwise return a null pointer.
221 /// Note that unique predecessor doesn't mean single edge, there can be
222 /// multiple edges from the unique predecessor to this block (for example
223 /// a switch statement with multiple cases having the same destination).
225  pred_iterator PI = pred_begin(this), E = pred_end(this);
226  if (PI == E) return nullptr; // No preds.
227  BasicBlock *PredBB = *PI;
228  ++PI;
229  for (;PI != E; ++PI) {
230  if (*PI != PredBB)
231  return nullptr;
232  // The same predecessor appears multiple times in the predecessor list.
233  // This is OK.
234  }
235  return PredBB;
236 }
237 
239  succ_iterator SI = succ_begin(this), E = succ_end(this);
240  if (SI == E) return nullptr; // no successors
241  BasicBlock *TheSucc = *SI;
242  ++SI;
243  return (SI == E) ? TheSucc : nullptr /* multiple successors */;
244 }
245 
247  succ_iterator SI = succ_begin(this), E = succ_end(this);
248  if (SI == E) return NULL; // No successors
249  BasicBlock *SuccBB = *SI;
250  ++SI;
251  for (;SI != E; ++SI) {
252  if (*SI != SuccBB)
253  return NULL;
254  // The same successor appears multiple times in the successor list.
255  // This is OK.
256  }
257  return SuccBB;
258 }
259 
260 /// This method is used to notify a BasicBlock that the
261 /// specified Predecessor of the block is no longer able to reach it. This is
262 /// actually not used to update the Predecessor list, but is actually used to
263 /// update the PHI nodes that reside in the block. Note that this should be
264 /// called while the predecessor still refers to this block.
265 ///
267  bool DontDeleteUselessPHIs) {
268  assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
269  find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
270  "removePredecessor: BB is not a predecessor!");
271 
272  if (InstList.empty()) return;
273  PHINode *APN = dyn_cast<PHINode>(&front());
274  if (!APN) return; // Quick exit.
275 
276  // If there are exactly two predecessors, then we want to nuke the PHI nodes
277  // altogether. However, we cannot do this, if this in this case:
278  //
279  // Loop:
280  // %x = phi [X, Loop]
281  // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
282  // br Loop ;; %x2 does not dominate all uses
283  //
284  // This is because the PHI node input is actually taken from the predecessor
285  // basic block. The only case this can happen is with a self loop, so we
286  // check for this case explicitly now.
287  //
288  unsigned max_idx = APN->getNumIncomingValues();
289  assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
290  if (max_idx == 2) {
291  BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
292 
293  // Disable PHI elimination!
294  if (this == Other) max_idx = 3;
295  }
296 
297  // <= Two predecessors BEFORE I remove one?
298  if (max_idx <= 2 && !DontDeleteUselessPHIs) {
299  // Yup, loop through and nuke the PHI nodes
300  while (PHINode *PN = dyn_cast<PHINode>(&front())) {
301  // Remove the predecessor first.
302  PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
303 
304  // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
305  if (max_idx == 2) {
306  if (PN->getIncomingValue(0) != PN)
307  PN->replaceAllUsesWith(PN->getIncomingValue(0));
308  else
309  // We are left with an infinite loop with no entries: kill the PHI.
310  PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
311  getInstList().pop_front(); // Remove the PHI node
312  }
313 
314  // If the PHI node already only had one entry, it got deleted by
315  // removeIncomingValue.
316  }
317  } else {
318  // Okay, now we know that we need to remove predecessor #pred_idx from all
319  // PHI nodes. Iterate over each PHI node fixing them up
320  PHINode *PN;
321  for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
322  ++II;
323  PN->removeIncomingValue(Pred, false);
324  // If all incoming values to the Phi are the same, we can replace the Phi
325  // with that value.
326  Value* PNV = nullptr;
327  if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
328  if (PNV != PN) {
329  PN->replaceAllUsesWith(PNV);
330  PN->eraseFromParent();
331  }
332  }
333  }
334 }
335 
336 
337 /// This splits a basic block into two at the specified
338 /// instruction. Note that all instructions BEFORE the specified iterator stay
339 /// as part of the original basic block, an unconditional branch is added to
340 /// the new BB, and the rest of the instructions in the BB are moved to the new
341 /// BB, including the old terminator. This invalidates the iterator.
342 ///
343 /// Note that this only works on well formed basic blocks (must have a
344 /// terminator), and 'I' must not be the end of instruction list (which would
345 /// cause a degenerate basic block to be formed, having a terminator inside of
346 /// the basic block).
347 ///
349  assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
350  assert(I != InstList.end() &&
351  "Trying to get me to create degenerate basic block!");
352 
353  BasicBlock *InsertBefore = std::next(Function::iterator(this))
354  .getNodePtrUnchecked();
355  BasicBlock *New = BasicBlock::Create(getContext(), BBName,
356  getParent(), InsertBefore);
357 
358  // Save DebugLoc of split point before invalidating iterator.
359  DebugLoc Loc = I->getDebugLoc();
360  // Move all of the specified instructions from the original basic block into
361  // the new basic block.
362  New->getInstList().splice(New->end(), this->getInstList(), I, end());
363 
364  // Add a branch instruction to the newly formed basic block.
365  BranchInst *BI = BranchInst::Create(New, this);
366  BI->setDebugLoc(Loc);
367 
368  // Now we must loop through all of the successors of the New block (which
369  // _were_ the successors of the 'this' block), and update any PHI nodes in
370  // successors. If there were PHI nodes in the successors, then they need to
371  // know that incoming branches will be from New, not from Old.
372  //
373  for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
374  // Loop over any phi nodes in the basic block, updating the BB field of
375  // incoming values...
376  BasicBlock *Successor = *I;
377  PHINode *PN;
378  for (BasicBlock::iterator II = Successor->begin();
379  (PN = dyn_cast<PHINode>(II)); ++II) {
380  int IDX = PN->getBasicBlockIndex(this);
381  while (IDX != -1) {
382  PN->setIncomingBlock((unsigned)IDX, New);
383  IDX = PN->getBasicBlockIndex(this);
384  }
385  }
386  }
387  return New;
388 }
389 
392  if (!TI)
393  // Cope with being called on a BasicBlock that doesn't have a terminator
394  // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
395  return;
396  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
397  BasicBlock *Succ = TI->getSuccessor(i);
398  // N.B. Succ might not be a complete BasicBlock, so don't assume
399  // that it ends with a non-phi instruction.
400  for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
401  PHINode *PN = dyn_cast<PHINode>(II);
402  if (!PN)
403  break;
404  int i;
405  while ((i = PN->getBasicBlockIndex(this)) >= 0)
406  PN->setIncomingBlock(i, New);
407  }
408  }
409 }
410 
411 /// Return true if this basic block is a landing pad. I.e., it's
412 /// the destination of the 'unwind' edge of an invoke instruction.
414  return isa<LandingPadInst>(getFirstNonPHI());
415 }
416 
417 /// Return the landingpad instruction associated with the landing pad.
420 }
423 }
ReturnInst - Return a value (possibly void), from a function.
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
Definition: Instruction.cpp:70
BasicBlock * getUniqueSuccessor()
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:246
This class provides a symbol table of name/value pairs.
BasicBlock * getUniquePredecessor()
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:224
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
Definition: BasicBlock.cpp:266
void insertInto(Function *Parent, BasicBlock *InsertBefore=nullptr)
Insert unlinked basic block into a function.
Definition: BasicBlock.cpp:54
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
CallInst * getTerminatingMustTailCall()
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
Definition: BasicBlock.cpp:134
CallInst - This class represents a function call, abstracting a target machine's calling convention...
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1822
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:111
A debug info location.
Definition: DebugLoc.h:34
const Instruction & front() const
Definition: BasicBlock.h:243
F(f)
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
Instruction * getFirstNonPHIOrDbg()
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
Definition: BasicBlock.cpp:172
BlockAddress - The address of a basic block.
Definition: Constants.h:802
void push_back(NodeTy *val)
Definition: ilist.h:554
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
removeIncomingValue - Remove an incoming value.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
Definition: BasicBlock.cpp:116
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:165
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:306
NodeTy * getPrevNode()
Get the previous node, or 0 for the list head.
Definition: ilist_node.h:58
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:250
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:591
void clear()
Definition: ilist.h:550
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:104
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
Definition: Type.h:125
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:351
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:107
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Definition: InstrTypes.h:57
void replaceSuccessorsPhiUsesWith(BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of to it...
Definition: BasicBlock.cpp:390
LandingPadInst - The landingpad instruction holds all of the information necessary to generate correc...
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:35
void setDebugLoc(DebugLoc Loc)
setDebugLoc - Set the debug location information for this instruction.
Definition: Instruction.h:227
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
Value * hasConstantValue() const
hasConstantValue - If the specified PHI node always merges together the same value, return the value, otherwise return null.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
Definition: InstrTypes.h:62
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:41
BranchInst - Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
LandingPadInst * getLandingPadInst()
Return the landingpad instruction associated with the landing pad.
Definition: BasicBlock.cpp:418
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:114
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:252
iterator insert(iterator where, NodeTy *New)
Definition: ilist.h:412
Value * getOperand(unsigned i) const
Definition: User.h:118
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:117
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:103
static UndefValue * get(Type *T)
get() - Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1473
Instruction * getFirstNonPHIOrDbgOrLifetime()
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
Definition: BasicBlock.cpp:179
iplist - The subset of list functionality that can safely be used on nodes of polymorphic types...
Definition: ilist.h:49
iterator erase(iterator where)
Definition: ilist.h:465
void removeFromParent()
Unlink 'this' from the containing function, but do not delete it.
Definition: BasicBlock.cpp:93
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
Definition: BasicBlock.cpp:110
const BasicBlockListType & getBasicBlockList() const
Definition: Function.h:436
void setIncomingBlock(unsigned i, BasicBlock *BB)
iterator end()
Definition: BasicBlock.h:233
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: ilist.h:385
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:582
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
void splice(iterator where, iplist &L2)
Definition: ilist.h:570
~BasicBlock() override
Definition: BasicBlock.cpp:64
BasicBlock * getSingleSuccessor()
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:238
BasicBlock * getSinglePredecessor()
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:211
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
reference front()
Definition: ilist.h:390
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:239
iplist< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition: BasicBlock.cpp:97
ValueSymbolTable * getValueSymbolTable()
Returns a pointer to the symbol table if one exists.
Definition: BasicBlock.cpp:26
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:413
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition: Constants.cpp:279
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:348
reference back()
Definition: ilist.h:398
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
Definition: Value.cpp:104
bool use_empty() const
Definition: Value.h:275
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:32
iterator end()
Definition: ilist.h:367
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:365
LLVM Value Representation.
Definition: Value.h:69
void pop_front()
Definition: ilist.h:555
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:194
NodeTy * remove(iterator &IT)
Definition: ilist.h:435
int getBasicBlockIndex(const BasicBlock *BB) const
getBasicBlockIndex - Return the first index of the specified basic block in the value list for this P...
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.cpp:103
void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
Definition: BasicBlock.cpp:204
User * user_back()
Definition: Value.h:298