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