1 //===-- Local.cpp - Functions to perform local transformations ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
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"
42 //===----------------------------------------------------------------------===//
43 // Local constant propagation.
46 // ConstantFoldTerminator - If a terminator instruction is predicated on a
47 // constant value, convert it into an unconditional branch to the constant
50 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
51 TerminatorInst *T = BB->getTerminator();
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);
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;
65 //cerr << "Function: " << T->getParent()->getParent()
66 // << "\nRemoving branch from " << T->getParent()
67 // << "\n\nTo: " << OldDest << endl;
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());
74 // Replace the conditional branch with an unconditional one.
75 BranchInst::Create(Destination, BI);
76 BI->eraseFromParent();
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
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());
89 // Replace the conditional branch with an unconditional one.
90 BranchInst::Create(Dest1, BI);
91 BI->eraseFromParent();
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?");
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);
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());
120 --i; --e; // Don't skip an entry...
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
127 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
130 if (CI && !TheOnlyDest) {
131 // Branching on a constant, but not any of the cases, go to the default
133 TheOnlyDest = SI->getDefaultDest();
136 // If we found a single destination that we can fold the switch into, do so
139 // Insert the new branch.
140 BranchInst::Create(TheOnlyDest, SI);
141 BasicBlock *BB = SI->getParent();
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
150 Succ->removePredecessor(BB);
153 // Delete the old switch.
154 BB->getInstList().erase(SI);
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);
166 // Delete the old switch.
167 SI->eraseFromParent();
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);
181 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
182 if (IBI->getDestination(i) == TheOnlyDest)
185 IBI->getDestination(i)->removePredecessor(IBI->getParent());
187 IBI->eraseFromParent();
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.
193 BB->getTerminator()->eraseFromParent();
194 new UnreachableInst(BB->getContext(), BB);
205 //===----------------------------------------------------------------------===//
206 // Local dead code elimination.
209 /// isInstructionTriviallyDead - Return true if the result produced by the
210 /// instruction is not used, and the instruction has no side effects.
212 bool llvm::isInstructionTriviallyDead(Instruction *I) {
213 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
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())
222 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
228 if (!I->mayHaveSideEffects()) return true;
230 // Special case intrinsics that "may have side effects" but can be deleted
232 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
233 // Safe to delete llvm.stacksave if dead.
234 if (II->getIntrinsicID() == Intrinsic::stacksave)
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))
248 SmallVector<Instruction*, 16> DeadInsts;
249 DeadInsts.push_back(I);
252 I = DeadInsts.pop_back_val();
254 // Null out all of the instruction's operands to see if any operand becomes
256 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
257 Value *OpV = I->getOperand(i);
260 if (!OpV->use_empty()) continue;
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
265 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
266 if (isInstructionTriviallyDead(OpI))
267 DeadInsts.push_back(OpI);
270 I->eraseFromParent();
271 } while (!DeadInsts.empty());
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
280 static bool areAllUsesEqual(Instruction *I) {
281 Value::use_iterator UI = I->use_begin();
282 Value::use_iterator UE = I->use_end();
287 for (++UI; UI != UE; ++UI) {
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())) {
304 return RecursivelyDeleteTriviallyDeadInstructions(I);
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);
318 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
319 /// simplify any instructions in it and recursively delete dead instructions.
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++;
328 if (Value *V = SimplifyInstruction(Inst, TD)) {
330 ReplaceAndSimplifyAllUses(Inst, V, TD);
337 if (Inst->isTerminator())
341 MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
348 //===----------------------------------------------------------------------===//
349 // Control Flow Graph Restructuring.
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.
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)
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,
366 // This only adjusts blocks with PHI nodes.
367 if (!isa<PHINode>(BB->begin()))
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);
375 WeakVH PhiIt = &BB->front();
376 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
377 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
379 Value *PNV = SimplifyInstruction(PN, TD);
380 if (PNV == 0) continue;
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!");
386 Value *OldPhiIt = PhiIt;
387 ReplaceAndSimplifyAllUses(PN, PNV, TD);
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
392 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
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.
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();
412 BasicBlock *PredBB = DestBB->getSinglePredecessor();
413 assert(PredBB && "Block doesn't have a single predecessor!");
415 // Splice all the instructions from PredBB to DestBB.
416 PredBB->getTerminator()->eraseFromParent();
417 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
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,
427 BA->destroyConstant();
430 // Anything that branched to PredBB now branches to DestBB.
431 PredBB->replaceAllUsesWith(DestBB);
434 DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
436 BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
437 DT->changeImmediateDominator(DestBB, PredBBIDom);
438 DT->eraseNode(PredBB);
440 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
442 PI->replaceAllUses(PredBB, DestBB);
443 PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
447 PredBB->eraseFromParent();
450 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
451 /// almost-empty BB ending in an unconditional branch to Succ, into succ.
453 /// Assumption: Succ is the single successor for BB.
455 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
456 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
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
462 if (Succ->getSinglePredecessor()) return true;
464 // Make a list of the predecessors of BB
465 typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
466 BlockSet BBPreds(pred_begin(BB), pred_end(BB));
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);
473 if (BBPreds.count(P))
474 CommonPreds.insert(P);
477 // Shortcut, if there are no common predecessors, merging is always safe
478 if (CommonPreds.empty())
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);
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();
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");
503 Value* Val = PN->getIncomingValueForBlock(BB);
504 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
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
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");
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!");
531 // We can't eliminate infinite loops.
532 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
533 if (BB == Succ) return false;
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;
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
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();
556 if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
557 if (PN->getIncomingBlock(UI) != BB)
567 DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
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
573 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
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!");
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));
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]);
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());
608 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
609 assert(PN->use_empty() && "There shouldn't be any uses here!");
610 PN->eraseFromParent();
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.
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.
626 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
627 bool Changed = false;
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.
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;
638 // Maintain linked lists of PHI nodes with common hash values.
639 DenseMap<PHINode *, PHINode *> CollisionMap;
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.
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));
654 // Avoid colliding with the DenseMap sentinels ~0 and ~0-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();
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;
678 // Procede to the next PHI in the list.
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.
692 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
693 unsigned PrefAlign) {
695 User *U = dyn_cast<User>(V);
696 if (!U) return Align;
698 switch (Operator::getOpcode(U)) {
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;
712 if (AllZeroOperands) {
713 // Treat this like a bitcast.
714 return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
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);
728 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
729 // If there is a large requested alignment and we can, bump up the alignment
731 if (GV->isDeclaration()) return Align;
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();
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();
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));
765 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
767 // LLVM doesn't support alignments larger than this currently.
768 Align = std::min(Align, +Value::MaximumAlignment);
770 if (PrefAlign > Align)
771 Align = enforceKnownAlignment(V, Align, PrefAlign);
773 // We don't need to make any adjustment.
777 ///===---------------------------------------------------------------------===//
778 /// Dbg Intrinsic utilities
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());
789 Instruction *DbgVal =
790 Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0,
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.
799 DbgVal->setDebugLoc(DDI->getDebugLoc());
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());
811 Instruction *DbgVal =
812 Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
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.
821 DbgVal->setDebugLoc(DDI->getDebugLoc());
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))
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();
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);
849 DDI->eraseFromParent();