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