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