1 //===-- Local.cpp - Functions to perform local transformations ------------===// 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 family of functions perform various local transformations to the 11 // program. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/Local.h" 16 #include "llvm/Constants.h" 17 #include "llvm/GlobalAlias.h" 18 #include "llvm/GlobalVariable.h" 19 #include "llvm/DerivedTypes.h" 20 #include "llvm/Instructions.h" 21 #include "llvm/Intrinsics.h" 22 #include "llvm/IntrinsicInst.h" 23 #include "llvm/Operator.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/Analysis/DebugInfo.h" 27 #include "llvm/Analysis/DIBuilder.h" 28 #include "llvm/Analysis/Dominators.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/InstructionSimplify.h" 31 #include "llvm/Analysis/ProfileInfo.h" 32 #include "llvm/Analysis/ValueTracking.h" 33 #include "llvm/Target/TargetData.h" 34 #include "llvm/Support/CFG.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/GetElementPtrTypeIterator.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Support/ValueHandle.h" 39 #include "llvm/Support/raw_ostream.h" 40 using namespace llvm; 41 42 //===----------------------------------------------------------------------===// 43 // Local constant propagation. 44 // 45 46 // ConstantFoldTerminator - If a terminator instruction is predicated on a 47 // constant value, convert it into an unconditional branch to the constant 48 // destination. 49 // 50 bool llvm::ConstantFoldTerminator(BasicBlock *BB) { 51 TerminatorInst *T = BB->getTerminator(); 52 53 // Branch - See if we are conditional jumping on constant 54 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 55 if (BI->isUnconditional()) return false; // Can't optimize uncond branch 56 BasicBlock *Dest1 = BI->getSuccessor(0); 57 BasicBlock *Dest2 = BI->getSuccessor(1); 58 59 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) { 60 // Are we branching on constant? 61 // YES. Change to unconditional branch... 62 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2; 63 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1; 64 65 //cerr << "Function: " << T->getParent()->getParent() 66 // << "\nRemoving branch from " << T->getParent() 67 // << "\n\nTo: " << OldDest << endl; 68 69 // Let the basic block know that we are letting go of it. Based on this, 70 // it will adjust it's PHI nodes. 71 assert(BI->getParent() && "Terminator not inserted in block!"); 72 OldDest->removePredecessor(BI->getParent()); 73 74 // Replace the conditional branch with an unconditional one. 75 BranchInst::Create(Destination, BI); 76 BI->eraseFromParent(); 77 return true; 78 } 79 80 if (Dest2 == Dest1) { // Conditional branch to same location? 81 // This branch matches something like this: 82 // br bool %cond, label %Dest, label %Dest 83 // and changes it into: br label %Dest 84 85 // Let the basic block know that we are letting go of one copy of it. 86 assert(BI->getParent() && "Terminator not inserted in block!"); 87 Dest1->removePredecessor(BI->getParent()); 88 89 // Replace the conditional branch with an unconditional one. 90 BranchInst::Create(Dest1, BI); 91 BI->eraseFromParent(); 92 return true; 93 } 94 return false; 95 } 96 97 if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { 98 // If we are switching on a constant, we can convert the switch into a 99 // single branch instruction! 100 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); 101 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest 102 BasicBlock *DefaultDest = TheOnlyDest; 103 assert(TheOnlyDest == SI->getDefaultDest() && 104 "Default destination is not successor #0?"); 105 106 // Figure out which case it goes to. 107 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) { 108 // Found case matching a constant operand? 109 if (SI->getSuccessorValue(i) == CI) { 110 TheOnlyDest = SI->getSuccessor(i); 111 break; 112 } 113 114 // Check to see if this branch is going to the same place as the default 115 // dest. If so, eliminate it as an explicit compare. 116 if (SI->getSuccessor(i) == DefaultDest) { 117 // Remove this entry. 118 DefaultDest->removePredecessor(SI->getParent()); 119 SI->removeCase(i); 120 --i; --e; // Don't skip an entry... 121 continue; 122 } 123 124 // Otherwise, check to see if the switch only branches to one destination. 125 // We do this by reseting "TheOnlyDest" to null when we find two non-equal 126 // destinations. 127 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0; 128 } 129 130 if (CI && !TheOnlyDest) { 131 // Branching on a constant, but not any of the cases, go to the default 132 // successor. 133 TheOnlyDest = SI->getDefaultDest(); 134 } 135 136 // If we found a single destination that we can fold the switch into, do so 137 // now. 138 if (TheOnlyDest) { 139 // Insert the new branch. 140 BranchInst::Create(TheOnlyDest, SI); 141 BasicBlock *BB = SI->getParent(); 142 143 // Remove entries from PHI nodes which we no longer branch to... 144 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { 145 // Found case matching a constant operand? 146 BasicBlock *Succ = SI->getSuccessor(i); 147 if (Succ == TheOnlyDest) 148 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest 149 else 150 Succ->removePredecessor(BB); 151 } 152 153 // Delete the old switch. 154 BB->getInstList().erase(SI); 155 return true; 156 } 157 158 if (SI->getNumSuccessors() == 2) { 159 // Otherwise, we can fold this switch into a conditional branch 160 // instruction if it has only one non-default destination. 161 Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(), 162 SI->getSuccessorValue(1), "cond"); 163 // Insert the new branch. 164 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI); 165 166 // Delete the old switch. 167 SI->eraseFromParent(); 168 return true; 169 } 170 return false; 171 } 172 173 if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) { 174 // indirectbr blockaddress(@F, @BB) -> br label @BB 175 if (BlockAddress *BA = 176 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) { 177 BasicBlock *TheOnlyDest = BA->getBasicBlock(); 178 // Insert the new branch. 179 BranchInst::Create(TheOnlyDest, IBI); 180 181 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 182 if (IBI->getDestination(i) == TheOnlyDest) 183 TheOnlyDest = 0; 184 else 185 IBI->getDestination(i)->removePredecessor(IBI->getParent()); 186 } 187 IBI->eraseFromParent(); 188 189 // If we didn't find our destination in the IBI successor list, then we 190 // have undefined behavior. Replace the unconditional branch with an 191 // 'unreachable' instruction. 192 if (TheOnlyDest) { 193 BB->getTerminator()->eraseFromParent(); 194 new UnreachableInst(BB->getContext(), BB); 195 } 196 197 return true; 198 } 199 } 200 201 return false; 202 } 203 204 205 //===----------------------------------------------------------------------===// 206 // Local dead code elimination. 207 // 208 209 /// isInstructionTriviallyDead - Return true if the result produced by the 210 /// instruction is not used, and the instruction has no side effects. 211 /// 212 bool llvm::isInstructionTriviallyDead(Instruction *I) { 213 if (!I->use_empty() || isa<TerminatorInst>(I)) return false; 214 215 // We don't want debug info removed by anything this general, unless 216 // debug info is empty. 217 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) { 218 if (DDI->getAddress()) 219 return false; 220 return true; 221 } 222 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) { 223 if (DVI->getValue()) 224 return false; 225 return true; 226 } 227 228 if (!I->mayHaveSideEffects()) return true; 229 230 // Special case intrinsics that "may have side effects" but can be deleted 231 // when dead. 232 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 233 // Safe to delete llvm.stacksave if dead. 234 if (II->getIntrinsicID() == Intrinsic::stacksave) 235 return true; 236 return false; 237 } 238 239 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a 240 /// trivially dead instruction, delete it. If that makes any of its operands 241 /// trivially dead, delete them too, recursively. Return true if any 242 /// instructions were deleted. 243 bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) { 244 Instruction *I = dyn_cast<Instruction>(V); 245 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I)) 246 return false; 247 248 SmallVector<Instruction*, 16> DeadInsts; 249 DeadInsts.push_back(I); 250 251 do { 252 I = DeadInsts.pop_back_val(); 253 254 // Null out all of the instruction's operands to see if any operand becomes 255 // dead as we go. 256 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 257 Value *OpV = I->getOperand(i); 258 I->setOperand(i, 0); 259 260 if (!OpV->use_empty()) continue; 261 262 // If the operand is an instruction that became dead as we nulled out the 263 // operand, and if it is 'trivially' dead, delete it in a future loop 264 // iteration. 265 if (Instruction *OpI = dyn_cast<Instruction>(OpV)) 266 if (isInstructionTriviallyDead(OpI)) 267 DeadInsts.push_back(OpI); 268 } 269 270 I->eraseFromParent(); 271 } while (!DeadInsts.empty()); 272 273 return true; 274 } 275 276 /// areAllUsesEqual - Check whether the uses of a value are all the same. 277 /// This is similar to Instruction::hasOneUse() except this will also return 278 /// true when there are no uses or multiple uses that all refer to the same 279 /// value. 280 static bool areAllUsesEqual(Instruction *I) { 281 Value::use_iterator UI = I->use_begin(); 282 Value::use_iterator UE = I->use_end(); 283 if (UI == UE) 284 return true; 285 286 User *TheUse = *UI; 287 for (++UI; UI != UE; ++UI) { 288 if (*UI != TheUse) 289 return false; 290 } 291 return true; 292 } 293 294 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively 295 /// dead PHI node, due to being a def-use chain of single-use nodes that 296 /// either forms a cycle or is terminated by a trivially dead instruction, 297 /// delete it. If that makes any of its operands trivially dead, delete them 298 /// too, recursively. Return true if a change was made. 299 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) { 300 SmallPtrSet<Instruction*, 4> Visited; 301 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects(); 302 I = cast<Instruction>(*I->use_begin())) { 303 if (I->use_empty()) 304 return RecursivelyDeleteTriviallyDeadInstructions(I); 305 306 // If we find an instruction more than once, we're on a cycle that 307 // won't prove fruitful. 308 if (!Visited.insert(I)) { 309 // Break the cycle and delete the instruction and its operands. 310 I->replaceAllUsesWith(UndefValue::get(I->getType())); 311 (void)RecursivelyDeleteTriviallyDeadInstructions(I); 312 return true; 313 } 314 } 315 return false; 316 } 317 318 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to 319 /// simplify any instructions in it and recursively delete dead instructions. 320 /// 321 /// This returns true if it changed the code, note that it can delete 322 /// instructions in other blocks as well in this block. 323 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) { 324 bool MadeChange = false; 325 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 326 Instruction *Inst = BI++; 327 328 if (Value *V = SimplifyInstruction(Inst, TD)) { 329 WeakVH BIHandle(BI); 330 ReplaceAndSimplifyAllUses(Inst, V, TD); 331 MadeChange = true; 332 if (BIHandle != BI) 333 BI = BB->begin(); 334 continue; 335 } 336 337 if (Inst->isTerminator()) 338 break; 339 340 WeakVH BIHandle(BI); 341 MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst); 342 if (BIHandle != BI) 343 BI = BB->begin(); 344 } 345 return MadeChange; 346 } 347 348 //===----------------------------------------------------------------------===// 349 // Control Flow Graph Restructuring. 350 // 351 352 353 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this 354 /// method is called when we're about to delete Pred as a predecessor of BB. If 355 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred. 356 /// 357 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI 358 /// nodes that collapse into identity values. For example, if we have: 359 /// x = phi(1, 0, 0, 0) 360 /// y = and x, z 361 /// 362 /// .. and delete the predecessor corresponding to the '1', this will attempt to 363 /// recursively fold the and to 0. 364 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred, 365 TargetData *TD) { 366 // This only adjusts blocks with PHI nodes. 367 if (!isa<PHINode>(BB->begin())) 368 return; 369 370 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify 371 // them down. This will leave us with single entry phi nodes and other phis 372 // that can be removed. 373 BB->removePredecessor(Pred, true); 374 375 WeakVH PhiIt = &BB->front(); 376 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) { 377 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt)); 378 379 Value *PNV = SimplifyInstruction(PN, TD); 380 if (PNV == 0) continue; 381 382 // If we're able to simplify the phi to a single value, substitute the new 383 // value into all of its uses. 384 assert(PNV != PN && "SimplifyInstruction broken!"); 385 386 Value *OldPhiIt = PhiIt; 387 ReplaceAndSimplifyAllUses(PN, PNV, TD); 388 389 // If recursive simplification ended up deleting the next PHI node we would 390 // iterate to, then our iterator is invalid, restart scanning from the top 391 // of the block. 392 if (PhiIt != OldPhiIt) PhiIt = &BB->front(); 393 } 394 } 395 396 397 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its 398 /// predecessor is known to have one successor (DestBB!). Eliminate the edge 399 /// between them, moving the instructions in the predecessor into DestBB and 400 /// deleting the predecessor block. 401 /// 402 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) { 403 // If BB has single-entry PHI nodes, fold them. 404 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) { 405 Value *NewVal = PN->getIncomingValue(0); 406 // Replace self referencing PHI with undef, it must be dead. 407 if (NewVal == PN) NewVal = UndefValue::get(PN->getType()); 408 PN->replaceAllUsesWith(NewVal); 409 PN->eraseFromParent(); 410 } 411 412 BasicBlock *PredBB = DestBB->getSinglePredecessor(); 413 assert(PredBB && "Block doesn't have a single predecessor!"); 414 415 // Splice all the instructions from PredBB to DestBB. 416 PredBB->getTerminator()->eraseFromParent(); 417 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList()); 418 419 // Zap anything that took the address of DestBB. Not doing this will give the 420 // address an invalid value. 421 if (DestBB->hasAddressTaken()) { 422 BlockAddress *BA = BlockAddress::get(DestBB); 423 Constant *Replacement = 424 ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1); 425 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement, 426 BA->getType())); 427 BA->destroyConstant(); 428 } 429 430 // Anything that branched to PredBB now branches to DestBB. 431 PredBB->replaceAllUsesWith(DestBB); 432 433 if (P) { 434 DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>(); 435 if (DT) { 436 BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock(); 437 DT->changeImmediateDominator(DestBB, PredBBIDom); 438 DT->eraseNode(PredBB); 439 } 440 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>(); 441 if (PI) { 442 PI->replaceAllUses(PredBB, DestBB); 443 PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB)); 444 } 445 } 446 // Nuke BB. 447 PredBB->eraseFromParent(); 448 } 449 450 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an 451 /// almost-empty BB ending in an unconditional branch to Succ, into succ. 452 /// 453 /// Assumption: Succ is the single successor for BB. 454 /// 455 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { 456 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!"); 457 458 DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into " 459 << Succ->getName() << "\n"); 460 // Shortcut, if there is only a single predecessor it must be BB and merging 461 // is always safe 462 if (Succ->getSinglePredecessor()) return true; 463 464 // Make a list of the predecessors of BB 465 typedef SmallPtrSet<BasicBlock*, 16> BlockSet; 466 BlockSet BBPreds(pred_begin(BB), pred_end(BB)); 467 468 // Use that list to make another list of common predecessors of BB and Succ 469 BlockSet CommonPreds; 470 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); 471 PI != PE; ++PI) { 472 BasicBlock *P = *PI; 473 if (BBPreds.count(P)) 474 CommonPreds.insert(P); 475 } 476 477 // Shortcut, if there are no common predecessors, merging is always safe 478 if (CommonPreds.empty()) 479 return true; 480 481 // Look at all the phi nodes in Succ, to see if they present a conflict when 482 // merging these blocks 483 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 484 PHINode *PN = cast<PHINode>(I); 485 486 // If the incoming value from BB is again a PHINode in 487 // BB which has the same incoming value for *PI as PN does, we can 488 // merge the phi nodes and then the blocks can still be merged 489 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB)); 490 if (BBPN && BBPN->getParent() == BB) { 491 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end(); 492 PI != PE; PI++) { 493 if (BBPN->getIncomingValueForBlock(*PI) 494 != PN->getIncomingValueForBlock(*PI)) { 495 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in " 496 << Succ->getName() << " is conflicting with " 497 << BBPN->getName() << " with regard to common predecessor " 498 << (*PI)->getName() << "\n"); 499 return false; 500 } 501 } 502 } else { 503 Value* Val = PN->getIncomingValueForBlock(BB); 504 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end(); 505 PI != PE; PI++) { 506 // See if the incoming value for the common predecessor is equal to the 507 // one for BB, in which case this phi node will not prevent the merging 508 // of the block. 509 if (Val != PN->getIncomingValueForBlock(*PI)) { 510 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in " 511 << Succ->getName() << " is conflicting with regard to common " 512 << "predecessor " << (*PI)->getName() << "\n"); 513 return false; 514 } 515 } 516 } 517 } 518 519 return true; 520 } 521 522 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an 523 /// unconditional branch, and contains no instructions other than PHI nodes, 524 /// potential debug intrinsics and the branch. If possible, eliminate BB by 525 /// rewriting all the predecessors to branch to the successor block and return 526 /// true. If we can't transform, return false. 527 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) { 528 assert(BB != &BB->getParent()->getEntryBlock() && 529 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!"); 530 531 // We can't eliminate infinite loops. 532 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0); 533 if (BB == Succ) return false; 534 535 // Check to see if merging these blocks would cause conflicts for any of the 536 // phi nodes in BB or Succ. If not, we can safely merge. 537 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false; 538 539 // Check for cases where Succ has multiple predecessors and a PHI node in BB 540 // has uses which will not disappear when the PHI nodes are merged. It is 541 // possible to handle such cases, but difficult: it requires checking whether 542 // BB dominates Succ, which is non-trivial to calculate in the case where 543 // Succ has multiple predecessors. Also, it requires checking whether 544 // constructing the necessary self-referential PHI node doesn't intoduce any 545 // conflicts; this isn't too difficult, but the previous code for doing this 546 // was incorrect. 547 // 548 // Note that if this check finds a live use, BB dominates Succ, so BB is 549 // something like a loop pre-header (or rarely, a part of an irreducible CFG); 550 // folding the branch isn't profitable in that case anyway. 551 if (!Succ->getSinglePredecessor()) { 552 BasicBlock::iterator BBI = BB->begin(); 553 while (isa<PHINode>(*BBI)) { 554 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end(); 555 UI != E; ++UI) { 556 if (PHINode* PN = dyn_cast<PHINode>(*UI)) { 557 if (PN->getIncomingBlock(UI) != BB) 558 return false; 559 } else { 560 return false; 561 } 562 } 563 ++BBI; 564 } 565 } 566 567 DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB); 568 569 if (isa<PHINode>(Succ->begin())) { 570 // If there is more than one pred of succ, and there are PHI nodes in 571 // the successor, then we need to add incoming edges for the PHI nodes 572 // 573 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB)); 574 575 // Loop over all of the PHI nodes in the successor of BB. 576 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 577 PHINode *PN = cast<PHINode>(I); 578 Value *OldVal = PN->removeIncomingValue(BB, false); 579 assert(OldVal && "No entry in PHI for Pred BB!"); 580 581 // If this incoming value is one of the PHI nodes in BB, the new entries 582 // in the PHI node are the entries from the old PHI. 583 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) { 584 PHINode *OldValPN = cast<PHINode>(OldVal); 585 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) 586 // Note that, since we are merging phi nodes and BB and Succ might 587 // have common predecessors, we could end up with a phi node with 588 // identical incoming branches. This will be cleaned up later (and 589 // will trigger asserts if we try to clean it up now, without also 590 // simplifying the corresponding conditional branch). 591 PN->addIncoming(OldValPN->getIncomingValue(i), 592 OldValPN->getIncomingBlock(i)); 593 } else { 594 // Add an incoming value for each of the new incoming values. 595 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) 596 PN->addIncoming(OldVal, BBPreds[i]); 597 } 598 } 599 } 600 601 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) { 602 if (Succ->getSinglePredecessor()) { 603 // BB is the only predecessor of Succ, so Succ will end up with exactly 604 // the same predecessors BB had. 605 Succ->getInstList().splice(Succ->begin(), 606 BB->getInstList(), BB->begin()); 607 } else { 608 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs. 609 assert(PN->use_empty() && "There shouldn't be any uses here!"); 610 PN->eraseFromParent(); 611 } 612 } 613 614 // Everything that jumped to BB now goes to Succ. 615 BB->replaceAllUsesWith(Succ); 616 if (!Succ->hasName()) Succ->takeName(BB); 617 BB->eraseFromParent(); // Delete the old basic block. 618 return true; 619 } 620 621 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI 622 /// nodes in this block. This doesn't try to be clever about PHI nodes 623 /// which differ only in the order of the incoming values, but instcombine 624 /// orders them so it usually won't matter. 625 /// 626 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) { 627 bool Changed = false; 628 629 // This implementation doesn't currently consider undef operands 630 // specially. Theroetically, two phis which are identical except for 631 // one having an undef where the other doesn't could be collapsed. 632 633 // Map from PHI hash values to PHI nodes. If multiple PHIs have 634 // the same hash value, the element is the first PHI in the 635 // linked list in CollisionMap. 636 DenseMap<uintptr_t, PHINode *> HashMap; 637 638 // Maintain linked lists of PHI nodes with common hash values. 639 DenseMap<PHINode *, PHINode *> CollisionMap; 640 641 // Examine each PHI. 642 for (BasicBlock::iterator I = BB->begin(); 643 PHINode *PN = dyn_cast<PHINode>(I++); ) { 644 // Compute a hash value on the operands. Instcombine will likely have sorted 645 // them, which helps expose duplicates, but we have to check all the 646 // operands to be safe in case instcombine hasn't run. 647 uintptr_t Hash = 0; 648 for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) { 649 // This hash algorithm is quite weak as hash functions go, but it seems 650 // to do a good enough job for this particular purpose, and is very quick. 651 Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I)); 652 Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7)); 653 } 654 // Avoid colliding with the DenseMap sentinels ~0 and ~0-1. 655 Hash >>= 1; 656 // If we've never seen this hash value before, it's a unique PHI. 657 std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair = 658 HashMap.insert(std::make_pair(Hash, PN)); 659 if (Pair.second) continue; 660 // Otherwise it's either a duplicate or a hash collision. 661 for (PHINode *OtherPN = Pair.first->second; ; ) { 662 if (OtherPN->isIdenticalTo(PN)) { 663 // A duplicate. Replace this PHI with its duplicate. 664 PN->replaceAllUsesWith(OtherPN); 665 PN->eraseFromParent(); 666 Changed = true; 667 break; 668 } 669 // A non-duplicate hash collision. 670 DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN); 671 if (I == CollisionMap.end()) { 672 // Set this PHI to be the head of the linked list of colliding PHIs. 673 PHINode *Old = Pair.first->second; 674 Pair.first->second = PN; 675 CollisionMap[PN] = Old; 676 break; 677 } 678 // Procede to the next PHI in the list. 679 OtherPN = I->second; 680 } 681 } 682 683 return Changed; 684 } 685 686 /// enforceKnownAlignment - If the specified pointer points to an object that 687 /// we control, modify the object's alignment to PrefAlign. This isn't 688 /// often possible though. If alignment is important, a more reliable approach 689 /// is to simply align all global variables and allocation instructions to 690 /// their preferred alignment from the beginning. 691 /// 692 static unsigned enforceKnownAlignment(Value *V, unsigned Align, 693 unsigned PrefAlign) { 694 695 User *U = dyn_cast<User>(V); 696 if (!U) return Align; 697 698 switch (Operator::getOpcode(U)) { 699 default: break; 700 case Instruction::BitCast: 701 return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign); 702 case Instruction::GetElementPtr: { 703 // If all indexes are zero, it is just the alignment of the base pointer. 704 bool AllZeroOperands = true; 705 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i) 706 if (!isa<Constant>(*i) || 707 !cast<Constant>(*i)->isNullValue()) { 708 AllZeroOperands = false; 709 break; 710 } 711 712 if (AllZeroOperands) { 713 // Treat this like a bitcast. 714 return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign); 715 } 716 return Align; 717 } 718 case Instruction::Alloca: { 719 AllocaInst *AI = cast<AllocaInst>(V); 720 // If there is a requested alignment and if this is an alloca, round up. 721 if (AI->getAlignment() >= PrefAlign) 722 return AI->getAlignment(); 723 AI->setAlignment(PrefAlign); 724 return PrefAlign; 725 } 726 } 727 728 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 729 // If there is a large requested alignment and we can, bump up the alignment 730 // of the global. 731 if (GV->isDeclaration()) return Align; 732 733 if (GV->getAlignment() >= PrefAlign) 734 return GV->getAlignment(); 735 // We can only increase the alignment of the global if it has no alignment 736 // specified or if it is not assigned a section. If it is assigned a 737 // section, the global could be densely packed with other objects in the 738 // section, increasing the alignment could cause padding issues. 739 if (!GV->hasSection() || GV->getAlignment() == 0) 740 GV->setAlignment(PrefAlign); 741 return GV->getAlignment(); 742 } 743 744 return Align; 745 } 746 747 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that 748 /// we can determine, return it, otherwise return 0. If PrefAlign is specified, 749 /// and it is more than the alignment of the ultimate object, see if we can 750 /// increase the alignment of the ultimate object, making this check succeed. 751 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, 752 const TargetData *TD) { 753 assert(V->getType()->isPointerTy() && 754 "getOrEnforceKnownAlignment expects a pointer!"); 755 unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64; 756 APInt Mask = APInt::getAllOnesValue(BitWidth); 757 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 758 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD); 759 unsigned TrailZ = KnownZero.countTrailingOnes(); 760 761 // Avoid trouble with rediculously large TrailZ values, such as 762 // those computed from a null pointer. 763 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1)); 764 765 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ); 766 767 // LLVM doesn't support alignments larger than this currently. 768 Align = std::min(Align, +Value::MaximumAlignment); 769 770 if (PrefAlign > Align) 771 Align = enforceKnownAlignment(V, Align, PrefAlign); 772 773 // We don't need to make any adjustment. 774 return Align; 775 } 776 777 ///===---------------------------------------------------------------------===// 778 /// Dbg Intrinsic utilities 779 /// 780 781 /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value 782 /// that has an associated llvm.dbg.decl intrinsic. 783 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, 784 StoreInst *SI, DIBuilder &Builder) { 785 DIVariable DIVar(DDI->getVariable()); 786 if (!DIVar.Verify()) 787 return false; 788 789 Instruction *DbgVal = 790 Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, 791 DIVar, SI); 792 793 // Propagate any debug metadata from the store onto the dbg.value. 794 DebugLoc SIDL = SI->getDebugLoc(); 795 if (!SIDL.isUnknown()) 796 DbgVal->setDebugLoc(SIDL); 797 // Otherwise propagate debug metadata from dbg.declare. 798 else 799 DbgVal->setDebugLoc(DDI->getDebugLoc()); 800 return true; 801 } 802 803 /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value 804 /// that has an associated llvm.dbg.decl intrinsic. 805 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, 806 LoadInst *LI, DIBuilder &Builder) { 807 DIVariable DIVar(DDI->getVariable()); 808 if (!DIVar.Verify()) 809 return false; 810 811 Instruction *DbgVal = 812 Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0, 813 DIVar, LI); 814 815 // Propagate any debug metadata from the store onto the dbg.value. 816 DebugLoc LIDL = LI->getDebugLoc(); 817 if (!LIDL.isUnknown()) 818 DbgVal->setDebugLoc(LIDL); 819 // Otherwise propagate debug metadata from dbg.declare. 820 else 821 DbgVal->setDebugLoc(DDI->getDebugLoc()); 822 return true; 823 } 824 825 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set 826 /// of llvm.dbg.value intrinsics. 827 bool llvm::LowerDbgDeclare(Function &F) { 828 DIBuilder DIB(*F.getParent()); 829 SmallVector<DbgDeclareInst *, 4> Dbgs; 830 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) 831 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { 832 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI)) 833 Dbgs.push_back(DDI); 834 } 835 if (Dbgs.empty()) 836 return false; 837 838 for (SmallVector<DbgDeclareInst *, 4>::iterator I = Dbgs.begin(), 839 E = Dbgs.end(); I != E; ++I) { 840 DbgDeclareInst *DDI = *I; 841 if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) { 842 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); 843 UI != E; ++UI) 844 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) 845 ConvertDebugDeclareToDebugValue(DDI, SI, DIB); 846 else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) 847 ConvertDebugDeclareToDebugValue(DDI, LI, DIB); 848 } 849 DDI->eraseFromParent(); 850 } 851 return true; 852 } 853