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