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/ADT/DenseMap.h" 17 #include "llvm/ADT/DenseSet.h" 18 #include "llvm/ADT/Hashing.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/EHPersonalities.h" 24 #include "llvm/Analysis/InstructionSimplify.h" 25 #include "llvm/Analysis/MemoryBuiltins.h" 26 #include "llvm/Analysis/LazyValueInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/CFG.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/DIBuilder.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/DebugInfo.h" 33 #include "llvm/IR/DerivedTypes.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/GetElementPtrTypeIterator.h" 36 #include "llvm/IR/GlobalAlias.h" 37 #include "llvm/IR/GlobalVariable.h" 38 #include "llvm/IR/IRBuilder.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/IntrinsicInst.h" 41 #include "llvm/IR/Intrinsics.h" 42 #include "llvm/IR/MDBuilder.h" 43 #include "llvm/IR/Metadata.h" 44 #include "llvm/IR/Operator.h" 45 #include "llvm/IR/PatternMatch.h" 46 #include "llvm/IR/ValueHandle.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Support/MathExtras.h" 49 #include "llvm/Support/raw_ostream.h" 50 using namespace llvm; 51 using namespace llvm::PatternMatch; 52 53 #define DEBUG_TYPE "local" 54 55 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed"); 56 57 //===----------------------------------------------------------------------===// 58 // Local constant propagation. 59 // 60 61 /// ConstantFoldTerminator - If a terminator instruction is predicated on a 62 /// constant value, convert it into an unconditional branch to the constant 63 /// destination. This is a nontrivial operation because the successors of this 64 /// basic block must have their PHI nodes updated. 65 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch 66 /// conditions and indirectbr addresses this might make dead if 67 /// DeleteDeadConditions is true. 68 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions, 69 const TargetLibraryInfo *TLI) { 70 TerminatorInst *T = BB->getTerminator(); 71 IRBuilder<> Builder(T); 72 73 // Branch - See if we are conditional jumping on constant 74 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 75 if (BI->isUnconditional()) return false; // Can't optimize uncond branch 76 BasicBlock *Dest1 = BI->getSuccessor(0); 77 BasicBlock *Dest2 = BI->getSuccessor(1); 78 79 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) { 80 // Are we branching on constant? 81 // YES. Change to unconditional branch... 82 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2; 83 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1; 84 85 //cerr << "Function: " << T->getParent()->getParent() 86 // << "\nRemoving branch from " << T->getParent() 87 // << "\n\nTo: " << OldDest << endl; 88 89 // Let the basic block know that we are letting go of it. Based on this, 90 // it will adjust it's PHI nodes. 91 OldDest->removePredecessor(BB); 92 93 // Replace the conditional branch with an unconditional one. 94 Builder.CreateBr(Destination); 95 BI->eraseFromParent(); 96 return true; 97 } 98 99 if (Dest2 == Dest1) { // Conditional branch to same location? 100 // This branch matches something like this: 101 // br bool %cond, label %Dest, label %Dest 102 // and changes it into: br label %Dest 103 104 // Let the basic block know that we are letting go of one copy of it. 105 assert(BI->getParent() && "Terminator not inserted in block!"); 106 Dest1->removePredecessor(BI->getParent()); 107 108 // Replace the conditional branch with an unconditional one. 109 Builder.CreateBr(Dest1); 110 Value *Cond = BI->getCondition(); 111 BI->eraseFromParent(); 112 if (DeleteDeadConditions) 113 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI); 114 return true; 115 } 116 return false; 117 } 118 119 if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { 120 // If we are switching on a constant, we can convert the switch to an 121 // unconditional branch. 122 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); 123 BasicBlock *DefaultDest = SI->getDefaultDest(); 124 BasicBlock *TheOnlyDest = DefaultDest; 125 126 // If the default is unreachable, ignore it when searching for TheOnlyDest. 127 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) && 128 SI->getNumCases() > 0) { 129 TheOnlyDest = SI->case_begin()->getCaseSuccessor(); 130 } 131 132 // Figure out which case it goes to. 133 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) { 134 // Found case matching a constant operand? 135 if (i->getCaseValue() == CI) { 136 TheOnlyDest = i->getCaseSuccessor(); 137 break; 138 } 139 140 // Check to see if this branch is going to the same place as the default 141 // dest. If so, eliminate it as an explicit compare. 142 if (i->getCaseSuccessor() == DefaultDest) { 143 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); 144 unsigned NCases = SI->getNumCases(); 145 // Fold the case metadata into the default if there will be any branches 146 // left, unless the metadata doesn't match the switch. 147 if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) { 148 // Collect branch weights into a vector. 149 SmallVector<uint32_t, 8> Weights; 150 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; 151 ++MD_i) { 152 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); 153 Weights.push_back(CI->getValue().getZExtValue()); 154 } 155 // Merge weight of this case to the default weight. 156 unsigned idx = i->getCaseIndex(); 157 Weights[0] += Weights[idx+1]; 158 // Remove weight for this case. 159 std::swap(Weights[idx+1], Weights.back()); 160 Weights.pop_back(); 161 SI->setMetadata(LLVMContext::MD_prof, 162 MDBuilder(BB->getContext()). 163 createBranchWeights(Weights)); 164 } 165 // Remove this entry. 166 DefaultDest->removePredecessor(SI->getParent()); 167 i = SI->removeCase(i); 168 e = SI->case_end(); 169 continue; 170 } 171 172 // Otherwise, check to see if the switch only branches to one destination. 173 // We do this by reseting "TheOnlyDest" to null when we find two non-equal 174 // destinations. 175 if (i->getCaseSuccessor() != TheOnlyDest) 176 TheOnlyDest = nullptr; 177 178 // Increment this iterator as we haven't removed the case. 179 ++i; 180 } 181 182 if (CI && !TheOnlyDest) { 183 // Branching on a constant, but not any of the cases, go to the default 184 // successor. 185 TheOnlyDest = SI->getDefaultDest(); 186 } 187 188 // If we found a single destination that we can fold the switch into, do so 189 // now. 190 if (TheOnlyDest) { 191 // Insert the new branch. 192 Builder.CreateBr(TheOnlyDest); 193 BasicBlock *BB = SI->getParent(); 194 195 // Remove entries from PHI nodes which we no longer branch to... 196 for (BasicBlock *Succ : SI->successors()) { 197 // Found case matching a constant operand? 198 if (Succ == TheOnlyDest) 199 TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest 200 else 201 Succ->removePredecessor(BB); 202 } 203 204 // Delete the old switch. 205 Value *Cond = SI->getCondition(); 206 SI->eraseFromParent(); 207 if (DeleteDeadConditions) 208 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI); 209 return true; 210 } 211 212 if (SI->getNumCases() == 1) { 213 // Otherwise, we can fold this switch into a conditional branch 214 // instruction if it has only one non-default destination. 215 auto FirstCase = *SI->case_begin(); 216 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(), 217 FirstCase.getCaseValue(), "cond"); 218 219 // Insert the new branch. 220 BranchInst *NewBr = Builder.CreateCondBr(Cond, 221 FirstCase.getCaseSuccessor(), 222 SI->getDefaultDest()); 223 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); 224 if (MD && MD->getNumOperands() == 3) { 225 ConstantInt *SICase = 226 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); 227 ConstantInt *SIDef = 228 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1)); 229 assert(SICase && SIDef); 230 // The TrueWeight should be the weight for the single case of SI. 231 NewBr->setMetadata(LLVMContext::MD_prof, 232 MDBuilder(BB->getContext()). 233 createBranchWeights(SICase->getValue().getZExtValue(), 234 SIDef->getValue().getZExtValue())); 235 } 236 237 // Update make.implicit metadata to the newly-created conditional branch. 238 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit); 239 if (MakeImplicitMD) 240 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD); 241 242 // Delete the old switch. 243 SI->eraseFromParent(); 244 return true; 245 } 246 return false; 247 } 248 249 if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) { 250 // indirectbr blockaddress(@F, @BB) -> br label @BB 251 if (BlockAddress *BA = 252 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) { 253 BasicBlock *TheOnlyDest = BA->getBasicBlock(); 254 // Insert the new branch. 255 Builder.CreateBr(TheOnlyDest); 256 257 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 258 if (IBI->getDestination(i) == TheOnlyDest) 259 TheOnlyDest = nullptr; 260 else 261 IBI->getDestination(i)->removePredecessor(IBI->getParent()); 262 } 263 Value *Address = IBI->getAddress(); 264 IBI->eraseFromParent(); 265 if (DeleteDeadConditions) 266 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI); 267 268 // If we didn't find our destination in the IBI successor list, then we 269 // have undefined behavior. Replace the unconditional branch with an 270 // 'unreachable' instruction. 271 if (TheOnlyDest) { 272 BB->getTerminator()->eraseFromParent(); 273 new UnreachableInst(BB->getContext(), BB); 274 } 275 276 return true; 277 } 278 } 279 280 return false; 281 } 282 283 284 //===----------------------------------------------------------------------===// 285 // Local dead code elimination. 286 // 287 288 /// isInstructionTriviallyDead - Return true if the result produced by the 289 /// instruction is not used, and the instruction has no side effects. 290 /// 291 bool llvm::isInstructionTriviallyDead(Instruction *I, 292 const TargetLibraryInfo *TLI) { 293 if (!I->use_empty()) 294 return false; 295 return wouldInstructionBeTriviallyDead(I, TLI); 296 } 297 298 bool llvm::wouldInstructionBeTriviallyDead(Instruction *I, 299 const TargetLibraryInfo *TLI) { 300 if (isa<TerminatorInst>(I)) 301 return false; 302 303 // We don't want the landingpad-like instructions removed by anything this 304 // general. 305 if (I->isEHPad()) 306 return false; 307 308 // We don't want debug info removed by anything this general, unless 309 // debug info is empty. 310 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) { 311 if (DDI->getAddress()) 312 return false; 313 return true; 314 } 315 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) { 316 if (DVI->getValue()) 317 return false; 318 return true; 319 } 320 321 if (!I->mayHaveSideEffects()) 322 return true; 323 324 // Special case intrinsics that "may have side effects" but can be deleted 325 // when dead. 326 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 327 // Safe to delete llvm.stacksave if dead. 328 if (II->getIntrinsicID() == Intrinsic::stacksave) 329 return true; 330 331 // Lifetime intrinsics are dead when their right-hand is undef. 332 if (II->getIntrinsicID() == Intrinsic::lifetime_start || 333 II->getIntrinsicID() == Intrinsic::lifetime_end) 334 return isa<UndefValue>(II->getArgOperand(1)); 335 336 // Assumptions are dead if their condition is trivially true. Guards on 337 // true are operationally no-ops. In the future we can consider more 338 // sophisticated tradeoffs for guards considering potential for check 339 // widening, but for now we keep things simple. 340 if (II->getIntrinsicID() == Intrinsic::assume || 341 II->getIntrinsicID() == Intrinsic::experimental_guard) { 342 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0))) 343 return !Cond->isZero(); 344 345 return false; 346 } 347 } 348 349 if (isAllocLikeFn(I, TLI)) 350 return true; 351 352 if (CallInst *CI = isFreeCall(I, TLI)) 353 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0))) 354 return C->isNullValue() || isa<UndefValue>(C); 355 356 if (CallSite CS = CallSite(I)) 357 if (isMathLibCallNoop(CS, TLI)) 358 return true; 359 360 return false; 361 } 362 363 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a 364 /// trivially dead instruction, delete it. If that makes any of its operands 365 /// trivially dead, delete them too, recursively. Return true if any 366 /// instructions were deleted. 367 bool 368 llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V, 369 const TargetLibraryInfo *TLI) { 370 Instruction *I = dyn_cast<Instruction>(V); 371 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI)) 372 return false; 373 374 SmallVector<Instruction*, 16> DeadInsts; 375 DeadInsts.push_back(I); 376 377 do { 378 I = DeadInsts.pop_back_val(); 379 380 // Null out all of the instruction's operands to see if any operand becomes 381 // dead as we go. 382 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 383 Value *OpV = I->getOperand(i); 384 I->setOperand(i, nullptr); 385 386 if (!OpV->use_empty()) continue; 387 388 // If the operand is an instruction that became dead as we nulled out the 389 // operand, and if it is 'trivially' dead, delete it in a future loop 390 // iteration. 391 if (Instruction *OpI = dyn_cast<Instruction>(OpV)) 392 if (isInstructionTriviallyDead(OpI, TLI)) 393 DeadInsts.push_back(OpI); 394 } 395 396 I->eraseFromParent(); 397 } while (!DeadInsts.empty()); 398 399 return true; 400 } 401 402 /// areAllUsesEqual - Check whether the uses of a value are all the same. 403 /// This is similar to Instruction::hasOneUse() except this will also return 404 /// true when there are no uses or multiple uses that all refer to the same 405 /// value. 406 static bool areAllUsesEqual(Instruction *I) { 407 Value::user_iterator UI = I->user_begin(); 408 Value::user_iterator UE = I->user_end(); 409 if (UI == UE) 410 return true; 411 412 User *TheUse = *UI; 413 for (++UI; UI != UE; ++UI) { 414 if (*UI != TheUse) 415 return false; 416 } 417 return true; 418 } 419 420 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively 421 /// dead PHI node, due to being a def-use chain of single-use nodes that 422 /// either forms a cycle or is terminated by a trivially dead instruction, 423 /// delete it. If that makes any of its operands trivially dead, delete them 424 /// too, recursively. Return true if a change was made. 425 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN, 426 const TargetLibraryInfo *TLI) { 427 SmallPtrSet<Instruction*, 4> Visited; 428 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects(); 429 I = cast<Instruction>(*I->user_begin())) { 430 if (I->use_empty()) 431 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI); 432 433 // If we find an instruction more than once, we're on a cycle that 434 // won't prove fruitful. 435 if (!Visited.insert(I).second) { 436 // Break the cycle and delete the instruction and its operands. 437 I->replaceAllUsesWith(UndefValue::get(I->getType())); 438 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI); 439 return true; 440 } 441 } 442 return false; 443 } 444 445 static bool 446 simplifyAndDCEInstruction(Instruction *I, 447 SmallSetVector<Instruction *, 16> &WorkList, 448 const DataLayout &DL, 449 const TargetLibraryInfo *TLI) { 450 if (isInstructionTriviallyDead(I, TLI)) { 451 // Null out all of the instruction's operands to see if any operand becomes 452 // dead as we go. 453 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 454 Value *OpV = I->getOperand(i); 455 I->setOperand(i, nullptr); 456 457 if (!OpV->use_empty() || I == OpV) 458 continue; 459 460 // If the operand is an instruction that became dead as we nulled out the 461 // operand, and if it is 'trivially' dead, delete it in a future loop 462 // iteration. 463 if (Instruction *OpI = dyn_cast<Instruction>(OpV)) 464 if (isInstructionTriviallyDead(OpI, TLI)) 465 WorkList.insert(OpI); 466 } 467 468 I->eraseFromParent(); 469 470 return true; 471 } 472 473 if (Value *SimpleV = SimplifyInstruction(I, DL)) { 474 // Add the users to the worklist. CAREFUL: an instruction can use itself, 475 // in the case of a phi node. 476 for (User *U : I->users()) { 477 if (U != I) { 478 WorkList.insert(cast<Instruction>(U)); 479 } 480 } 481 482 // Replace the instruction with its simplified value. 483 bool Changed = false; 484 if (!I->use_empty()) { 485 I->replaceAllUsesWith(SimpleV); 486 Changed = true; 487 } 488 if (isInstructionTriviallyDead(I, TLI)) { 489 I->eraseFromParent(); 490 Changed = true; 491 } 492 return Changed; 493 } 494 return false; 495 } 496 497 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to 498 /// simplify any instructions in it and recursively delete dead instructions. 499 /// 500 /// This returns true if it changed the code, note that it can delete 501 /// instructions in other blocks as well in this block. 502 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, 503 const TargetLibraryInfo *TLI) { 504 bool MadeChange = false; 505 const DataLayout &DL = BB->getModule()->getDataLayout(); 506 507 #ifndef NDEBUG 508 // In debug builds, ensure that the terminator of the block is never replaced 509 // or deleted by these simplifications. The idea of simplification is that it 510 // cannot introduce new instructions, and there is no way to replace the 511 // terminator of a block without introducing a new instruction. 512 AssertingVH<Instruction> TerminatorVH(&BB->back()); 513 #endif 514 515 SmallSetVector<Instruction *, 16> WorkList; 516 // Iterate over the original function, only adding insts to the worklist 517 // if they actually need to be revisited. This avoids having to pre-init 518 // the worklist with the entire function's worth of instructions. 519 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end()); 520 BI != E;) { 521 assert(!BI->isTerminator()); 522 Instruction *I = &*BI; 523 ++BI; 524 525 // We're visiting this instruction now, so make sure it's not in the 526 // worklist from an earlier visit. 527 if (!WorkList.count(I)) 528 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI); 529 } 530 531 while (!WorkList.empty()) { 532 Instruction *I = WorkList.pop_back_val(); 533 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI); 534 } 535 return MadeChange; 536 } 537 538 //===----------------------------------------------------------------------===// 539 // Control Flow Graph Restructuring. 540 // 541 542 543 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this 544 /// method is called when we're about to delete Pred as a predecessor of BB. If 545 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred. 546 /// 547 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI 548 /// nodes that collapse into identity values. For example, if we have: 549 /// x = phi(1, 0, 0, 0) 550 /// y = and x, z 551 /// 552 /// .. and delete the predecessor corresponding to the '1', this will attempt to 553 /// recursively fold the and to 0. 554 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) { 555 // This only adjusts blocks with PHI nodes. 556 if (!isa<PHINode>(BB->begin())) 557 return; 558 559 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify 560 // them down. This will leave us with single entry phi nodes and other phis 561 // that can be removed. 562 BB->removePredecessor(Pred, true); 563 564 WeakVH PhiIt = &BB->front(); 565 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) { 566 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt)); 567 Value *OldPhiIt = PhiIt; 568 569 if (!recursivelySimplifyInstruction(PN)) 570 continue; 571 572 // If recursive simplification ended up deleting the next PHI node we would 573 // iterate to, then our iterator is invalid, restart scanning from the top 574 // of the block. 575 if (PhiIt != OldPhiIt) PhiIt = &BB->front(); 576 } 577 } 578 579 580 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its 581 /// predecessor is known to have one successor (DestBB!). Eliminate the edge 582 /// between them, moving the instructions in the predecessor into DestBB and 583 /// deleting the predecessor block. 584 /// 585 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) { 586 // If BB has single-entry PHI nodes, fold them. 587 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) { 588 Value *NewVal = PN->getIncomingValue(0); 589 // Replace self referencing PHI with undef, it must be dead. 590 if (NewVal == PN) NewVal = UndefValue::get(PN->getType()); 591 PN->replaceAllUsesWith(NewVal); 592 PN->eraseFromParent(); 593 } 594 595 BasicBlock *PredBB = DestBB->getSinglePredecessor(); 596 assert(PredBB && "Block doesn't have a single predecessor!"); 597 598 // Zap anything that took the address of DestBB. Not doing this will give the 599 // address an invalid value. 600 if (DestBB->hasAddressTaken()) { 601 BlockAddress *BA = BlockAddress::get(DestBB); 602 Constant *Replacement = 603 ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1); 604 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement, 605 BA->getType())); 606 BA->destroyConstant(); 607 } 608 609 // Anything that branched to PredBB now branches to DestBB. 610 PredBB->replaceAllUsesWith(DestBB); 611 612 // Splice all the instructions from PredBB to DestBB. 613 PredBB->getTerminator()->eraseFromParent(); 614 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList()); 615 616 // If the PredBB is the entry block of the function, move DestBB up to 617 // become the entry block after we erase PredBB. 618 if (PredBB == &DestBB->getParent()->getEntryBlock()) 619 DestBB->moveAfter(PredBB); 620 621 if (DT) { 622 BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock(); 623 DT->changeImmediateDominator(DestBB, PredBBIDom); 624 DT->eraseNode(PredBB); 625 } 626 // Nuke BB. 627 PredBB->eraseFromParent(); 628 } 629 630 /// CanMergeValues - Return true if we can choose one of these values to use 631 /// in place of the other. Note that we will always choose the non-undef 632 /// value to keep. 633 static bool CanMergeValues(Value *First, Value *Second) { 634 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second); 635 } 636 637 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an 638 /// almost-empty BB ending in an unconditional branch to Succ, into Succ. 639 /// 640 /// Assumption: Succ is the single successor for BB. 641 /// 642 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { 643 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!"); 644 645 DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into " 646 << Succ->getName() << "\n"); 647 // Shortcut, if there is only a single predecessor it must be BB and merging 648 // is always safe 649 if (Succ->getSinglePredecessor()) return true; 650 651 // Make a list of the predecessors of BB 652 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB)); 653 654 // Look at all the phi nodes in Succ, to see if they present a conflict when 655 // merging these blocks 656 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 657 PHINode *PN = cast<PHINode>(I); 658 659 // If the incoming value from BB is again a PHINode in 660 // BB which has the same incoming value for *PI as PN does, we can 661 // merge the phi nodes and then the blocks can still be merged 662 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB)); 663 if (BBPN && BBPN->getParent() == BB) { 664 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) { 665 BasicBlock *IBB = PN->getIncomingBlock(PI); 666 if (BBPreds.count(IBB) && 667 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB), 668 PN->getIncomingValue(PI))) { 669 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in " 670 << Succ->getName() << " is conflicting with " 671 << BBPN->getName() << " with regard to common predecessor " 672 << IBB->getName() << "\n"); 673 return false; 674 } 675 } 676 } else { 677 Value* Val = PN->getIncomingValueForBlock(BB); 678 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) { 679 // See if the incoming value for the common predecessor is equal to the 680 // one for BB, in which case this phi node will not prevent the merging 681 // of the block. 682 BasicBlock *IBB = PN->getIncomingBlock(PI); 683 if (BBPreds.count(IBB) && 684 !CanMergeValues(Val, PN->getIncomingValue(PI))) { 685 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in " 686 << Succ->getName() << " is conflicting with regard to common " 687 << "predecessor " << IBB->getName() << "\n"); 688 return false; 689 } 690 } 691 } 692 } 693 694 return true; 695 } 696 697 typedef SmallVector<BasicBlock *, 16> PredBlockVector; 698 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap; 699 700 /// \brief Determines the value to use as the phi node input for a block. 701 /// 702 /// Select between \p OldVal any value that we know flows from \p BB 703 /// to a particular phi on the basis of which one (if either) is not 704 /// undef. Update IncomingValues based on the selected value. 705 /// 706 /// \param OldVal The value we are considering selecting. 707 /// \param BB The block that the value flows in from. 708 /// \param IncomingValues A map from block-to-value for other phi inputs 709 /// that we have examined. 710 /// 711 /// \returns the selected value. 712 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB, 713 IncomingValueMap &IncomingValues) { 714 if (!isa<UndefValue>(OldVal)) { 715 assert((!IncomingValues.count(BB) || 716 IncomingValues.find(BB)->second == OldVal) && 717 "Expected OldVal to match incoming value from BB!"); 718 719 IncomingValues.insert(std::make_pair(BB, OldVal)); 720 return OldVal; 721 } 722 723 IncomingValueMap::const_iterator It = IncomingValues.find(BB); 724 if (It != IncomingValues.end()) return It->second; 725 726 return OldVal; 727 } 728 729 /// \brief Create a map from block to value for the operands of a 730 /// given phi. 731 /// 732 /// Create a map from block to value for each non-undef value flowing 733 /// into \p PN. 734 /// 735 /// \param PN The phi we are collecting the map for. 736 /// \param IncomingValues [out] The map from block to value for this phi. 737 static void gatherIncomingValuesToPhi(PHINode *PN, 738 IncomingValueMap &IncomingValues) { 739 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 740 BasicBlock *BB = PN->getIncomingBlock(i); 741 Value *V = PN->getIncomingValue(i); 742 743 if (!isa<UndefValue>(V)) 744 IncomingValues.insert(std::make_pair(BB, V)); 745 } 746 } 747 748 /// \brief Replace the incoming undef values to a phi with the values 749 /// from a block-to-value map. 750 /// 751 /// \param PN The phi we are replacing the undefs in. 752 /// \param IncomingValues A map from block to value. 753 static void replaceUndefValuesInPhi(PHINode *PN, 754 const IncomingValueMap &IncomingValues) { 755 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 756 Value *V = PN->getIncomingValue(i); 757 758 if (!isa<UndefValue>(V)) continue; 759 760 BasicBlock *BB = PN->getIncomingBlock(i); 761 IncomingValueMap::const_iterator It = IncomingValues.find(BB); 762 if (It == IncomingValues.end()) continue; 763 764 PN->setIncomingValue(i, It->second); 765 } 766 } 767 768 /// \brief Replace a value flowing from a block to a phi with 769 /// potentially multiple instances of that value flowing from the 770 /// block's predecessors to the phi. 771 /// 772 /// \param BB The block with the value flowing into the phi. 773 /// \param BBPreds The predecessors of BB. 774 /// \param PN The phi that we are updating. 775 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB, 776 const PredBlockVector &BBPreds, 777 PHINode *PN) { 778 Value *OldVal = PN->removeIncomingValue(BB, false); 779 assert(OldVal && "No entry in PHI for Pred BB!"); 780 781 IncomingValueMap IncomingValues; 782 783 // We are merging two blocks - BB, and the block containing PN - and 784 // as a result we need to redirect edges from the predecessors of BB 785 // to go to the block containing PN, and update PN 786 // accordingly. Since we allow merging blocks in the case where the 787 // predecessor and successor blocks both share some predecessors, 788 // and where some of those common predecessors might have undef 789 // values flowing into PN, we want to rewrite those values to be 790 // consistent with the non-undef values. 791 792 gatherIncomingValuesToPhi(PN, IncomingValues); 793 794 // If this incoming value is one of the PHI nodes in BB, the new entries 795 // in the PHI node are the entries from the old PHI. 796 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) { 797 PHINode *OldValPN = cast<PHINode>(OldVal); 798 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) { 799 // Note that, since we are merging phi nodes and BB and Succ might 800 // have common predecessors, we could end up with a phi node with 801 // identical incoming branches. This will be cleaned up later (and 802 // will trigger asserts if we try to clean it up now, without also 803 // simplifying the corresponding conditional branch). 804 BasicBlock *PredBB = OldValPN->getIncomingBlock(i); 805 Value *PredVal = OldValPN->getIncomingValue(i); 806 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB, 807 IncomingValues); 808 809 // And add a new incoming value for this predecessor for the 810 // newly retargeted branch. 811 PN->addIncoming(Selected, PredBB); 812 } 813 } else { 814 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) { 815 // Update existing incoming values in PN for this 816 // predecessor of BB. 817 BasicBlock *PredBB = BBPreds[i]; 818 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB, 819 IncomingValues); 820 821 // And add a new incoming value for this predecessor for the 822 // newly retargeted branch. 823 PN->addIncoming(Selected, PredBB); 824 } 825 } 826 827 replaceUndefValuesInPhi(PN, IncomingValues); 828 } 829 830 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an 831 /// unconditional branch, and contains no instructions other than PHI nodes, 832 /// potential side-effect free intrinsics and the branch. If possible, 833 /// eliminate BB by rewriting all the predecessors to branch to the successor 834 /// block and return true. If we can't transform, return false. 835 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) { 836 assert(BB != &BB->getParent()->getEntryBlock() && 837 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!"); 838 839 // We can't eliminate infinite loops. 840 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0); 841 if (BB == Succ) return false; 842 843 // Check to see if merging these blocks would cause conflicts for any of the 844 // phi nodes in BB or Succ. If not, we can safely merge. 845 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false; 846 847 // Check for cases where Succ has multiple predecessors and a PHI node in BB 848 // has uses which will not disappear when the PHI nodes are merged. It is 849 // possible to handle such cases, but difficult: it requires checking whether 850 // BB dominates Succ, which is non-trivial to calculate in the case where 851 // Succ has multiple predecessors. Also, it requires checking whether 852 // constructing the necessary self-referential PHI node doesn't introduce any 853 // conflicts; this isn't too difficult, but the previous code for doing this 854 // was incorrect. 855 // 856 // Note that if this check finds a live use, BB dominates Succ, so BB is 857 // something like a loop pre-header (or rarely, a part of an irreducible CFG); 858 // folding the branch isn't profitable in that case anyway. 859 if (!Succ->getSinglePredecessor()) { 860 BasicBlock::iterator BBI = BB->begin(); 861 while (isa<PHINode>(*BBI)) { 862 for (Use &U : BBI->uses()) { 863 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) { 864 if (PN->getIncomingBlock(U) != BB) 865 return false; 866 } else { 867 return false; 868 } 869 } 870 ++BBI; 871 } 872 } 873 874 DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB); 875 876 if (isa<PHINode>(Succ->begin())) { 877 // If there is more than one pred of succ, and there are PHI nodes in 878 // the successor, then we need to add incoming edges for the PHI nodes 879 // 880 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB)); 881 882 // Loop over all of the PHI nodes in the successor of BB. 883 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 884 PHINode *PN = cast<PHINode>(I); 885 886 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN); 887 } 888 } 889 890 if (Succ->getSinglePredecessor()) { 891 // BB is the only predecessor of Succ, so Succ will end up with exactly 892 // the same predecessors BB had. 893 894 // Copy over any phi, debug or lifetime instruction. 895 BB->getTerminator()->eraseFromParent(); 896 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(), 897 BB->getInstList()); 898 } else { 899 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) { 900 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs. 901 assert(PN->use_empty() && "There shouldn't be any uses here!"); 902 PN->eraseFromParent(); 903 } 904 } 905 906 // If the unconditional branch we replaced contains llvm.loop metadata, we 907 // add the metadata to the branch instructions in the predecessors. 908 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop"); 909 Instruction *TI = BB->getTerminator(); 910 if (TI) 911 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind)) 912 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 913 BasicBlock *Pred = *PI; 914 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD); 915 } 916 917 // Everything that jumped to BB now goes to Succ. 918 BB->replaceAllUsesWith(Succ); 919 if (!Succ->hasName()) Succ->takeName(BB); 920 BB->eraseFromParent(); // Delete the old basic block. 921 return true; 922 } 923 924 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI 925 /// nodes in this block. This doesn't try to be clever about PHI nodes 926 /// which differ only in the order of the incoming values, but instcombine 927 /// orders them so it usually won't matter. 928 /// 929 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) { 930 // This implementation doesn't currently consider undef operands 931 // specially. Theoretically, two phis which are identical except for 932 // one having an undef where the other doesn't could be collapsed. 933 934 struct PHIDenseMapInfo { 935 static PHINode *getEmptyKey() { 936 return DenseMapInfo<PHINode *>::getEmptyKey(); 937 } 938 static PHINode *getTombstoneKey() { 939 return DenseMapInfo<PHINode *>::getTombstoneKey(); 940 } 941 static unsigned getHashValue(PHINode *PN) { 942 // Compute a hash value on the operands. Instcombine will likely have 943 // sorted them, which helps expose duplicates, but we have to check all 944 // the operands to be safe in case instcombine hasn't run. 945 return static_cast<unsigned>(hash_combine( 946 hash_combine_range(PN->value_op_begin(), PN->value_op_end()), 947 hash_combine_range(PN->block_begin(), PN->block_end()))); 948 } 949 static bool isEqual(PHINode *LHS, PHINode *RHS) { 950 if (LHS == getEmptyKey() || LHS == getTombstoneKey() || 951 RHS == getEmptyKey() || RHS == getTombstoneKey()) 952 return LHS == RHS; 953 return LHS->isIdenticalTo(RHS); 954 } 955 }; 956 957 // Set of unique PHINodes. 958 DenseSet<PHINode *, PHIDenseMapInfo> PHISet; 959 960 // Examine each PHI. 961 bool Changed = false; 962 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) { 963 auto Inserted = PHISet.insert(PN); 964 if (!Inserted.second) { 965 // A duplicate. Replace this PHI with its duplicate. 966 PN->replaceAllUsesWith(*Inserted.first); 967 PN->eraseFromParent(); 968 Changed = true; 969 970 // The RAUW can change PHIs that we already visited. Start over from the 971 // beginning. 972 PHISet.clear(); 973 I = BB->begin(); 974 } 975 } 976 977 return Changed; 978 } 979 980 /// enforceKnownAlignment - If the specified pointer points to an object that 981 /// we control, modify the object's alignment to PrefAlign. This isn't 982 /// often possible though. If alignment is important, a more reliable approach 983 /// is to simply align all global variables and allocation instructions to 984 /// their preferred alignment from the beginning. 985 /// 986 static unsigned enforceKnownAlignment(Value *V, unsigned Align, 987 unsigned PrefAlign, 988 const DataLayout &DL) { 989 assert(PrefAlign > Align); 990 991 V = V->stripPointerCasts(); 992 993 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 994 // TODO: ideally, computeKnownBits ought to have used 995 // AllocaInst::getAlignment() in its computation already, making 996 // the below max redundant. But, as it turns out, 997 // stripPointerCasts recurses through infinite layers of bitcasts, 998 // while computeKnownBits is not allowed to traverse more than 6 999 // levels. 1000 Align = std::max(AI->getAlignment(), Align); 1001 if (PrefAlign <= Align) 1002 return Align; 1003 1004 // If the preferred alignment is greater than the natural stack alignment 1005 // then don't round up. This avoids dynamic stack realignment. 1006 if (DL.exceedsNaturalStackAlignment(PrefAlign)) 1007 return Align; 1008 AI->setAlignment(PrefAlign); 1009 return PrefAlign; 1010 } 1011 1012 if (auto *GO = dyn_cast<GlobalObject>(V)) { 1013 // TODO: as above, this shouldn't be necessary. 1014 Align = std::max(GO->getAlignment(), Align); 1015 if (PrefAlign <= Align) 1016 return Align; 1017 1018 // If there is a large requested alignment and we can, bump up the alignment 1019 // of the global. If the memory we set aside for the global may not be the 1020 // memory used by the final program then it is impossible for us to reliably 1021 // enforce the preferred alignment. 1022 if (!GO->canIncreaseAlignment()) 1023 return Align; 1024 1025 GO->setAlignment(PrefAlign); 1026 return PrefAlign; 1027 } 1028 1029 return Align; 1030 } 1031 1032 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, 1033 const DataLayout &DL, 1034 const Instruction *CxtI, 1035 AssumptionCache *AC, 1036 const DominatorTree *DT) { 1037 assert(V->getType()->isPointerTy() && 1038 "getOrEnforceKnownAlignment expects a pointer!"); 1039 unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType()); 1040 1041 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 1042 computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT); 1043 unsigned TrailZ = KnownZero.countTrailingOnes(); 1044 1045 // Avoid trouble with ridiculously large TrailZ values, such as 1046 // those computed from a null pointer. 1047 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1)); 1048 1049 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ); 1050 1051 // LLVM doesn't support alignments larger than this currently. 1052 Align = std::min(Align, +Value::MaximumAlignment); 1053 1054 if (PrefAlign > Align) 1055 Align = enforceKnownAlignment(V, Align, PrefAlign, DL); 1056 1057 // We don't need to make any adjustment. 1058 return Align; 1059 } 1060 1061 ///===---------------------------------------------------------------------===// 1062 /// Dbg Intrinsic utilities 1063 /// 1064 1065 /// See if there is a dbg.value intrinsic for DIVar before I. 1066 static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr, 1067 Instruction *I) { 1068 // Since we can't guarantee that the original dbg.declare instrinsic 1069 // is removed by LowerDbgDeclare(), we need to make sure that we are 1070 // not inserting the same dbg.value intrinsic over and over. 1071 llvm::BasicBlock::InstListType::iterator PrevI(I); 1072 if (PrevI != I->getParent()->getInstList().begin()) { 1073 --PrevI; 1074 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI)) 1075 if (DVI->getValue() == I->getOperand(0) && 1076 DVI->getOffset() == 0 && 1077 DVI->getVariable() == DIVar && 1078 DVI->getExpression() == DIExpr) 1079 return true; 1080 } 1081 return false; 1082 } 1083 1084 /// See if there is a dbg.value intrinsic for DIVar for the PHI node. 1085 static bool PhiHasDebugValue(DILocalVariable *DIVar, 1086 DIExpression *DIExpr, 1087 PHINode *APN) { 1088 // Since we can't guarantee that the original dbg.declare instrinsic 1089 // is removed by LowerDbgDeclare(), we need to make sure that we are 1090 // not inserting the same dbg.value intrinsic over and over. 1091 SmallVector<DbgValueInst *, 1> DbgValues; 1092 findDbgValues(DbgValues, APN); 1093 for (auto *DVI : DbgValues) { 1094 assert(DVI->getValue() == APN); 1095 assert(DVI->getOffset() == 0); 1096 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr)) 1097 return true; 1098 } 1099 return false; 1100 } 1101 1102 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value 1103 /// that has an associated llvm.dbg.decl intrinsic. 1104 void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, 1105 StoreInst *SI, DIBuilder &Builder) { 1106 auto *DIVar = DDI->getVariable(); 1107 auto *DIExpr = DDI->getExpression(); 1108 assert(DIVar && "Missing variable"); 1109 1110 // If an argument is zero extended then use argument directly. The ZExt 1111 // may be zapped by an optimization pass in future. 1112 Argument *ExtendedArg = nullptr; 1113 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0))) 1114 ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0)); 1115 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0))) 1116 ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0)); 1117 if (ExtendedArg) { 1118 // We're now only describing a subset of the variable. The fragment we're 1119 // describing will always be smaller than the variable size, because 1120 // VariableSize == Size of Alloca described by DDI. Since SI stores 1121 // to the alloca described by DDI, if it's first operand is an extend, 1122 // we're guaranteed that before extension, the value was narrower than 1123 // the size of the alloca, hence the size of the described variable. 1124 SmallVector<uint64_t, 3> Ops; 1125 unsigned FragmentOffset = 0; 1126 // If this already is a bit fragment, we drop the bit fragment from the 1127 // expression and record the offset. 1128 auto Fragment = DIExpr->getFragmentInfo(); 1129 if (Fragment) { 1130 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()-3); 1131 FragmentOffset = Fragment->OffsetInBits; 1132 } else { 1133 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()); 1134 } 1135 Ops.push_back(dwarf::DW_OP_LLVM_fragment); 1136 Ops.push_back(FragmentOffset); 1137 const DataLayout &DL = DDI->getModule()->getDataLayout(); 1138 Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType())); 1139 auto NewDIExpr = Builder.createExpression(Ops); 1140 if (!LdStHasDebugValue(DIVar, NewDIExpr, SI)) 1141 Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, NewDIExpr, 1142 DDI->getDebugLoc(), SI); 1143 } else if (!LdStHasDebugValue(DIVar, DIExpr, SI)) 1144 Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr, 1145 DDI->getDebugLoc(), SI); 1146 } 1147 1148 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value 1149 /// that has an associated llvm.dbg.decl intrinsic. 1150 void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, 1151 LoadInst *LI, DIBuilder &Builder) { 1152 auto *DIVar = DDI->getVariable(); 1153 auto *DIExpr = DDI->getExpression(); 1154 assert(DIVar && "Missing variable"); 1155 1156 if (LdStHasDebugValue(DIVar, DIExpr, LI)) 1157 return; 1158 1159 // We are now tracking the loaded value instead of the address. In the 1160 // future if multi-location support is added to the IR, it might be 1161 // preferable to keep tracking both the loaded value and the original 1162 // address in case the alloca can not be elided. 1163 Instruction *DbgValue = Builder.insertDbgValueIntrinsic( 1164 LI, 0, DIVar, DIExpr, DDI->getDebugLoc(), (Instruction *)nullptr); 1165 DbgValue->insertAfter(LI); 1166 } 1167 1168 /// Inserts a llvm.dbg.value intrinsic after a phi 1169 /// that has an associated llvm.dbg.decl intrinsic. 1170 void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, 1171 PHINode *APN, DIBuilder &Builder) { 1172 auto *DIVar = DDI->getVariable(); 1173 auto *DIExpr = DDI->getExpression(); 1174 assert(DIVar && "Missing variable"); 1175 1176 if (PhiHasDebugValue(DIVar, DIExpr, APN)) 1177 return; 1178 1179 BasicBlock *BB = APN->getParent(); 1180 auto InsertionPt = BB->getFirstInsertionPt(); 1181 1182 // The block may be a catchswitch block, which does not have a valid 1183 // insertion point. 1184 // FIXME: Insert dbg.value markers in the successors when appropriate. 1185 if (InsertionPt != BB->end()) 1186 Builder.insertDbgValueIntrinsic(APN, 0, DIVar, DIExpr, DDI->getDebugLoc(), 1187 &*InsertionPt); 1188 } 1189 1190 /// Determine whether this alloca is either a VLA or an array. 1191 static bool isArray(AllocaInst *AI) { 1192 return AI->isArrayAllocation() || 1193 AI->getType()->getElementType()->isArrayTy(); 1194 } 1195 1196 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set 1197 /// of llvm.dbg.value intrinsics. 1198 bool llvm::LowerDbgDeclare(Function &F) { 1199 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false); 1200 SmallVector<DbgDeclareInst *, 4> Dbgs; 1201 for (auto &FI : F) 1202 for (Instruction &BI : FI) 1203 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI)) 1204 Dbgs.push_back(DDI); 1205 1206 if (Dbgs.empty()) 1207 return false; 1208 1209 for (auto &I : Dbgs) { 1210 DbgDeclareInst *DDI = I; 1211 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress()); 1212 // If this is an alloca for a scalar variable, insert a dbg.value 1213 // at each load and store to the alloca and erase the dbg.declare. 1214 // The dbg.values allow tracking a variable even if it is not 1215 // stored on the stack, while the dbg.declare can only describe 1216 // the stack slot (and at a lexical-scope granularity). Later 1217 // passes will attempt to elide the stack slot. 1218 if (AI && !isArray(AI)) { 1219 for (auto &AIUse : AI->uses()) { 1220 User *U = AIUse.getUser(); 1221 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 1222 if (AIUse.getOperandNo() == 1) 1223 ConvertDebugDeclareToDebugValue(DDI, SI, DIB); 1224 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 1225 ConvertDebugDeclareToDebugValue(DDI, LI, DIB); 1226 } else if (CallInst *CI = dyn_cast<CallInst>(U)) { 1227 // This is a call by-value or some other instruction that 1228 // takes a pointer to the variable. Insert a *value* 1229 // intrinsic that describes the alloca. 1230 SmallVector<uint64_t, 1> NewDIExpr; 1231 auto *DIExpr = DDI->getExpression(); 1232 NewDIExpr.push_back(dwarf::DW_OP_deref); 1233 NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end()); 1234 DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(), 1235 DIB.createExpression(NewDIExpr), 1236 DDI->getDebugLoc(), CI); 1237 } 1238 } 1239 DDI->eraseFromParent(); 1240 } 1241 } 1242 return true; 1243 } 1244 1245 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the 1246 /// alloca 'V', if any. 1247 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) { 1248 if (auto *L = LocalAsMetadata::getIfExists(V)) 1249 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) 1250 for (User *U : MDV->users()) 1251 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U)) 1252 return DDI; 1253 1254 return nullptr; 1255 } 1256 1257 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) { 1258 if (auto *L = LocalAsMetadata::getIfExists(V)) 1259 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) 1260 for (User *U : MDV->users()) 1261 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U)) 1262 DbgValues.push_back(DVI); 1263 } 1264 1265 static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset) { 1266 if (Offset > 0) { 1267 Ops.push_back(dwarf::DW_OP_plus); 1268 Ops.push_back(Offset); 1269 } else if (Offset < 0) { 1270 Ops.push_back(dwarf::DW_OP_minus); 1271 Ops.push_back(-Offset); 1272 } 1273 } 1274 1275 /// Prepend \p DIExpr with a deref and offset operation. 1276 static DIExpression *prependDIExpr(DIBuilder &Builder, DIExpression *DIExpr, 1277 bool Deref, int64_t Offset) { 1278 if (!Deref && !Offset) 1279 return DIExpr; 1280 // Create a copy of the original DIDescriptor for user variable, prepending 1281 // "deref" operation to a list of address elements, as new llvm.dbg.declare 1282 // will take a value storing address of the memory for variable, not 1283 // alloca itself. 1284 SmallVector<uint64_t, 4> Ops; 1285 if (Deref) 1286 Ops.push_back(dwarf::DW_OP_deref); 1287 appendOffset(Ops, Offset); 1288 if (DIExpr) 1289 Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()); 1290 return Builder.createExpression(Ops); 1291 } 1292 1293 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress, 1294 Instruction *InsertBefore, DIBuilder &Builder, 1295 bool Deref, int Offset) { 1296 DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address); 1297 if (!DDI) 1298 return false; 1299 DebugLoc Loc = DDI->getDebugLoc(); 1300 auto *DIVar = DDI->getVariable(); 1301 auto *DIExpr = DDI->getExpression(); 1302 assert(DIVar && "Missing variable"); 1303 1304 DIExpr = prependDIExpr(Builder, DIExpr, Deref, Offset); 1305 1306 // Insert llvm.dbg.declare immediately after the original alloca, and remove 1307 // old llvm.dbg.declare. 1308 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore); 1309 DDI->eraseFromParent(); 1310 return true; 1311 } 1312 1313 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, 1314 DIBuilder &Builder, bool Deref, int Offset) { 1315 return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder, 1316 Deref, Offset); 1317 } 1318 1319 static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress, 1320 DIBuilder &Builder, int Offset) { 1321 DebugLoc Loc = DVI->getDebugLoc(); 1322 auto *DIVar = DVI->getVariable(); 1323 auto *DIExpr = DVI->getExpression(); 1324 assert(DIVar && "Missing variable"); 1325 1326 // This is an alloca-based llvm.dbg.value. The first thing it should do with 1327 // the alloca pointer is dereference it. Otherwise we don't know how to handle 1328 // it and give up. 1329 if (!DIExpr || DIExpr->getNumElements() < 1 || 1330 DIExpr->getElement(0) != dwarf::DW_OP_deref) 1331 return; 1332 1333 // Insert the offset immediately after the first deref. 1334 // We could just change the offset argument of dbg.value, but it's unsigned... 1335 if (Offset) { 1336 SmallVector<uint64_t, 4> Ops; 1337 Ops.push_back(dwarf::DW_OP_deref); 1338 appendOffset(Ops, Offset); 1339 Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end()); 1340 DIExpr = Builder.createExpression(Ops); 1341 } 1342 1343 Builder.insertDbgValueIntrinsic(NewAddress, DVI->getOffset(), DIVar, DIExpr, 1344 Loc, DVI); 1345 DVI->eraseFromParent(); 1346 } 1347 1348 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, 1349 DIBuilder &Builder, int Offset) { 1350 if (auto *L = LocalAsMetadata::getIfExists(AI)) 1351 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L)) 1352 for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) { 1353 Use &U = *UI++; 1354 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser())) 1355 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset); 1356 } 1357 } 1358 1359 void llvm::salvageDebugInfo(Instruction &I) { 1360 SmallVector<DbgValueInst *, 1> DbgValues; 1361 auto &M = *I.getModule(); 1362 1363 auto MDWrap = [&](Value *V) { 1364 return MetadataAsValue::get(I.getContext(), ValueAsMetadata::get(V)); 1365 }; 1366 1367 if (isa<BitCastInst>(&I)) { 1368 findDbgValues(DbgValues, &I); 1369 for (auto *DVI : DbgValues) { 1370 // Bitcasts are entirely irrelevant for debug info. Rewrite the dbg.value 1371 // to use the cast's source. 1372 DVI->setOperand(0, MDWrap(I.getOperand(0))); 1373 DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n'); 1374 } 1375 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 1376 findDbgValues(DbgValues, &I); 1377 for (auto *DVI : DbgValues) { 1378 unsigned BitWidth = 1379 M.getDataLayout().getPointerSizeInBits(GEP->getPointerAddressSpace()); 1380 APInt Offset(BitWidth, 0); 1381 // Rewrite a constant GEP into a DIExpression. 1382 if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) { 1383 auto *DIExpr = DVI->getExpression(); 1384 DIBuilder DIB(M, /*AllowUnresolved*/ false); 1385 // GEP offsets are i32 and thus alwaus fit into an int64_t. 1386 DIExpr = prependDIExpr(DIB, DIExpr, NoDeref, Offset.getSExtValue()); 1387 DVI->setOperand(0, MDWrap(I.getOperand(0))); 1388 DVI->setOperand(3, MetadataAsValue::get(I.getContext(), DIExpr)); 1389 DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n'); 1390 } 1391 } 1392 } else if (isa<LoadInst>(&I)) { 1393 findDbgValues(DbgValues, &I); 1394 for (auto *DVI : DbgValues) { 1395 // Rewrite the load into DW_OP_deref. 1396 auto *DIExpr = DVI->getExpression(); 1397 DIBuilder DIB(M, /*AllowUnresolved*/ false); 1398 DIExpr = prependDIExpr(DIB, DIExpr, WithDeref, 0); 1399 DVI->setOperand(0, MDWrap(I.getOperand(0))); 1400 DVI->setOperand(3, MetadataAsValue::get(I.getContext(), DIExpr)); 1401 DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n'); 1402 } 1403 } 1404 } 1405 1406 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) { 1407 unsigned NumDeadInst = 0; 1408 // Delete the instructions backwards, as it has a reduced likelihood of 1409 // having to update as many def-use and use-def chains. 1410 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted. 1411 while (EndInst != &BB->front()) { 1412 // Delete the next to last instruction. 1413 Instruction *Inst = &*--EndInst->getIterator(); 1414 if (!Inst->use_empty() && !Inst->getType()->isTokenTy()) 1415 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType())); 1416 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) { 1417 EndInst = Inst; 1418 continue; 1419 } 1420 if (!isa<DbgInfoIntrinsic>(Inst)) 1421 ++NumDeadInst; 1422 Inst->eraseFromParent(); 1423 } 1424 return NumDeadInst; 1425 } 1426 1427 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap, 1428 bool PreserveLCSSA) { 1429 BasicBlock *BB = I->getParent(); 1430 // Loop over all of the successors, removing BB's entry from any PHI 1431 // nodes. 1432 for (BasicBlock *Successor : successors(BB)) 1433 Successor->removePredecessor(BB, PreserveLCSSA); 1434 1435 // Insert a call to llvm.trap right before this. This turns the undefined 1436 // behavior into a hard fail instead of falling through into random code. 1437 if (UseLLVMTrap) { 1438 Function *TrapFn = 1439 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap); 1440 CallInst *CallTrap = CallInst::Create(TrapFn, "", I); 1441 CallTrap->setDebugLoc(I->getDebugLoc()); 1442 } 1443 new UnreachableInst(I->getContext(), I); 1444 1445 // All instructions after this are dead. 1446 unsigned NumInstrsRemoved = 0; 1447 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end(); 1448 while (BBI != BBE) { 1449 if (!BBI->use_empty()) 1450 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 1451 BB->getInstList().erase(BBI++); 1452 ++NumInstrsRemoved; 1453 } 1454 return NumInstrsRemoved; 1455 } 1456 1457 /// changeToCall - Convert the specified invoke into a normal call. 1458 static void changeToCall(InvokeInst *II) { 1459 SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end()); 1460 SmallVector<OperandBundleDef, 1> OpBundles; 1461 II->getOperandBundlesAsDefs(OpBundles); 1462 CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles, 1463 "", II); 1464 NewCall->takeName(II); 1465 NewCall->setCallingConv(II->getCallingConv()); 1466 NewCall->setAttributes(II->getAttributes()); 1467 NewCall->setDebugLoc(II->getDebugLoc()); 1468 II->replaceAllUsesWith(NewCall); 1469 1470 // Follow the call by a branch to the normal destination. 1471 BranchInst::Create(II->getNormalDest(), II); 1472 1473 // Update PHI nodes in the unwind destination 1474 II->getUnwindDest()->removePredecessor(II->getParent()); 1475 II->eraseFromParent(); 1476 } 1477 1478 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI, 1479 BasicBlock *UnwindEdge) { 1480 BasicBlock *BB = CI->getParent(); 1481 1482 // Convert this function call into an invoke instruction. First, split the 1483 // basic block. 1484 BasicBlock *Split = 1485 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc"); 1486 1487 // Delete the unconditional branch inserted by splitBasicBlock 1488 BB->getInstList().pop_back(); 1489 1490 // Create the new invoke instruction. 1491 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end()); 1492 SmallVector<OperandBundleDef, 1> OpBundles; 1493 1494 CI->getOperandBundlesAsDefs(OpBundles); 1495 1496 // Note: we're round tripping operand bundles through memory here, and that 1497 // can potentially be avoided with a cleverer API design that we do not have 1498 // as of this time. 1499 1500 InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge, 1501 InvokeArgs, OpBundles, CI->getName(), BB); 1502 II->setDebugLoc(CI->getDebugLoc()); 1503 II->setCallingConv(CI->getCallingConv()); 1504 II->setAttributes(CI->getAttributes()); 1505 1506 // Make sure that anything using the call now uses the invoke! This also 1507 // updates the CallGraph if present, because it uses a WeakVH. 1508 CI->replaceAllUsesWith(II); 1509 1510 // Delete the original call 1511 Split->getInstList().pop_front(); 1512 return Split; 1513 } 1514 1515 static bool markAliveBlocks(Function &F, 1516 SmallPtrSetImpl<BasicBlock*> &Reachable) { 1517 1518 SmallVector<BasicBlock*, 128> Worklist; 1519 BasicBlock *BB = &F.front(); 1520 Worklist.push_back(BB); 1521 Reachable.insert(BB); 1522 bool Changed = false; 1523 do { 1524 BB = Worklist.pop_back_val(); 1525 1526 // Do a quick scan of the basic block, turning any obviously unreachable 1527 // instructions into LLVM unreachable insts. The instruction combining pass 1528 // canonicalizes unreachable insts into stores to null or undef. 1529 for (Instruction &I : *BB) { 1530 // Assumptions that are known to be false are equivalent to unreachable. 1531 // Also, if the condition is undefined, then we make the choice most 1532 // beneficial to the optimizer, and choose that to also be unreachable. 1533 if (auto *II = dyn_cast<IntrinsicInst>(&I)) { 1534 if (II->getIntrinsicID() == Intrinsic::assume) { 1535 if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) { 1536 // Don't insert a call to llvm.trap right before the unreachable. 1537 changeToUnreachable(II, false); 1538 Changed = true; 1539 break; 1540 } 1541 } 1542 1543 if (II->getIntrinsicID() == Intrinsic::experimental_guard) { 1544 // A call to the guard intrinsic bails out of the current compilation 1545 // unit if the predicate passed to it is false. If the predicate is a 1546 // constant false, then we know the guard will bail out of the current 1547 // compile unconditionally, so all code following it is dead. 1548 // 1549 // Note: unlike in llvm.assume, it is not "obviously profitable" for 1550 // guards to treat `undef` as `false` since a guard on `undef` can 1551 // still be useful for widening. 1552 if (match(II->getArgOperand(0), m_Zero())) 1553 if (!isa<UnreachableInst>(II->getNextNode())) { 1554 changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false); 1555 Changed = true; 1556 break; 1557 } 1558 } 1559 } 1560 1561 if (auto *CI = dyn_cast<CallInst>(&I)) { 1562 Value *Callee = CI->getCalledValue(); 1563 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) { 1564 changeToUnreachable(CI, /*UseLLVMTrap=*/false); 1565 Changed = true; 1566 break; 1567 } 1568 if (CI->doesNotReturn()) { 1569 // If we found a call to a no-return function, insert an unreachable 1570 // instruction after it. Make sure there isn't *already* one there 1571 // though. 1572 if (!isa<UnreachableInst>(CI->getNextNode())) { 1573 // Don't insert a call to llvm.trap right before the unreachable. 1574 changeToUnreachable(CI->getNextNode(), false); 1575 Changed = true; 1576 } 1577 break; 1578 } 1579 } 1580 1581 // Store to undef and store to null are undefined and used to signal that 1582 // they should be changed to unreachable by passes that can't modify the 1583 // CFG. 1584 if (auto *SI = dyn_cast<StoreInst>(&I)) { 1585 // Don't touch volatile stores. 1586 if (SI->isVolatile()) continue; 1587 1588 Value *Ptr = SI->getOperand(1); 1589 1590 if (isa<UndefValue>(Ptr) || 1591 (isa<ConstantPointerNull>(Ptr) && 1592 SI->getPointerAddressSpace() == 0)) { 1593 changeToUnreachable(SI, true); 1594 Changed = true; 1595 break; 1596 } 1597 } 1598 } 1599 1600 TerminatorInst *Terminator = BB->getTerminator(); 1601 if (auto *II = dyn_cast<InvokeInst>(Terminator)) { 1602 // Turn invokes that call 'nounwind' functions into ordinary calls. 1603 Value *Callee = II->getCalledValue(); 1604 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) { 1605 changeToUnreachable(II, true); 1606 Changed = true; 1607 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) { 1608 if (II->use_empty() && II->onlyReadsMemory()) { 1609 // jump to the normal destination branch. 1610 BranchInst::Create(II->getNormalDest(), II); 1611 II->getUnwindDest()->removePredecessor(II->getParent()); 1612 II->eraseFromParent(); 1613 } else 1614 changeToCall(II); 1615 Changed = true; 1616 } 1617 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) { 1618 // Remove catchpads which cannot be reached. 1619 struct CatchPadDenseMapInfo { 1620 static CatchPadInst *getEmptyKey() { 1621 return DenseMapInfo<CatchPadInst *>::getEmptyKey(); 1622 } 1623 static CatchPadInst *getTombstoneKey() { 1624 return DenseMapInfo<CatchPadInst *>::getTombstoneKey(); 1625 } 1626 static unsigned getHashValue(CatchPadInst *CatchPad) { 1627 return static_cast<unsigned>(hash_combine_range( 1628 CatchPad->value_op_begin(), CatchPad->value_op_end())); 1629 } 1630 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) { 1631 if (LHS == getEmptyKey() || LHS == getTombstoneKey() || 1632 RHS == getEmptyKey() || RHS == getTombstoneKey()) 1633 return LHS == RHS; 1634 return LHS->isIdenticalTo(RHS); 1635 } 1636 }; 1637 1638 // Set of unique CatchPads. 1639 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4, 1640 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>> 1641 HandlerSet; 1642 detail::DenseSetEmpty Empty; 1643 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(), 1644 E = CatchSwitch->handler_end(); 1645 I != E; ++I) { 1646 BasicBlock *HandlerBB = *I; 1647 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI()); 1648 if (!HandlerSet.insert({CatchPad, Empty}).second) { 1649 CatchSwitch->removeHandler(I); 1650 --I; 1651 --E; 1652 Changed = true; 1653 } 1654 } 1655 } 1656 1657 Changed |= ConstantFoldTerminator(BB, true); 1658 for (BasicBlock *Successor : successors(BB)) 1659 if (Reachable.insert(Successor).second) 1660 Worklist.push_back(Successor); 1661 } while (!Worklist.empty()); 1662 return Changed; 1663 } 1664 1665 void llvm::removeUnwindEdge(BasicBlock *BB) { 1666 TerminatorInst *TI = BB->getTerminator(); 1667 1668 if (auto *II = dyn_cast<InvokeInst>(TI)) { 1669 changeToCall(II); 1670 return; 1671 } 1672 1673 TerminatorInst *NewTI; 1674 BasicBlock *UnwindDest; 1675 1676 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 1677 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI); 1678 UnwindDest = CRI->getUnwindDest(); 1679 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) { 1680 auto *NewCatchSwitch = CatchSwitchInst::Create( 1681 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(), 1682 CatchSwitch->getName(), CatchSwitch); 1683 for (BasicBlock *PadBB : CatchSwitch->handlers()) 1684 NewCatchSwitch->addHandler(PadBB); 1685 1686 NewTI = NewCatchSwitch; 1687 UnwindDest = CatchSwitch->getUnwindDest(); 1688 } else { 1689 llvm_unreachable("Could not find unwind successor"); 1690 } 1691 1692 NewTI->takeName(TI); 1693 NewTI->setDebugLoc(TI->getDebugLoc()); 1694 UnwindDest->removePredecessor(BB); 1695 TI->replaceAllUsesWith(NewTI); 1696 TI->eraseFromParent(); 1697 } 1698 1699 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even 1700 /// if they are in a dead cycle. Return true if a change was made, false 1701 /// otherwise. 1702 bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) { 1703 SmallPtrSet<BasicBlock*, 16> Reachable; 1704 bool Changed = markAliveBlocks(F, Reachable); 1705 1706 // If there are unreachable blocks in the CFG... 1707 if (Reachable.size() == F.size()) 1708 return Changed; 1709 1710 assert(Reachable.size() < F.size()); 1711 NumRemoved += F.size()-Reachable.size(); 1712 1713 // Loop over all of the basic blocks that are not reachable, dropping all of 1714 // their internal references... 1715 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) { 1716 if (Reachable.count(&*BB)) 1717 continue; 1718 1719 for (BasicBlock *Successor : successors(&*BB)) 1720 if (Reachable.count(Successor)) 1721 Successor->removePredecessor(&*BB); 1722 if (LVI) 1723 LVI->eraseBlock(&*BB); 1724 BB->dropAllReferences(); 1725 } 1726 1727 for (Function::iterator I = ++F.begin(); I != F.end();) 1728 if (!Reachable.count(&*I)) 1729 I = F.getBasicBlockList().erase(I); 1730 else 1731 ++I; 1732 1733 return true; 1734 } 1735 1736 void llvm::combineMetadata(Instruction *K, const Instruction *J, 1737 ArrayRef<unsigned> KnownIDs) { 1738 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 1739 K->dropUnknownNonDebugMetadata(KnownIDs); 1740 K->getAllMetadataOtherThanDebugLoc(Metadata); 1741 for (const auto &MD : Metadata) { 1742 unsigned Kind = MD.first; 1743 MDNode *JMD = J->getMetadata(Kind); 1744 MDNode *KMD = MD.second; 1745 1746 switch (Kind) { 1747 default: 1748 K->setMetadata(Kind, nullptr); // Remove unknown metadata 1749 break; 1750 case LLVMContext::MD_dbg: 1751 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg"); 1752 case LLVMContext::MD_tbaa: 1753 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD)); 1754 break; 1755 case LLVMContext::MD_alias_scope: 1756 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD)); 1757 break; 1758 case LLVMContext::MD_noalias: 1759 case LLVMContext::MD_mem_parallel_loop_access: 1760 K->setMetadata(Kind, MDNode::intersect(JMD, KMD)); 1761 break; 1762 case LLVMContext::MD_range: 1763 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD)); 1764 break; 1765 case LLVMContext::MD_fpmath: 1766 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD)); 1767 break; 1768 case LLVMContext::MD_invariant_load: 1769 // Only set the !invariant.load if it is present in both instructions. 1770 K->setMetadata(Kind, JMD); 1771 break; 1772 case LLVMContext::MD_nonnull: 1773 // Only set the !nonnull if it is present in both instructions. 1774 K->setMetadata(Kind, JMD); 1775 break; 1776 case LLVMContext::MD_invariant_group: 1777 // Preserve !invariant.group in K. 1778 break; 1779 case LLVMContext::MD_align: 1780 K->setMetadata(Kind, 1781 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD)); 1782 break; 1783 case LLVMContext::MD_dereferenceable: 1784 case LLVMContext::MD_dereferenceable_or_null: 1785 K->setMetadata(Kind, 1786 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD)); 1787 break; 1788 } 1789 } 1790 // Set !invariant.group from J if J has it. If both instructions have it 1791 // then we will just pick it from J - even when they are different. 1792 // Also make sure that K is load or store - f.e. combining bitcast with load 1793 // could produce bitcast with invariant.group metadata, which is invalid. 1794 // FIXME: we should try to preserve both invariant.group md if they are 1795 // different, but right now instruction can only have one invariant.group. 1796 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group)) 1797 if (isa<LoadInst>(K) || isa<StoreInst>(K)) 1798 K->setMetadata(LLVMContext::MD_invariant_group, JMD); 1799 } 1800 1801 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J) { 1802 unsigned KnownIDs[] = { 1803 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 1804 LLVMContext::MD_noalias, LLVMContext::MD_range, 1805 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull, 1806 LLVMContext::MD_invariant_group, LLVMContext::MD_align, 1807 LLVMContext::MD_dereferenceable, 1808 LLVMContext::MD_dereferenceable_or_null}; 1809 combineMetadata(K, J, KnownIDs); 1810 } 1811 1812 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, 1813 DominatorTree &DT, 1814 const BasicBlockEdge &Root) { 1815 assert(From->getType() == To->getType()); 1816 1817 unsigned Count = 0; 1818 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); 1819 UI != UE; ) { 1820 Use &U = *UI++; 1821 if (DT.dominates(Root, U)) { 1822 U.set(To); 1823 DEBUG(dbgs() << "Replace dominated use of '" 1824 << From->getName() << "' as " 1825 << *To << " in " << *U << "\n"); 1826 ++Count; 1827 } 1828 } 1829 return Count; 1830 } 1831 1832 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, 1833 DominatorTree &DT, 1834 const BasicBlock *BB) { 1835 assert(From->getType() == To->getType()); 1836 1837 unsigned Count = 0; 1838 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); 1839 UI != UE;) { 1840 Use &U = *UI++; 1841 auto *I = cast<Instruction>(U.getUser()); 1842 if (DT.properlyDominates(BB, I->getParent())) { 1843 U.set(To); 1844 DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as " 1845 << *To << " in " << *U << "\n"); 1846 ++Count; 1847 } 1848 } 1849 return Count; 1850 } 1851 1852 bool llvm::callsGCLeafFunction(ImmutableCallSite CS) { 1853 // Check if the function is specifically marked as a gc leaf function. 1854 if (CS.hasFnAttr("gc-leaf-function")) 1855 return true; 1856 if (const Function *F = CS.getCalledFunction()) { 1857 if (F->hasFnAttribute("gc-leaf-function")) 1858 return true; 1859 1860 if (auto IID = F->getIntrinsicID()) 1861 // Most LLVM intrinsics do not take safepoints. 1862 return IID != Intrinsic::experimental_gc_statepoint && 1863 IID != Intrinsic::experimental_deoptimize; 1864 } 1865 1866 return false; 1867 } 1868 1869 namespace { 1870 /// A potential constituent of a bitreverse or bswap expression. See 1871 /// collectBitParts for a fuller explanation. 1872 struct BitPart { 1873 BitPart(Value *P, unsigned BW) : Provider(P) { 1874 Provenance.resize(BW); 1875 } 1876 1877 /// The Value that this is a bitreverse/bswap of. 1878 Value *Provider; 1879 /// The "provenance" of each bit. Provenance[A] = B means that bit A 1880 /// in Provider becomes bit B in the result of this expression. 1881 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128. 1882 1883 enum { Unset = -1 }; 1884 }; 1885 } // end anonymous namespace 1886 1887 /// Analyze the specified subexpression and see if it is capable of providing 1888 /// pieces of a bswap or bitreverse. The subexpression provides a potential 1889 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in 1890 /// the output of the expression came from a corresponding bit in some other 1891 /// value. This function is recursive, and the end result is a mapping of 1892 /// bitnumber to bitnumber. It is the caller's responsibility to validate that 1893 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse. 1894 /// 1895 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know 1896 /// that the expression deposits the low byte of %X into the high byte of the 1897 /// result and that all other bits are zero. This expression is accepted and a 1898 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to 1899 /// [0-7]. 1900 /// 1901 /// To avoid revisiting values, the BitPart results are memoized into the 1902 /// provided map. To avoid unnecessary copying of BitParts, BitParts are 1903 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to 1904 /// store BitParts objects, not pointers. As we need the concept of a nullptr 1905 /// BitParts (Value has been analyzed and the analysis failed), we an Optional 1906 /// type instead to provide the same functionality. 1907 /// 1908 /// Because we pass around references into \c BPS, we must use a container that 1909 /// does not invalidate internal references (std::map instead of DenseMap). 1910 /// 1911 static const Optional<BitPart> & 1912 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals, 1913 std::map<Value *, Optional<BitPart>> &BPS) { 1914 auto I = BPS.find(V); 1915 if (I != BPS.end()) 1916 return I->second; 1917 1918 auto &Result = BPS[V] = None; 1919 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 1920 1921 if (Instruction *I = dyn_cast<Instruction>(V)) { 1922 // If this is an or instruction, it may be an inner node of the bswap. 1923 if (I->getOpcode() == Instruction::Or) { 1924 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps, 1925 MatchBitReversals, BPS); 1926 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps, 1927 MatchBitReversals, BPS); 1928 if (!A || !B) 1929 return Result; 1930 1931 // Try and merge the two together. 1932 if (!A->Provider || A->Provider != B->Provider) 1933 return Result; 1934 1935 Result = BitPart(A->Provider, BitWidth); 1936 for (unsigned i = 0; i < A->Provenance.size(); ++i) { 1937 if (A->Provenance[i] != BitPart::Unset && 1938 B->Provenance[i] != BitPart::Unset && 1939 A->Provenance[i] != B->Provenance[i]) 1940 return Result = None; 1941 1942 if (A->Provenance[i] == BitPart::Unset) 1943 Result->Provenance[i] = B->Provenance[i]; 1944 else 1945 Result->Provenance[i] = A->Provenance[i]; 1946 } 1947 1948 return Result; 1949 } 1950 1951 // If this is a logical shift by a constant, recurse then shift the result. 1952 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) { 1953 unsigned BitShift = 1954 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U); 1955 // Ensure the shift amount is defined. 1956 if (BitShift > BitWidth) 1957 return Result; 1958 1959 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 1960 MatchBitReversals, BPS); 1961 if (!Res) 1962 return Result; 1963 Result = Res; 1964 1965 // Perform the "shift" on BitProvenance. 1966 auto &P = Result->Provenance; 1967 if (I->getOpcode() == Instruction::Shl) { 1968 P.erase(std::prev(P.end(), BitShift), P.end()); 1969 P.insert(P.begin(), BitShift, BitPart::Unset); 1970 } else { 1971 P.erase(P.begin(), std::next(P.begin(), BitShift)); 1972 P.insert(P.end(), BitShift, BitPart::Unset); 1973 } 1974 1975 return Result; 1976 } 1977 1978 // If this is a logical 'and' with a mask that clears bits, recurse then 1979 // unset the appropriate bits. 1980 if (I->getOpcode() == Instruction::And && 1981 isa<ConstantInt>(I->getOperand(1))) { 1982 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1); 1983 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue(); 1984 1985 // Check that the mask allows a multiple of 8 bits for a bswap, for an 1986 // early exit. 1987 unsigned NumMaskedBits = AndMask.countPopulation(); 1988 if (!MatchBitReversals && NumMaskedBits % 8 != 0) 1989 return Result; 1990 1991 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 1992 MatchBitReversals, BPS); 1993 if (!Res) 1994 return Result; 1995 Result = Res; 1996 1997 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1) 1998 // If the AndMask is zero for this bit, clear the bit. 1999 if ((AndMask & Bit) == 0) 2000 Result->Provenance[i] = BitPart::Unset; 2001 return Result; 2002 } 2003 2004 // If this is a zext instruction zero extend the result. 2005 if (I->getOpcode() == Instruction::ZExt) { 2006 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 2007 MatchBitReversals, BPS); 2008 if (!Res) 2009 return Result; 2010 2011 Result = BitPart(Res->Provider, BitWidth); 2012 auto NarrowBitWidth = 2013 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth(); 2014 for (unsigned i = 0; i < NarrowBitWidth; ++i) 2015 Result->Provenance[i] = Res->Provenance[i]; 2016 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i) 2017 Result->Provenance[i] = BitPart::Unset; 2018 return Result; 2019 } 2020 } 2021 2022 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be 2023 // the input value to the bswap/bitreverse. 2024 Result = BitPart(V, BitWidth); 2025 for (unsigned i = 0; i < BitWidth; ++i) 2026 Result->Provenance[i] = i; 2027 return Result; 2028 } 2029 2030 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To, 2031 unsigned BitWidth) { 2032 if (From % 8 != To % 8) 2033 return false; 2034 // Convert from bit indices to byte indices and check for a byte reversal. 2035 From >>= 3; 2036 To >>= 3; 2037 BitWidth >>= 3; 2038 return From == BitWidth - To - 1; 2039 } 2040 2041 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To, 2042 unsigned BitWidth) { 2043 return From == BitWidth - To - 1; 2044 } 2045 2046 /// Given an OR instruction, check to see if this is a bitreverse 2047 /// idiom. If so, insert the new intrinsic and return true. 2048 bool llvm::recognizeBSwapOrBitReverseIdiom( 2049 Instruction *I, bool MatchBSwaps, bool MatchBitReversals, 2050 SmallVectorImpl<Instruction *> &InsertedInsts) { 2051 if (Operator::getOpcode(I) != Instruction::Or) 2052 return false; 2053 if (!MatchBSwaps && !MatchBitReversals) 2054 return false; 2055 IntegerType *ITy = dyn_cast<IntegerType>(I->getType()); 2056 if (!ITy || ITy->getBitWidth() > 128) 2057 return false; // Can't do vectors or integers > 128 bits. 2058 unsigned BW = ITy->getBitWidth(); 2059 2060 unsigned DemandedBW = BW; 2061 IntegerType *DemandedTy = ITy; 2062 if (I->hasOneUse()) { 2063 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) { 2064 DemandedTy = cast<IntegerType>(Trunc->getType()); 2065 DemandedBW = DemandedTy->getBitWidth(); 2066 } 2067 } 2068 2069 // Try to find all the pieces corresponding to the bswap. 2070 std::map<Value *, Optional<BitPart>> BPS; 2071 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS); 2072 if (!Res) 2073 return false; 2074 auto &BitProvenance = Res->Provenance; 2075 2076 // Now, is the bit permutation correct for a bswap or a bitreverse? We can 2077 // only byteswap values with an even number of bytes. 2078 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true; 2079 for (unsigned i = 0; i < DemandedBW; ++i) { 2080 OKForBSwap &= 2081 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW); 2082 OKForBitReverse &= 2083 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW); 2084 } 2085 2086 Intrinsic::ID Intrin; 2087 if (OKForBSwap && MatchBSwaps) 2088 Intrin = Intrinsic::bswap; 2089 else if (OKForBitReverse && MatchBitReversals) 2090 Intrin = Intrinsic::bitreverse; 2091 else 2092 return false; 2093 2094 if (ITy != DemandedTy) { 2095 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy); 2096 Value *Provider = Res->Provider; 2097 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType()); 2098 // We may need to truncate the provider. 2099 if (DemandedTy != ProviderTy) { 2100 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy, 2101 "trunc", I); 2102 InsertedInsts.push_back(Trunc); 2103 Provider = Trunc; 2104 } 2105 auto *CI = CallInst::Create(F, Provider, "rev", I); 2106 InsertedInsts.push_back(CI); 2107 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I); 2108 InsertedInsts.push_back(ExtInst); 2109 return true; 2110 } 2111 2112 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy); 2113 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I)); 2114 return true; 2115 } 2116 2117 // CodeGen has special handling for some string functions that may replace 2118 // them with target-specific intrinsics. Since that'd skip our interceptors 2119 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses, 2120 // we mark affected calls as NoBuiltin, which will disable optimization 2121 // in CodeGen. 2122 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin( 2123 CallInst *CI, const TargetLibraryInfo *TLI) { 2124 Function *F = CI->getCalledFunction(); 2125 LibFunc Func; 2126 if (F && !F->hasLocalLinkage() && F->hasName() && 2127 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) && 2128 !F->doesNotAccessMemory()) 2129 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin); 2130 } 2131