[NVPTX] Generate a more optimal sequence for select of i1
[oota-llvm.git] / lib / Transforms / Utils / Local.cpp
1 //===-- Local.cpp - Functions to perform local transformations ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions perform various local transformations to the
11 // program.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/MemoryBuiltins.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DIBuilder.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/GetElementPtrTypeIterator.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_ostream.h"
44 using namespace llvm;
45
46 #define DEBUG_TYPE "local"
47
48 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
49
50 //===----------------------------------------------------------------------===//
51 //  Local constant propagation.
52 //
53
54 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
55 /// constant value, convert it into an unconditional branch to the constant
56 /// destination.  This is a nontrivial operation because the successors of this
57 /// basic block must have their PHI nodes updated.
58 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
59 /// conditions and indirectbr addresses this might make dead if
60 /// DeleteDeadConditions is true.
61 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
62                                   const TargetLibraryInfo *TLI) {
63   TerminatorInst *T = BB->getTerminator();
64   IRBuilder<> Builder(T);
65
66   // Branch - See if we are conditional jumping on constant
67   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
68     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
69     BasicBlock *Dest1 = BI->getSuccessor(0);
70     BasicBlock *Dest2 = BI->getSuccessor(1);
71
72     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
73       // Are we branching on constant?
74       // YES.  Change to unconditional branch...
75       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
76       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
77
78       //cerr << "Function: " << T->getParent()->getParent()
79       //     << "\nRemoving branch from " << T->getParent()
80       //     << "\n\nTo: " << OldDest << endl;
81
82       // Let the basic block know that we are letting go of it.  Based on this,
83       // it will adjust it's PHI nodes.
84       OldDest->removePredecessor(BB);
85
86       // Replace the conditional branch with an unconditional one.
87       Builder.CreateBr(Destination);
88       BI->eraseFromParent();
89       return true;
90     }
91
92     if (Dest2 == Dest1) {       // Conditional branch to same location?
93       // This branch matches something like this:
94       //     br bool %cond, label %Dest, label %Dest
95       // and changes it into:  br label %Dest
96
97       // Let the basic block know that we are letting go of one copy of it.
98       assert(BI->getParent() && "Terminator not inserted in block!");
99       Dest1->removePredecessor(BI->getParent());
100
101       // Replace the conditional branch with an unconditional one.
102       Builder.CreateBr(Dest1);
103       Value *Cond = BI->getCondition();
104       BI->eraseFromParent();
105       if (DeleteDeadConditions)
106         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
107       return true;
108     }
109     return false;
110   }
111
112   if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
113     // If we are switching on a constant, we can convert the switch into a
114     // single branch instruction!
115     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
116     BasicBlock *TheOnlyDest = SI->getDefaultDest();
117     BasicBlock *DefaultDest = TheOnlyDest;
118
119     // Figure out which case it goes to.
120     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
121          i != e; ++i) {
122       // Found case matching a constant operand?
123       if (i.getCaseValue() == CI) {
124         TheOnlyDest = i.getCaseSuccessor();
125         break;
126       }
127
128       // Check to see if this branch is going to the same place as the default
129       // dest.  If so, eliminate it as an explicit compare.
130       if (i.getCaseSuccessor() == DefaultDest) {
131         MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
132         unsigned NCases = SI->getNumCases();
133         // Fold the case metadata into the default if there will be any branches
134         // left, unless the metadata doesn't match the switch.
135         if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
136           // Collect branch weights into a vector.
137           SmallVector<uint32_t, 8> Weights;
138           for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
139                ++MD_i) {
140             ConstantInt *CI =
141                 mdconst::dyn_extract<ConstantInt>(MD->getOperand(MD_i));
142             assert(CI);
143             Weights.push_back(CI->getValue().getZExtValue());
144           }
145           // Merge weight of this case to the default weight.
146           unsigned idx = i.getCaseIndex();
147           Weights[0] += Weights[idx+1];
148           // Remove weight for this case.
149           std::swap(Weights[idx+1], Weights.back());
150           Weights.pop_back();
151           SI->setMetadata(LLVMContext::MD_prof,
152                           MDBuilder(BB->getContext()).
153                           createBranchWeights(Weights));
154         }
155         // Remove this entry.
156         DefaultDest->removePredecessor(SI->getParent());
157         SI->removeCase(i);
158         --i; --e;
159         continue;
160       }
161
162       // Otherwise, check to see if the switch only branches to one destination.
163       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
164       // destinations.
165       if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
166     }
167
168     if (CI && !TheOnlyDest) {
169       // Branching on a constant, but not any of the cases, go to the default
170       // successor.
171       TheOnlyDest = SI->getDefaultDest();
172     }
173
174     // If we found a single destination that we can fold the switch into, do so
175     // now.
176     if (TheOnlyDest) {
177       // Insert the new branch.
178       Builder.CreateBr(TheOnlyDest);
179       BasicBlock *BB = SI->getParent();
180
181       // Remove entries from PHI nodes which we no longer branch to...
182       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
183         // Found case matching a constant operand?
184         BasicBlock *Succ = SI->getSuccessor(i);
185         if (Succ == TheOnlyDest)
186           TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
187         else
188           Succ->removePredecessor(BB);
189       }
190
191       // Delete the old switch.
192       Value *Cond = SI->getCondition();
193       SI->eraseFromParent();
194       if (DeleteDeadConditions)
195         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
196       return true;
197     }
198
199     if (SI->getNumCases() == 1) {
200       // Otherwise, we can fold this switch into a conditional branch
201       // instruction if it has only one non-default destination.
202       SwitchInst::CaseIt FirstCase = SI->case_begin();
203       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
204           FirstCase.getCaseValue(), "cond");
205
206       // Insert the new branch.
207       BranchInst *NewBr = Builder.CreateCondBr(Cond,
208                                                FirstCase.getCaseSuccessor(),
209                                                SI->getDefaultDest());
210       MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
211       if (MD && MD->getNumOperands() == 3) {
212         ConstantInt *SICase =
213             mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
214         ConstantInt *SIDef =
215             mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
216         assert(SICase && SIDef);
217         // The TrueWeight should be the weight for the single case of SI.
218         NewBr->setMetadata(LLVMContext::MD_prof,
219                         MDBuilder(BB->getContext()).
220                         createBranchWeights(SICase->getValue().getZExtValue(),
221                                             SIDef->getValue().getZExtValue()));
222       }
223
224       // Delete the old switch.
225       SI->eraseFromParent();
226       return true;
227     }
228     return false;
229   }
230
231   if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
232     // indirectbr blockaddress(@F, @BB) -> br label @BB
233     if (BlockAddress *BA =
234           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
235       BasicBlock *TheOnlyDest = BA->getBasicBlock();
236       // Insert the new branch.
237       Builder.CreateBr(TheOnlyDest);
238
239       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
240         if (IBI->getDestination(i) == TheOnlyDest)
241           TheOnlyDest = nullptr;
242         else
243           IBI->getDestination(i)->removePredecessor(IBI->getParent());
244       }
245       Value *Address = IBI->getAddress();
246       IBI->eraseFromParent();
247       if (DeleteDeadConditions)
248         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
249
250       // If we didn't find our destination in the IBI successor list, then we
251       // have undefined behavior.  Replace the unconditional branch with an
252       // 'unreachable' instruction.
253       if (TheOnlyDest) {
254         BB->getTerminator()->eraseFromParent();
255         new UnreachableInst(BB->getContext(), BB);
256       }
257
258       return true;
259     }
260   }
261
262   return false;
263 }
264
265
266 //===----------------------------------------------------------------------===//
267 //  Local dead code elimination.
268 //
269
270 /// isInstructionTriviallyDead - Return true if the result produced by the
271 /// instruction is not used, and the instruction has no side effects.
272 ///
273 bool llvm::isInstructionTriviallyDead(Instruction *I,
274                                       const TargetLibraryInfo *TLI) {
275   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
276
277   // We don't want the landingpad instruction removed by anything this general.
278   if (isa<LandingPadInst>(I))
279     return false;
280
281   // We don't want debug info removed by anything this general, unless
282   // debug info is empty.
283   if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
284     if (DDI->getAddress())
285       return false;
286     return true;
287   }
288   if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
289     if (DVI->getValue())
290       return false;
291     return true;
292   }
293
294   if (!I->mayHaveSideEffects()) return true;
295
296   // Special case intrinsics that "may have side effects" but can be deleted
297   // when dead.
298   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
299     // Safe to delete llvm.stacksave if dead.
300     if (II->getIntrinsicID() == Intrinsic::stacksave)
301       return true;
302
303     // Lifetime intrinsics are dead when their right-hand is undef.
304     if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
305         II->getIntrinsicID() == Intrinsic::lifetime_end)
306       return isa<UndefValue>(II->getArgOperand(1));
307
308     // Assumptions are dead if their condition is trivially true.
309     if (II->getIntrinsicID() == Intrinsic::assume) {
310       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
311         return !Cond->isZero();
312
313       return false;
314     }
315   }
316
317   if (isAllocLikeFn(I, TLI)) return true;
318
319   if (CallInst *CI = isFreeCall(I, TLI))
320     if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
321       return C->isNullValue() || isa<UndefValue>(C);
322
323   return false;
324 }
325
326 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
327 /// trivially dead instruction, delete it.  If that makes any of its operands
328 /// trivially dead, delete them too, recursively.  Return true if any
329 /// instructions were deleted.
330 bool
331 llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
332                                                  const TargetLibraryInfo *TLI) {
333   Instruction *I = dyn_cast<Instruction>(V);
334   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
335     return false;
336
337   SmallVector<Instruction*, 16> DeadInsts;
338   DeadInsts.push_back(I);
339
340   do {
341     I = DeadInsts.pop_back_val();
342
343     // Null out all of the instruction's operands to see if any operand becomes
344     // dead as we go.
345     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
346       Value *OpV = I->getOperand(i);
347       I->setOperand(i, nullptr);
348
349       if (!OpV->use_empty()) continue;
350
351       // If the operand is an instruction that became dead as we nulled out the
352       // operand, and if it is 'trivially' dead, delete it in a future loop
353       // iteration.
354       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
355         if (isInstructionTriviallyDead(OpI, TLI))
356           DeadInsts.push_back(OpI);
357     }
358
359     I->eraseFromParent();
360   } while (!DeadInsts.empty());
361
362   return true;
363 }
364
365 /// areAllUsesEqual - Check whether the uses of a value are all the same.
366 /// This is similar to Instruction::hasOneUse() except this will also return
367 /// true when there are no uses or multiple uses that all refer to the same
368 /// value.
369 static bool areAllUsesEqual(Instruction *I) {
370   Value::user_iterator UI = I->user_begin();
371   Value::user_iterator UE = I->user_end();
372   if (UI == UE)
373     return true;
374
375   User *TheUse = *UI;
376   for (++UI; UI != UE; ++UI) {
377     if (*UI != TheUse)
378       return false;
379   }
380   return true;
381 }
382
383 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
384 /// dead PHI node, due to being a def-use chain of single-use nodes that
385 /// either forms a cycle or is terminated by a trivially dead instruction,
386 /// delete it.  If that makes any of its operands trivially dead, delete them
387 /// too, recursively.  Return true if a change was made.
388 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
389                                         const TargetLibraryInfo *TLI) {
390   SmallPtrSet<Instruction*, 4> Visited;
391   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
392        I = cast<Instruction>(*I->user_begin())) {
393     if (I->use_empty())
394       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
395
396     // If we find an instruction more than once, we're on a cycle that
397     // won't prove fruitful.
398     if (!Visited.insert(I).second) {
399       // Break the cycle and delete the instruction and its operands.
400       I->replaceAllUsesWith(UndefValue::get(I->getType()));
401       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
402       return true;
403     }
404   }
405   return false;
406 }
407
408 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
409 /// simplify any instructions in it and recursively delete dead instructions.
410 ///
411 /// This returns true if it changed the code, note that it can delete
412 /// instructions in other blocks as well in this block.
413 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD,
414                                        const TargetLibraryInfo *TLI) {
415   bool MadeChange = false;
416
417 #ifndef NDEBUG
418   // In debug builds, ensure that the terminator of the block is never replaced
419   // or deleted by these simplifications. The idea of simplification is that it
420   // cannot introduce new instructions, and there is no way to replace the
421   // terminator of a block without introducing a new instruction.
422   AssertingVH<Instruction> TerminatorVH(--BB->end());
423 #endif
424
425   for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
426     assert(!BI->isTerminator());
427     Instruction *Inst = BI++;
428
429     WeakVH BIHandle(BI);
430     if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
431       MadeChange = true;
432       if (BIHandle != BI)
433         BI = BB->begin();
434       continue;
435     }
436
437     MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
438     if (BIHandle != BI)
439       BI = BB->begin();
440   }
441   return MadeChange;
442 }
443
444 //===----------------------------------------------------------------------===//
445 //  Control Flow Graph Restructuring.
446 //
447
448
449 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
450 /// method is called when we're about to delete Pred as a predecessor of BB.  If
451 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
452 ///
453 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
454 /// nodes that collapse into identity values.  For example, if we have:
455 ///   x = phi(1, 0, 0, 0)
456 ///   y = and x, z
457 ///
458 /// .. and delete the predecessor corresponding to the '1', this will attempt to
459 /// recursively fold the and to 0.
460 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
461                                         DataLayout *TD) {
462   // This only adjusts blocks with PHI nodes.
463   if (!isa<PHINode>(BB->begin()))
464     return;
465
466   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
467   // them down.  This will leave us with single entry phi nodes and other phis
468   // that can be removed.
469   BB->removePredecessor(Pred, true);
470
471   WeakVH PhiIt = &BB->front();
472   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
473     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
474     Value *OldPhiIt = PhiIt;
475
476     if (!recursivelySimplifyInstruction(PN, TD))
477       continue;
478
479     // If recursive simplification ended up deleting the next PHI node we would
480     // iterate to, then our iterator is invalid, restart scanning from the top
481     // of the block.
482     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
483   }
484 }
485
486
487 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
488 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
489 /// between them, moving the instructions in the predecessor into DestBB and
490 /// deleting the predecessor block.
491 ///
492 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
493   // If BB has single-entry PHI nodes, fold them.
494   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
495     Value *NewVal = PN->getIncomingValue(0);
496     // Replace self referencing PHI with undef, it must be dead.
497     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
498     PN->replaceAllUsesWith(NewVal);
499     PN->eraseFromParent();
500   }
501
502   BasicBlock *PredBB = DestBB->getSinglePredecessor();
503   assert(PredBB && "Block doesn't have a single predecessor!");
504
505   // Zap anything that took the address of DestBB.  Not doing this will give the
506   // address an invalid value.
507   if (DestBB->hasAddressTaken()) {
508     BlockAddress *BA = BlockAddress::get(DestBB);
509     Constant *Replacement =
510       ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
511     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
512                                                      BA->getType()));
513     BA->destroyConstant();
514   }
515
516   // Anything that branched to PredBB now branches to DestBB.
517   PredBB->replaceAllUsesWith(DestBB);
518
519   // Splice all the instructions from PredBB to DestBB.
520   PredBB->getTerminator()->eraseFromParent();
521   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
522
523   // If the PredBB is the entry block of the function, move DestBB up to
524   // become the entry block after we erase PredBB.
525   if (PredBB == &DestBB->getParent()->getEntryBlock())
526     DestBB->moveAfter(PredBB);
527
528   if (DT) {
529     BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
530     DT->changeImmediateDominator(DestBB, PredBBIDom);
531     DT->eraseNode(PredBB);
532   }
533   // Nuke BB.
534   PredBB->eraseFromParent();
535 }
536
537 /// CanMergeValues - Return true if we can choose one of these values to use
538 /// in place of the other. Note that we will always choose the non-undef
539 /// value to keep.
540 static bool CanMergeValues(Value *First, Value *Second) {
541   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
542 }
543
544 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
545 /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
546 ///
547 /// Assumption: Succ is the single successor for BB.
548 ///
549 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
550   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
551
552   DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
553         << Succ->getName() << "\n");
554   // Shortcut, if there is only a single predecessor it must be BB and merging
555   // is always safe
556   if (Succ->getSinglePredecessor()) return true;
557
558   // Make a list of the predecessors of BB
559   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
560
561   // Look at all the phi nodes in Succ, to see if they present a conflict when
562   // merging these blocks
563   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
564     PHINode *PN = cast<PHINode>(I);
565
566     // If the incoming value from BB is again a PHINode in
567     // BB which has the same incoming value for *PI as PN does, we can
568     // merge the phi nodes and then the blocks can still be merged
569     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
570     if (BBPN && BBPN->getParent() == BB) {
571       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
572         BasicBlock *IBB = PN->getIncomingBlock(PI);
573         if (BBPreds.count(IBB) &&
574             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
575                             PN->getIncomingValue(PI))) {
576           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
577                 << Succ->getName() << " is conflicting with "
578                 << BBPN->getName() << " with regard to common predecessor "
579                 << IBB->getName() << "\n");
580           return false;
581         }
582       }
583     } else {
584       Value* Val = PN->getIncomingValueForBlock(BB);
585       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
586         // See if the incoming value for the common predecessor is equal to the
587         // one for BB, in which case this phi node will not prevent the merging
588         // of the block.
589         BasicBlock *IBB = PN->getIncomingBlock(PI);
590         if (BBPreds.count(IBB) &&
591             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
592           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
593                 << Succ->getName() << " is conflicting with regard to common "
594                 << "predecessor " << IBB->getName() << "\n");
595           return false;
596         }
597       }
598     }
599   }
600
601   return true;
602 }
603
604 typedef SmallVector<BasicBlock *, 16> PredBlockVector;
605 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
606
607 /// \brief Determines the value to use as the phi node input for a block.
608 ///
609 /// Select between \p OldVal any value that we know flows from \p BB
610 /// to a particular phi on the basis of which one (if either) is not
611 /// undef. Update IncomingValues based on the selected value.
612 ///
613 /// \param OldVal The value we are considering selecting.
614 /// \param BB The block that the value flows in from.
615 /// \param IncomingValues A map from block-to-value for other phi inputs
616 /// that we have examined.
617 ///
618 /// \returns the selected value.
619 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
620                                           IncomingValueMap &IncomingValues) {
621   if (!isa<UndefValue>(OldVal)) {
622     assert((!IncomingValues.count(BB) ||
623             IncomingValues.find(BB)->second == OldVal) &&
624            "Expected OldVal to match incoming value from BB!");
625
626     IncomingValues.insert(std::make_pair(BB, OldVal));
627     return OldVal;
628   }
629
630   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
631   if (It != IncomingValues.end()) return It->second;
632
633   return OldVal;
634 }
635
636 /// \brief Create a map from block to value for the operands of a
637 /// given phi.
638 ///
639 /// Create a map from block to value for each non-undef value flowing
640 /// into \p PN.
641 ///
642 /// \param PN The phi we are collecting the map for.
643 /// \param IncomingValues [out] The map from block to value for this phi.
644 static void gatherIncomingValuesToPhi(PHINode *PN,
645                                       IncomingValueMap &IncomingValues) {
646   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
647     BasicBlock *BB = PN->getIncomingBlock(i);
648     Value *V = PN->getIncomingValue(i);
649
650     if (!isa<UndefValue>(V))
651       IncomingValues.insert(std::make_pair(BB, V));
652   }
653 }
654
655 /// \brief Replace the incoming undef values to a phi with the values
656 /// from a block-to-value map.
657 ///
658 /// \param PN The phi we are replacing the undefs in.
659 /// \param IncomingValues A map from block to value.
660 static void replaceUndefValuesInPhi(PHINode *PN,
661                                     const IncomingValueMap &IncomingValues) {
662   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
663     Value *V = PN->getIncomingValue(i);
664
665     if (!isa<UndefValue>(V)) continue;
666
667     BasicBlock *BB = PN->getIncomingBlock(i);
668     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
669     if (It == IncomingValues.end()) continue;
670
671     PN->setIncomingValue(i, It->second);
672   }
673 }
674
675 /// \brief Replace a value flowing from a block to a phi with
676 /// potentially multiple instances of that value flowing from the
677 /// block's predecessors to the phi.
678 ///
679 /// \param BB The block with the value flowing into the phi.
680 /// \param BBPreds The predecessors of BB.
681 /// \param PN The phi that we are updating.
682 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
683                                                 const PredBlockVector &BBPreds,
684                                                 PHINode *PN) {
685   Value *OldVal = PN->removeIncomingValue(BB, false);
686   assert(OldVal && "No entry in PHI for Pred BB!");
687
688   IncomingValueMap IncomingValues;
689
690   // We are merging two blocks - BB, and the block containing PN - and
691   // as a result we need to redirect edges from the predecessors of BB
692   // to go to the block containing PN, and update PN
693   // accordingly. Since we allow merging blocks in the case where the
694   // predecessor and successor blocks both share some predecessors,
695   // and where some of those common predecessors might have undef
696   // values flowing into PN, we want to rewrite those values to be
697   // consistent with the non-undef values.
698
699   gatherIncomingValuesToPhi(PN, IncomingValues);
700
701   // If this incoming value is one of the PHI nodes in BB, the new entries
702   // in the PHI node are the entries from the old PHI.
703   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
704     PHINode *OldValPN = cast<PHINode>(OldVal);
705     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
706       // Note that, since we are merging phi nodes and BB and Succ might
707       // have common predecessors, we could end up with a phi node with
708       // identical incoming branches. This will be cleaned up later (and
709       // will trigger asserts if we try to clean it up now, without also
710       // simplifying the corresponding conditional branch).
711       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
712       Value *PredVal = OldValPN->getIncomingValue(i);
713       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
714                                                     IncomingValues);
715
716       // And add a new incoming value for this predecessor for the
717       // newly retargeted branch.
718       PN->addIncoming(Selected, PredBB);
719     }
720   } else {
721     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
722       // Update existing incoming values in PN for this
723       // predecessor of BB.
724       BasicBlock *PredBB = BBPreds[i];
725       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
726                                                     IncomingValues);
727
728       // And add a new incoming value for this predecessor for the
729       // newly retargeted branch.
730       PN->addIncoming(Selected, PredBB);
731     }
732   }
733
734   replaceUndefValuesInPhi(PN, IncomingValues);
735 }
736
737 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
738 /// unconditional branch, and contains no instructions other than PHI nodes,
739 /// potential side-effect free intrinsics and the branch.  If possible,
740 /// eliminate BB by rewriting all the predecessors to branch to the successor
741 /// block and return true.  If we can't transform, return false.
742 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
743   assert(BB != &BB->getParent()->getEntryBlock() &&
744          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
745
746   // We can't eliminate infinite loops.
747   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
748   if (BB == Succ) return false;
749
750   // Check to see if merging these blocks would cause conflicts for any of the
751   // phi nodes in BB or Succ. If not, we can safely merge.
752   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
753
754   // Check for cases where Succ has multiple predecessors and a PHI node in BB
755   // has uses which will not disappear when the PHI nodes are merged.  It is
756   // possible to handle such cases, but difficult: it requires checking whether
757   // BB dominates Succ, which is non-trivial to calculate in the case where
758   // Succ has multiple predecessors.  Also, it requires checking whether
759   // constructing the necessary self-referential PHI node doesn't introduce any
760   // conflicts; this isn't too difficult, but the previous code for doing this
761   // was incorrect.
762   //
763   // Note that if this check finds a live use, BB dominates Succ, so BB is
764   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
765   // folding the branch isn't profitable in that case anyway.
766   if (!Succ->getSinglePredecessor()) {
767     BasicBlock::iterator BBI = BB->begin();
768     while (isa<PHINode>(*BBI)) {
769       for (Use &U : BBI->uses()) {
770         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
771           if (PN->getIncomingBlock(U) != BB)
772             return false;
773         } else {
774           return false;
775         }
776       }
777       ++BBI;
778     }
779   }
780
781   DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
782
783   if (isa<PHINode>(Succ->begin())) {
784     // If there is more than one pred of succ, and there are PHI nodes in
785     // the successor, then we need to add incoming edges for the PHI nodes
786     //
787     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
788
789     // Loop over all of the PHI nodes in the successor of BB.
790     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
791       PHINode *PN = cast<PHINode>(I);
792
793       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
794     }
795   }
796
797   if (Succ->getSinglePredecessor()) {
798     // BB is the only predecessor of Succ, so Succ will end up with exactly
799     // the same predecessors BB had.
800
801     // Copy over any phi, debug or lifetime instruction.
802     BB->getTerminator()->eraseFromParent();
803     Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
804   } else {
805     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
806       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
807       assert(PN->use_empty() && "There shouldn't be any uses here!");
808       PN->eraseFromParent();
809     }
810   }
811
812   // Everything that jumped to BB now goes to Succ.
813   BB->replaceAllUsesWith(Succ);
814   if (!Succ->hasName()) Succ->takeName(BB);
815   BB->eraseFromParent();              // Delete the old basic block.
816   return true;
817 }
818
819 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
820 /// nodes in this block. This doesn't try to be clever about PHI nodes
821 /// which differ only in the order of the incoming values, but instcombine
822 /// orders them so it usually won't matter.
823 ///
824 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
825   bool Changed = false;
826
827   // This implementation doesn't currently consider undef operands
828   // specially. Theoretically, two phis which are identical except for
829   // one having an undef where the other doesn't could be collapsed.
830
831   // Map from PHI hash values to PHI nodes. If multiple PHIs have
832   // the same hash value, the element is the first PHI in the
833   // linked list in CollisionMap.
834   DenseMap<uintptr_t, PHINode *> HashMap;
835
836   // Maintain linked lists of PHI nodes with common hash values.
837   DenseMap<PHINode *, PHINode *> CollisionMap;
838
839   // Examine each PHI.
840   for (BasicBlock::iterator I = BB->begin();
841        PHINode *PN = dyn_cast<PHINode>(I++); ) {
842     // Compute a hash value on the operands. Instcombine will likely have sorted
843     // them, which helps expose duplicates, but we have to check all the
844     // operands to be safe in case instcombine hasn't run.
845     uintptr_t Hash = 0;
846     // This hash algorithm is quite weak as hash functions go, but it seems
847     // to do a good enough job for this particular purpose, and is very quick.
848     for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
849       Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
850       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
851     }
852     for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
853          I != E; ++I) {
854       Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
855       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
856     }
857     // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
858     Hash >>= 1;
859     // If we've never seen this hash value before, it's a unique PHI.
860     std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
861       HashMap.insert(std::make_pair(Hash, PN));
862     if (Pair.second) continue;
863     // Otherwise it's either a duplicate or a hash collision.
864     for (PHINode *OtherPN = Pair.first->second; ; ) {
865       if (OtherPN->isIdenticalTo(PN)) {
866         // A duplicate. Replace this PHI with its duplicate.
867         PN->replaceAllUsesWith(OtherPN);
868         PN->eraseFromParent();
869         Changed = true;
870         break;
871       }
872       // A non-duplicate hash collision.
873       DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
874       if (I == CollisionMap.end()) {
875         // Set this PHI to be the head of the linked list of colliding PHIs.
876         PHINode *Old = Pair.first->second;
877         Pair.first->second = PN;
878         CollisionMap[PN] = Old;
879         break;
880       }
881       // Proceed to the next PHI in the list.
882       OtherPN = I->second;
883     }
884   }
885
886   return Changed;
887 }
888
889 /// enforceKnownAlignment - If the specified pointer points to an object that
890 /// we control, modify the object's alignment to PrefAlign. This isn't
891 /// often possible though. If alignment is important, a more reliable approach
892 /// is to simply align all global variables and allocation instructions to
893 /// their preferred alignment from the beginning.
894 ///
895 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
896                                       unsigned PrefAlign, const DataLayout *TD) {
897   V = V->stripPointerCasts();
898
899   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
900     // If the preferred alignment is greater than the natural stack alignment
901     // then don't round up. This avoids dynamic stack realignment.
902     if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
903       return Align;
904     // If there is a requested alignment and if this is an alloca, round up.
905     if (AI->getAlignment() >= PrefAlign)
906       return AI->getAlignment();
907     AI->setAlignment(PrefAlign);
908     return PrefAlign;
909   }
910
911   if (auto *GO = dyn_cast<GlobalObject>(V)) {
912     // If there is a large requested alignment and we can, bump up the alignment
913     // of the global.
914     if (GO->isDeclaration())
915       return Align;
916     // If the memory we set aside for the global may not be the memory used by
917     // the final program then it is impossible for us to reliably enforce the
918     // preferred alignment.
919     if (GO->isWeakForLinker())
920       return Align;
921
922     if (GO->getAlignment() >= PrefAlign)
923       return GO->getAlignment();
924     // We can only increase the alignment of the global if it has no alignment
925     // specified or if it is not assigned a section.  If it is assigned a
926     // section, the global could be densely packed with other objects in the
927     // section, increasing the alignment could cause padding issues.
928     if (!GO->hasSection() || GO->getAlignment() == 0)
929       GO->setAlignment(PrefAlign);
930     return GO->getAlignment();
931   }
932
933   return Align;
934 }
935
936 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
937 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
938 /// and it is more than the alignment of the ultimate object, see if we can
939 /// increase the alignment of the ultimate object, making this check succeed.
940 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
941                                           const DataLayout *DL,
942                                           AssumptionCache *AC,
943                                           const Instruction *CxtI,
944                                           const DominatorTree *DT) {
945   assert(V->getType()->isPointerTy() &&
946          "getOrEnforceKnownAlignment expects a pointer!");
947   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(V->getType()) : 64;
948
949   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
950   computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
951   unsigned TrailZ = KnownZero.countTrailingOnes();
952
953   // Avoid trouble with ridiculously large TrailZ values, such as
954   // those computed from a null pointer.
955   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
956
957   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
958
959   // LLVM doesn't support alignments larger than this currently.
960   Align = std::min(Align, +Value::MaximumAlignment);
961
962   if (PrefAlign > Align)
963     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
964
965   // We don't need to make any adjustment.
966   return Align;
967 }
968
969 ///===---------------------------------------------------------------------===//
970 ///  Dbg Intrinsic utilities
971 ///
972
973 /// See if there is a dbg.value intrinsic for DIVar before I.
974 static bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
975   // Since we can't guarantee that the original dbg.declare instrinsic
976   // is removed by LowerDbgDeclare(), we need to make sure that we are
977   // not inserting the same dbg.value intrinsic over and over.
978   llvm::BasicBlock::InstListType::iterator PrevI(I);
979   if (PrevI != I->getParent()->getInstList().begin()) {
980     --PrevI;
981     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
982       if (DVI->getValue() == I->getOperand(0) &&
983           DVI->getOffset() == 0 &&
984           DVI->getVariable() == DIVar)
985         return true;
986   }
987   return false;
988 }
989
990 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
991 /// that has an associated llvm.dbg.decl intrinsic.
992 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
993                                            StoreInst *SI, DIBuilder &Builder) {
994   DIVariable DIVar(DDI->getVariable());
995   DIExpression DIExpr(DDI->getExpression());
996   assert((!DIVar || DIVar.isVariable()) &&
997          "Variable in DbgDeclareInst should be either null or a DIVariable.");
998   if (!DIVar)
999     return false;
1000
1001   if (LdStHasDebugValue(DIVar, SI))
1002     return true;
1003
1004   Instruction *DbgVal = nullptr;
1005   // If an argument is zero extended then use argument directly. The ZExt
1006   // may be zapped by an optimization pass in future.
1007   Argument *ExtendedArg = nullptr;
1008   if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1009     ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1010   if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1011     ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1012   if (ExtendedArg)
1013     DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, DIExpr, SI);
1014   else
1015     DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar,
1016                                              DIExpr, SI);
1017   DbgVal->setDebugLoc(DDI->getDebugLoc());
1018   return true;
1019 }
1020
1021 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1022 /// that has an associated llvm.dbg.decl intrinsic.
1023 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1024                                            LoadInst *LI, DIBuilder &Builder) {
1025   DIVariable DIVar(DDI->getVariable());
1026   DIExpression DIExpr(DDI->getExpression());
1027   assert((!DIVar || DIVar.isVariable()) &&
1028          "Variable in DbgDeclareInst should be either null or a DIVariable.");
1029   if (!DIVar)
1030     return false;
1031
1032   if (LdStHasDebugValue(DIVar, LI))
1033     return true;
1034
1035   Instruction *DbgVal =
1036       Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0, DIVar, DIExpr, LI);
1037   DbgVal->setDebugLoc(DDI->getDebugLoc());
1038   return true;
1039 }
1040
1041 /// Determine whether this alloca is either a VLA or an array.
1042 static bool isArray(AllocaInst *AI) {
1043   return AI->isArrayAllocation() ||
1044     AI->getType()->getElementType()->isArrayTy();
1045 }
1046
1047 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1048 /// of llvm.dbg.value intrinsics.
1049 bool llvm::LowerDbgDeclare(Function &F) {
1050   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1051   SmallVector<DbgDeclareInst *, 4> Dbgs;
1052   for (auto &FI : F)
1053     for (BasicBlock::iterator BI : FI)
1054       if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
1055         Dbgs.push_back(DDI);
1056
1057   if (Dbgs.empty())
1058     return false;
1059
1060   for (auto &I : Dbgs) {
1061     DbgDeclareInst *DDI = I;
1062     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1063     // If this is an alloca for a scalar variable, insert a dbg.value
1064     // at each load and store to the alloca and erase the dbg.declare.
1065     // The dbg.values allow tracking a variable even if it is not
1066     // stored on the stack, while the dbg.declare can only describe
1067     // the stack slot (and at a lexical-scope granularity). Later
1068     // passes will attempt to elide the stack slot.
1069     if (AI && !isArray(AI)) {
1070       for (User *U : AI->users())
1071         if (StoreInst *SI = dyn_cast<StoreInst>(U))
1072           ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1073         else if (LoadInst *LI = dyn_cast<LoadInst>(U))
1074           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1075         else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1076           // This is a call by-value or some other instruction that
1077           // takes a pointer to the variable. Insert a *value*
1078           // intrinsic that describes the alloca.
1079           auto DbgVal = DIB.insertDbgValueIntrinsic(
1080               AI, 0, DIVariable(DDI->getVariable()),
1081               DIExpression(DDI->getExpression()), CI);
1082           DbgVal->setDebugLoc(DDI->getDebugLoc());
1083         }
1084       DDI->eraseFromParent();
1085     }
1086   }
1087   return true;
1088 }
1089
1090 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1091 /// alloca 'V', if any.
1092 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
1093   if (auto *L = LocalAsMetadata::getIfExists(V))
1094     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1095       for (User *U : MDV->users())
1096         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1097           return DDI;
1098
1099   return nullptr;
1100 }
1101
1102 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1103                                       DIBuilder &Builder) {
1104   DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
1105   if (!DDI)
1106     return false;
1107   DIVariable DIVar(DDI->getVariable());
1108   DIExpression DIExpr(DDI->getExpression());
1109   assert((!DIVar || DIVar.isVariable()) &&
1110          "Variable in DbgDeclareInst should be either null or a DIVariable.");
1111   if (!DIVar)
1112     return false;
1113
1114   // Create a copy of the original DIDescriptor for user variable, prepending
1115   // "deref" operation to a list of address elements, as new llvm.dbg.declare
1116   // will take a value storing address of the memory for variable, not
1117   // alloca itself.
1118   SmallVector<int64_t, 4> NewDIExpr;
1119   NewDIExpr.push_back(dwarf::DW_OP_deref);
1120   if (DIExpr)
1121     for (unsigned i = 0, n = DIExpr.getNumElements(); i < n; ++i)
1122       NewDIExpr.push_back(DIExpr.getElement(i));
1123
1124   // Insert llvm.dbg.declare in the same basic block as the original alloca,
1125   // and remove old llvm.dbg.declare.
1126   BasicBlock *BB = AI->getParent();
1127   Builder.insertDeclare(NewAllocaAddress, DIVar,
1128                         Builder.createExpression(NewDIExpr), BB);
1129   DDI->eraseFromParent();
1130   return true;
1131 }
1132
1133 /// changeToUnreachable - Insert an unreachable instruction before the specified
1134 /// instruction, making it and the rest of the code in the block dead.
1135 static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
1136   BasicBlock *BB = I->getParent();
1137   // Loop over all of the successors, removing BB's entry from any PHI
1138   // nodes.
1139   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
1140     (*SI)->removePredecessor(BB);
1141
1142   // Insert a call to llvm.trap right before this.  This turns the undefined
1143   // behavior into a hard fail instead of falling through into random code.
1144   if (UseLLVMTrap) {
1145     Function *TrapFn =
1146       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1147     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1148     CallTrap->setDebugLoc(I->getDebugLoc());
1149   }
1150   new UnreachableInst(I->getContext(), I);
1151
1152   // All instructions after this are dead.
1153   BasicBlock::iterator BBI = I, BBE = BB->end();
1154   while (BBI != BBE) {
1155     if (!BBI->use_empty())
1156       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1157     BB->getInstList().erase(BBI++);
1158   }
1159 }
1160
1161 /// changeToCall - Convert the specified invoke into a normal call.
1162 static void changeToCall(InvokeInst *II) {
1163   SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
1164   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
1165   NewCall->takeName(II);
1166   NewCall->setCallingConv(II->getCallingConv());
1167   NewCall->setAttributes(II->getAttributes());
1168   NewCall->setDebugLoc(II->getDebugLoc());
1169   II->replaceAllUsesWith(NewCall);
1170
1171   // Follow the call by a branch to the normal destination.
1172   BranchInst::Create(II->getNormalDest(), II);
1173
1174   // Update PHI nodes in the unwind destination
1175   II->getUnwindDest()->removePredecessor(II->getParent());
1176   II->eraseFromParent();
1177 }
1178
1179 static bool markAliveBlocks(BasicBlock *BB,
1180                             SmallPtrSetImpl<BasicBlock*> &Reachable) {
1181
1182   SmallVector<BasicBlock*, 128> Worklist;
1183   Worklist.push_back(BB);
1184   Reachable.insert(BB);
1185   bool Changed = false;
1186   do {
1187     BB = Worklist.pop_back_val();
1188
1189     // Do a quick scan of the basic block, turning any obviously unreachable
1190     // instructions into LLVM unreachable insts.  The instruction combining pass
1191     // canonicalizes unreachable insts into stores to null or undef.
1192     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
1193       // Assumptions that are known to be false are equivalent to unreachable.
1194       // Also, if the condition is undefined, then we make the choice most
1195       // beneficial to the optimizer, and choose that to also be unreachable.
1196       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
1197         if (II->getIntrinsicID() == Intrinsic::assume) {
1198           bool MakeUnreachable = false;
1199           if (isa<UndefValue>(II->getArgOperand(0)))
1200             MakeUnreachable = true;
1201           else if (ConstantInt *Cond =
1202                    dyn_cast<ConstantInt>(II->getArgOperand(0)))
1203             MakeUnreachable = Cond->isZero();
1204
1205           if (MakeUnreachable) {
1206             // Don't insert a call to llvm.trap right before the unreachable.
1207             changeToUnreachable(BBI, false);
1208             Changed = true;
1209             break;
1210           }
1211         }
1212
1213       if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
1214         if (CI->doesNotReturn()) {
1215           // If we found a call to a no-return function, insert an unreachable
1216           // instruction after it.  Make sure there isn't *already* one there
1217           // though.
1218           ++BBI;
1219           if (!isa<UnreachableInst>(BBI)) {
1220             // Don't insert a call to llvm.trap right before the unreachable.
1221             changeToUnreachable(BBI, false);
1222             Changed = true;
1223           }
1224           break;
1225         }
1226       }
1227
1228       // Store to undef and store to null are undefined and used to signal that
1229       // they should be changed to unreachable by passes that can't modify the
1230       // CFG.
1231       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
1232         // Don't touch volatile stores.
1233         if (SI->isVolatile()) continue;
1234
1235         Value *Ptr = SI->getOperand(1);
1236
1237         if (isa<UndefValue>(Ptr) ||
1238             (isa<ConstantPointerNull>(Ptr) &&
1239              SI->getPointerAddressSpace() == 0)) {
1240           changeToUnreachable(SI, true);
1241           Changed = true;
1242           break;
1243         }
1244       }
1245     }
1246
1247     // Turn invokes that call 'nounwind' functions into ordinary calls.
1248     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
1249       Value *Callee = II->getCalledValue();
1250       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1251         changeToUnreachable(II, true);
1252         Changed = true;
1253       } else if (II->doesNotThrow()) {
1254         if (II->use_empty() && II->onlyReadsMemory()) {
1255           // jump to the normal destination branch.
1256           BranchInst::Create(II->getNormalDest(), II);
1257           II->getUnwindDest()->removePredecessor(II->getParent());
1258           II->eraseFromParent();
1259         } else
1260           changeToCall(II);
1261         Changed = true;
1262       }
1263     }
1264
1265     Changed |= ConstantFoldTerminator(BB, true);
1266     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
1267       if (Reachable.insert(*SI).second)
1268         Worklist.push_back(*SI);
1269   } while (!Worklist.empty());
1270   return Changed;
1271 }
1272
1273 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
1274 /// if they are in a dead cycle.  Return true if a change was made, false
1275 /// otherwise.
1276 bool llvm::removeUnreachableBlocks(Function &F) {
1277   SmallPtrSet<BasicBlock*, 128> Reachable;
1278   bool Changed = markAliveBlocks(F.begin(), Reachable);
1279
1280   // If there are unreachable blocks in the CFG...
1281   if (Reachable.size() == F.size())
1282     return Changed;
1283
1284   assert(Reachable.size() < F.size());
1285   NumRemoved += F.size()-Reachable.size();
1286
1287   // Loop over all of the basic blocks that are not reachable, dropping all of
1288   // their internal references...
1289   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
1290     if (Reachable.count(BB))
1291       continue;
1292
1293     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
1294       if (Reachable.count(*SI))
1295         (*SI)->removePredecessor(BB);
1296     BB->dropAllReferences();
1297   }
1298
1299   for (Function::iterator I = ++F.begin(); I != F.end();)
1300     if (!Reachable.count(I))
1301       I = F.getBasicBlockList().erase(I);
1302     else
1303       ++I;
1304
1305   return true;
1306 }
1307
1308 void llvm::combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs) {
1309   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
1310   K->dropUnknownMetadata(KnownIDs);
1311   K->getAllMetadataOtherThanDebugLoc(Metadata);
1312   for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
1313     unsigned Kind = Metadata[i].first;
1314     MDNode *JMD = J->getMetadata(Kind);
1315     MDNode *KMD = Metadata[i].second;
1316
1317     switch (Kind) {
1318       default:
1319         K->setMetadata(Kind, nullptr); // Remove unknown metadata
1320         break;
1321       case LLVMContext::MD_dbg:
1322         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1323       case LLVMContext::MD_tbaa:
1324         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
1325         break;
1326       case LLVMContext::MD_alias_scope:
1327       case LLVMContext::MD_noalias:
1328         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
1329         break;
1330       case LLVMContext::MD_range:
1331         K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
1332         break;
1333       case LLVMContext::MD_fpmath:
1334         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
1335         break;
1336       case LLVMContext::MD_invariant_load:
1337         // Only set the !invariant.load if it is present in both instructions.
1338         K->setMetadata(Kind, JMD);
1339         break;
1340       case LLVMContext::MD_nonnull:
1341         // Only set the !nonnull if it is present in both instructions.
1342         K->setMetadata(Kind, JMD);
1343         break;
1344     }
1345   }
1346 }