1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the BasicBlock class for the IR library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/BasicBlock.h" 15 #include "SymbolTableListTraitsImpl.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/IR/CFG.h" 18 #include "llvm/IR/Constants.h" 19 #include "llvm/IR/Instructions.h" 20 #include "llvm/IR/IntrinsicInst.h" 21 #include "llvm/IR/LLVMContext.h" 22 #include "llvm/IR/Type.h" 23 #include <algorithm> 24 using namespace llvm; 25 26 ValueSymbolTable *BasicBlock::getValueSymbolTable() { 27 if (Function *F = getParent()) 28 return &F->getValueSymbolTable(); 29 return nullptr; 30 } 31 32 const DataLayout *BasicBlock::getDataLayout() const { 33 return getParent()->getDataLayout(); 34 } 35 36 LLVMContext &BasicBlock::getContext() const { 37 return getType()->getContext(); 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, BasicBlock>; 43 44 45 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent, 46 BasicBlock *InsertBefore) 47 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) { 48 49 if (NewParent) 50 insertInto(NewParent, InsertBefore); 51 else 52 assert(!InsertBefore && 53 "Cannot insert block before another block with no function!"); 54 55 setName(Name); 56 } 57 58 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) { 59 assert(NewParent && "Expected a parent"); 60 assert(!Parent && "Already has a parent"); 61 62 if (InsertBefore) 63 NewParent->getBasicBlockList().insert(InsertBefore, this); 64 else 65 NewParent->getBasicBlockList().push_back(this); 66 } 67 68 BasicBlock::~BasicBlock() { 69 // If the address of the block is taken and it is being deleted (e.g. because 70 // it is dead), this means that there is either a dangling constant expr 71 // hanging off the block, or an undefined use of the block (source code 72 // expecting the address of a label to keep the block alive even though there 73 // is no indirect branch). Handle these cases by zapping the BlockAddress 74 // nodes. There are no other possible uses at this point. 75 if (hasAddressTaken()) { 76 assert(!use_empty() && "There should be at least one blockaddress!"); 77 Constant *Replacement = 78 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1); 79 while (!use_empty()) { 80 BlockAddress *BA = cast<BlockAddress>(user_back()); 81 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement, 82 BA->getType())); 83 BA->destroyConstant(); 84 } 85 } 86 87 assert(getParent() == nullptr && "BasicBlock still linked into the program!"); 88 dropAllReferences(); 89 InstList.clear(); 90 } 91 92 void BasicBlock::setParent(Function *parent) { 93 // Set Parent=parent, updating instruction symtab entries as appropriate. 94 InstList.setSymTabObject(&Parent, parent); 95 } 96 97 void BasicBlock::removeFromParent() { 98 getParent()->getBasicBlockList().remove(this); 99 } 100 101 void BasicBlock::eraseFromParent() { 102 getParent()->getBasicBlockList().erase(this); 103 } 104 105 /// moveBefore - Unlink this basic block from its current function and 106 /// insert it into the function that MovePos lives in, right before MovePos. 107 void BasicBlock::moveBefore(BasicBlock *MovePos) { 108 MovePos->getParent()->getBasicBlockList().splice(MovePos, 109 getParent()->getBasicBlockList(), this); 110 } 111 112 /// moveAfter - Unlink this basic block from its current function and 113 /// insert it into the function that MovePos lives in, right after MovePos. 114 void BasicBlock::moveAfter(BasicBlock *MovePos) { 115 Function::iterator I = MovePos; 116 MovePos->getParent()->getBasicBlockList().splice(++I, 117 getParent()->getBasicBlockList(), this); 118 } 119 120 121 TerminatorInst *BasicBlock::getTerminator() { 122 if (InstList.empty()) return nullptr; 123 return dyn_cast<TerminatorInst>(&InstList.back()); 124 } 125 126 const TerminatorInst *BasicBlock::getTerminator() const { 127 if (InstList.empty()) return nullptr; 128 return dyn_cast<TerminatorInst>(&InstList.back()); 129 } 130 131 CallInst *BasicBlock::getTerminatingMustTailCall() { 132 if (InstList.empty()) 133 return nullptr; 134 ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back()); 135 if (!RI || RI == &InstList.front()) 136 return nullptr; 137 138 Instruction *Prev = RI->getPrevNode(); 139 if (!Prev) 140 return nullptr; 141 142 if (Value *RV = RI->getReturnValue()) { 143 if (RV != Prev) 144 return nullptr; 145 146 // Look through the optional bitcast. 147 if (auto *BI = dyn_cast<BitCastInst>(Prev)) { 148 RV = BI->getOperand(0); 149 Prev = BI->getPrevNode(); 150 if (!Prev || RV != Prev) 151 return nullptr; 152 } 153 } 154 155 if (auto *CI = dyn_cast<CallInst>(Prev)) { 156 if (CI->isMustTailCall()) 157 return CI; 158 } 159 return nullptr; 160 } 161 162 Instruction* BasicBlock::getFirstNonPHI() { 163 BasicBlock::iterator i = begin(); 164 // All valid basic blocks should have a terminator, 165 // which is not a PHINode. If we have an invalid basic 166 // block we'll get an assertion failure when dereferencing 167 // a past-the-end iterator. 168 while (isa<PHINode>(i)) ++i; 169 return &*i; 170 } 171 172 Instruction* BasicBlock::getFirstNonPHIOrDbg() { 173 BasicBlock::iterator i = begin(); 174 // All valid basic blocks should have a terminator, 175 // which is not a PHINode. If we have an invalid basic 176 // block we'll get an assertion failure when dereferencing 177 // a past-the-end iterator. 178 while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i; 179 return &*i; 180 } 181 182 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() { 183 // All valid basic blocks should have a terminator, 184 // which is not a PHINode. If we have an invalid basic 185 // block we'll get an assertion failure when dereferencing 186 // a past-the-end iterator. 187 BasicBlock::iterator i = begin(); 188 for (;; ++i) { 189 if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) 190 continue; 191 192 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i); 193 if (!II) 194 break; 195 if (II->getIntrinsicID() != Intrinsic::lifetime_start && 196 II->getIntrinsicID() != Intrinsic::lifetime_end) 197 break; 198 } 199 return &*i; 200 } 201 202 BasicBlock::iterator BasicBlock::getFirstInsertionPt() { 203 iterator InsertPt = getFirstNonPHI(); 204 if (isa<LandingPadInst>(InsertPt)) ++InsertPt; 205 return InsertPt; 206 } 207 208 void BasicBlock::dropAllReferences() { 209 for(iterator I = begin(), E = end(); I != E; ++I) 210 I->dropAllReferences(); 211 } 212 213 /// getSinglePredecessor - If this basic block has a single predecessor block, 214 /// return the block, otherwise return a null pointer. 215 BasicBlock *BasicBlock::getSinglePredecessor() { 216 pred_iterator PI = pred_begin(this), E = pred_end(this); 217 if (PI == E) return nullptr; // No preds. 218 BasicBlock *ThePred = *PI; 219 ++PI; 220 return (PI == E) ? ThePred : nullptr /*multiple preds*/; 221 } 222 223 /// getUniquePredecessor - If this basic block has a unique predecessor block, 224 /// return the block, otherwise return a null pointer. 225 /// Note that unique predecessor doesn't mean single edge, there can be 226 /// multiple edges from the unique predecessor to this block (for example 227 /// a switch statement with multiple cases having the same destination). 228 BasicBlock *BasicBlock::getUniquePredecessor() { 229 pred_iterator PI = pred_begin(this), E = pred_end(this); 230 if (PI == E) return nullptr; // No preds. 231 BasicBlock *PredBB = *PI; 232 ++PI; 233 for (;PI != E; ++PI) { 234 if (*PI != PredBB) 235 return nullptr; 236 // The same predecessor appears multiple times in the predecessor list. 237 // This is OK. 238 } 239 return PredBB; 240 } 241 242 /// removePredecessor - This method is used to notify a BasicBlock that the 243 /// specified Predecessor of the block is no longer able to reach it. This is 244 /// actually not used to update the Predecessor list, but is actually used to 245 /// update the PHI nodes that reside in the block. Note that this should be 246 /// called while the predecessor still refers to this block. 247 /// 248 void BasicBlock::removePredecessor(BasicBlock *Pred, 249 bool DontDeleteUselessPHIs) { 250 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs. 251 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) && 252 "removePredecessor: BB is not a predecessor!"); 253 254 if (InstList.empty()) return; 255 PHINode *APN = dyn_cast<PHINode>(&front()); 256 if (!APN) return; // Quick exit. 257 258 // If there are exactly two predecessors, then we want to nuke the PHI nodes 259 // altogether. However, we cannot do this, if this in this case: 260 // 261 // Loop: 262 // %x = phi [X, Loop] 263 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1 264 // br Loop ;; %x2 does not dominate all uses 265 // 266 // This is because the PHI node input is actually taken from the predecessor 267 // basic block. The only case this can happen is with a self loop, so we 268 // check for this case explicitly now. 269 // 270 unsigned max_idx = APN->getNumIncomingValues(); 271 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!"); 272 if (max_idx == 2) { 273 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred); 274 275 // Disable PHI elimination! 276 if (this == Other) max_idx = 3; 277 } 278 279 // <= Two predecessors BEFORE I remove one? 280 if (max_idx <= 2 && !DontDeleteUselessPHIs) { 281 // Yup, loop through and nuke the PHI nodes 282 while (PHINode *PN = dyn_cast<PHINode>(&front())) { 283 // Remove the predecessor first. 284 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs); 285 286 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value 287 if (max_idx == 2) { 288 if (PN->getIncomingValue(0) != PN) 289 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 290 else 291 // We are left with an infinite loop with no entries: kill the PHI. 292 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 293 getInstList().pop_front(); // Remove the PHI node 294 } 295 296 // If the PHI node already only had one entry, it got deleted by 297 // removeIncomingValue. 298 } 299 } else { 300 // Okay, now we know that we need to remove predecessor #pred_idx from all 301 // PHI nodes. Iterate over each PHI node fixing them up 302 PHINode *PN; 303 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) { 304 ++II; 305 PN->removeIncomingValue(Pred, false); 306 // If all incoming values to the Phi are the same, we can replace the Phi 307 // with that value. 308 Value* PNV = nullptr; 309 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) 310 if (PNV != PN) { 311 PN->replaceAllUsesWith(PNV); 312 PN->eraseFromParent(); 313 } 314 } 315 } 316 } 317 318 319 /// splitBasicBlock - This splits a basic block into two at the specified 320 /// instruction. Note that all instructions BEFORE the specified iterator stay 321 /// as part of the original basic block, an unconditional branch is added to 322 /// the new BB, and the rest of the instructions in the BB are moved to the new 323 /// BB, including the old terminator. This invalidates the iterator. 324 /// 325 /// Note that this only works on well formed basic blocks (must have a 326 /// terminator), and 'I' must not be the end of instruction list (which would 327 /// cause a degenerate basic block to be formed, having a terminator inside of 328 /// the basic block). 329 /// 330 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) { 331 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!"); 332 assert(I != InstList.end() && 333 "Trying to get me to create degenerate basic block!"); 334 335 BasicBlock *InsertBefore = std::next(Function::iterator(this)) 336 .getNodePtrUnchecked(); 337 BasicBlock *New = BasicBlock::Create(getContext(), BBName, 338 getParent(), InsertBefore); 339 340 // Move all of the specified instructions from the original basic block into 341 // the new basic block. 342 New->getInstList().splice(New->end(), this->getInstList(), I, end()); 343 344 // Add a branch instruction to the newly formed basic block. 345 BranchInst::Create(New, this); 346 347 // Now we must loop through all of the successors of the New block (which 348 // _were_ the successors of the 'this' block), and update any PHI nodes in 349 // successors. If there were PHI nodes in the successors, then they need to 350 // know that incoming branches will be from New, not from Old. 351 // 352 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) { 353 // Loop over any phi nodes in the basic block, updating the BB field of 354 // incoming values... 355 BasicBlock *Successor = *I; 356 PHINode *PN; 357 for (BasicBlock::iterator II = Successor->begin(); 358 (PN = dyn_cast<PHINode>(II)); ++II) { 359 int IDX = PN->getBasicBlockIndex(this); 360 while (IDX != -1) { 361 PN->setIncomingBlock((unsigned)IDX, New); 362 IDX = PN->getBasicBlockIndex(this); 363 } 364 } 365 } 366 return New; 367 } 368 369 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) { 370 TerminatorInst *TI = getTerminator(); 371 if (!TI) 372 // Cope with being called on a BasicBlock that doesn't have a terminator 373 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this. 374 return; 375 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 376 BasicBlock *Succ = TI->getSuccessor(i); 377 // N.B. Succ might not be a complete BasicBlock, so don't assume 378 // that it ends with a non-phi instruction. 379 for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) { 380 PHINode *PN = dyn_cast<PHINode>(II); 381 if (!PN) 382 break; 383 int i; 384 while ((i = PN->getBasicBlockIndex(this)) >= 0) 385 PN->setIncomingBlock(i, New); 386 } 387 } 388 } 389 390 /// isLandingPad - Return true if this basic block is a landing pad. I.e., it's 391 /// the destination of the 'unwind' edge of an invoke instruction. 392 bool BasicBlock::isLandingPad() const { 393 return isa<LandingPadInst>(getFirstNonPHI()); 394 } 395 396 /// getLandingPadInst() - Return the landingpad instruction associated with 397 /// the landing pad. 398 LandingPadInst *BasicBlock::getLandingPadInst() { 399 return dyn_cast<LandingPadInst>(getFirstNonPHI()); 400 } 401 const LandingPadInst *BasicBlock::getLandingPadInst() const { 402 return dyn_cast<LandingPadInst>(getFirstNonPHI()); 403 } 404