[ARM] Align stack objects passed to memory intrinsics
[oota-llvm.git] / lib / CodeGen / CodeGenPrepare.cpp
1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
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 pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/Statepoint.h"
37 #include "llvm/IR/ValueHandle.h"
38 #include "llvm/IR/ValueMap.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/BuildLibCalls.h"
47 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
50 using namespace llvm;
51 using namespace llvm::PatternMatch;
52
53 #define DEBUG_TYPE "codegenprepare"
54
55 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
56 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
57 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
58 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
59                       "sunken Cmps");
60 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
61                        "of sunken Casts");
62 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
63                           "computations were sunk");
64 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
65 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
66 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
67 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
68 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
69 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
70 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
71
72 static cl::opt<bool> DisableBranchOpts(
73   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
74   cl::desc("Disable branch optimizations in CodeGenPrepare"));
75
76 static cl::opt<bool>
77     DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
78                   cl::desc("Disable GC optimizations in CodeGenPrepare"));
79
80 static cl::opt<bool> DisableSelectToBranch(
81   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
82   cl::desc("Disable select to branch conversion."));
83
84 static cl::opt<bool> AddrSinkUsingGEPs(
85   "addr-sink-using-gep", cl::Hidden, cl::init(false),
86   cl::desc("Address sinking in CGP using GEPs."));
87
88 static cl::opt<bool> EnableAndCmpSinking(
89    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
90    cl::desc("Enable sinkinig and/cmp into branches."));
91
92 static cl::opt<bool> DisableStoreExtract(
93     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
94     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
95
96 static cl::opt<bool> StressStoreExtract(
97     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
98     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
99
100 static cl::opt<bool> DisableExtLdPromotion(
101     "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102     cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
103              "CodeGenPrepare"));
104
105 static cl::opt<bool> StressExtLdPromotion(
106     "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
107     cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
108              "optimization in CodeGenPrepare"));
109
110 namespace {
111 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
112 struct TypeIsSExt {
113   Type *Ty;
114   bool IsSExt;
115   TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
116 };
117 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
118 class TypePromotionTransaction;
119
120   class CodeGenPrepare : public FunctionPass {
121     /// TLI - Keep a pointer of a TargetLowering to consult for determining
122     /// transformation profitability.
123     const TargetMachine *TM;
124     const TargetLowering *TLI;
125     const TargetTransformInfo *TTI;
126     const TargetLibraryInfo *TLInfo;
127     DominatorTree *DT;
128
129     /// CurInstIterator - As we scan instructions optimizing them, this is the
130     /// next instruction to optimize.  Xforms that can invalidate this should
131     /// update it.
132     BasicBlock::iterator CurInstIterator;
133
134     /// Keeps track of non-local addresses that have been sunk into a block.
135     /// This allows us to avoid inserting duplicate code for blocks with
136     /// multiple load/stores of the same address.
137     ValueMap<Value*, Value*> SunkAddrs;
138
139     /// Keeps track of all truncates inserted for the current function.
140     SetOfInstrs InsertedTruncsSet;
141     /// Keeps track of the type of the related instruction before their
142     /// promotion for the current function.
143     InstrToOrigTy PromotedInsts;
144
145     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
146     /// be updated.
147     bool ModifiedDT;
148
149     /// OptSize - True if optimizing for size.
150     bool OptSize;
151
152   public:
153     static char ID; // Pass identification, replacement for typeid
154     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
155         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
156         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
157       }
158     bool runOnFunction(Function &F) override;
159
160     const char *getPassName() const override { return "CodeGen Prepare"; }
161
162     void getAnalysisUsage(AnalysisUsage &AU) const override {
163       AU.addPreserved<DominatorTreeWrapperPass>();
164       AU.addRequired<TargetLibraryInfoWrapperPass>();
165       AU.addRequired<TargetTransformInfoWrapperPass>();
166     }
167
168   private:
169     bool EliminateFallThrough(Function &F);
170     bool EliminateMostlyEmptyBlocks(Function &F);
171     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
172     void EliminateMostlyEmptyBlock(BasicBlock *BB);
173     bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
174     bool OptimizeInst(Instruction *I, bool& ModifiedDT);
175     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
176     bool OptimizeInlineAsmInst(CallInst *CS);
177     bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
178     bool MoveExtToFormExtLoad(Instruction *&I);
179     bool OptimizeExtUses(Instruction *I);
180     bool OptimizeSelectInst(SelectInst *SI);
181     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
182     bool OptimizeExtractElementInst(Instruction *Inst);
183     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
184     bool PlaceDbgValues(Function &F);
185     bool sinkAndCmp(Function &F);
186     bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
187                         Instruction *&Inst,
188                         const SmallVectorImpl<Instruction *> &Exts,
189                         unsigned CreatedInstCost);
190     bool splitBranchCondition(Function &F);
191     bool simplifyOffsetableRelocate(Instruction &I);
192   };
193 }
194
195 char CodeGenPrepare::ID = 0;
196 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
197                    "Optimize for code generation", false, false)
198
199 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
200   return new CodeGenPrepare(TM);
201 }
202
203 bool CodeGenPrepare::runOnFunction(Function &F) {
204   if (skipOptnoneFunction(F))
205     return false;
206
207   bool EverMadeChange = false;
208   // Clear per function information.
209   InsertedTruncsSet.clear();
210   PromotedInsts.clear();
211
212   ModifiedDT = false;
213   if (TM)
214     TLI = TM->getSubtargetImpl(F)->getTargetLowering();
215   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
216   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
217   DominatorTreeWrapperPass *DTWP =
218       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
219   DT = DTWP ? &DTWP->getDomTree() : nullptr;
220   OptSize = F.hasFnAttribute(Attribute::OptimizeForSize);
221
222   /// This optimization identifies DIV instructions that can be
223   /// profitably bypassed and carried out with a shorter, faster divide.
224   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
225     const DenseMap<unsigned int, unsigned int> &BypassWidths =
226        TLI->getBypassSlowDivWidths();
227     for (Function::iterator I = F.begin(); I != F.end(); I++)
228       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
229   }
230
231   // Eliminate blocks that contain only PHI nodes and an
232   // unconditional branch.
233   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
234
235   // llvm.dbg.value is far away from the value then iSel may not be able
236   // handle it properly. iSel will drop llvm.dbg.value if it can not
237   // find a node corresponding to the value.
238   EverMadeChange |= PlaceDbgValues(F);
239
240   // If there is a mask, compare against zero, and branch that can be combined
241   // into a single target instruction, push the mask and compare into branch
242   // users. Do this before OptimizeBlock -> OptimizeInst ->
243   // OptimizeCmpExpression, which perturbs the pattern being searched for.
244   if (!DisableBranchOpts) {
245     EverMadeChange |= sinkAndCmp(F);
246     EverMadeChange |= splitBranchCondition(F);
247   }
248
249   bool MadeChange = true;
250   while (MadeChange) {
251     MadeChange = false;
252     for (Function::iterator I = F.begin(); I != F.end(); ) {
253       BasicBlock *BB = I++;
254       bool ModifiedDTOnIteration = false;
255       MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
256
257       // Restart BB iteration if the dominator tree of the Function was changed
258       ModifiedDT |= ModifiedDTOnIteration;
259       if (ModifiedDTOnIteration)
260         break;
261     }
262     EverMadeChange |= MadeChange;
263   }
264
265   SunkAddrs.clear();
266
267   if (!DisableBranchOpts) {
268     MadeChange = false;
269     SmallPtrSet<BasicBlock*, 8> WorkList;
270     for (BasicBlock &BB : F) {
271       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
272       MadeChange |= ConstantFoldTerminator(&BB, true);
273       if (!MadeChange) continue;
274
275       for (SmallVectorImpl<BasicBlock*>::iterator
276              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
277         if (pred_begin(*II) == pred_end(*II))
278           WorkList.insert(*II);
279     }
280
281     // Delete the dead blocks and any of their dead successors.
282     MadeChange |= !WorkList.empty();
283     while (!WorkList.empty()) {
284       BasicBlock *BB = *WorkList.begin();
285       WorkList.erase(BB);
286       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
287
288       DeleteDeadBlock(BB);
289
290       for (SmallVectorImpl<BasicBlock*>::iterator
291              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
292         if (pred_begin(*II) == pred_end(*II))
293           WorkList.insert(*II);
294     }
295
296     // Merge pairs of basic blocks with unconditional branches, connected by
297     // a single edge.
298     if (EverMadeChange || MadeChange)
299       MadeChange |= EliminateFallThrough(F);
300
301     if (MadeChange)
302       ModifiedDT = true;
303     EverMadeChange |= MadeChange;
304   }
305
306   if (!DisableGCOpts) {
307     SmallVector<Instruction *, 2> Statepoints;
308     for (BasicBlock &BB : F)
309       for (Instruction &I : BB)
310         if (isStatepoint(I))
311           Statepoints.push_back(&I);
312     for (auto &I : Statepoints)
313       EverMadeChange |= simplifyOffsetableRelocate(*I);
314   }
315
316   if (ModifiedDT && DT)
317     DT->recalculate(F);
318
319   return EverMadeChange;
320 }
321
322 /// EliminateFallThrough - Merge basic blocks which are connected
323 /// by a single edge, where one of the basic blocks has a single successor
324 /// pointing to the other basic block, which has a single predecessor.
325 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
326   bool Changed = false;
327   // Scan all of the blocks in the function, except for the entry block.
328   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
329     BasicBlock *BB = I++;
330     // If the destination block has a single pred, then this is a trivial
331     // edge, just collapse it.
332     BasicBlock *SinglePred = BB->getSinglePredecessor();
333
334     // Don't merge if BB's address is taken.
335     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
336
337     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
338     if (Term && !Term->isConditional()) {
339       Changed = true;
340       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
341       // Remember if SinglePred was the entry block of the function.
342       // If so, we will need to move BB back to the entry position.
343       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
344       MergeBasicBlockIntoOnlyPred(BB, DT);
345
346       if (isEntry && BB != &BB->getParent()->getEntryBlock())
347         BB->moveBefore(&BB->getParent()->getEntryBlock());
348
349       // We have erased a block. Update the iterator.
350       I = BB;
351     }
352   }
353   return Changed;
354 }
355
356 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
357 /// debug info directives, and an unconditional branch.  Passes before isel
358 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
359 /// isel.  Start by eliminating these blocks so we can split them the way we
360 /// want them.
361 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
362   bool MadeChange = false;
363   // Note that this intentionally skips the entry block.
364   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
365     BasicBlock *BB = I++;
366
367     // If this block doesn't end with an uncond branch, ignore it.
368     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
369     if (!BI || !BI->isUnconditional())
370       continue;
371
372     // If the instruction before the branch (skipping debug info) isn't a phi
373     // node, then other stuff is happening here.
374     BasicBlock::iterator BBI = BI;
375     if (BBI != BB->begin()) {
376       --BBI;
377       while (isa<DbgInfoIntrinsic>(BBI)) {
378         if (BBI == BB->begin())
379           break;
380         --BBI;
381       }
382       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
383         continue;
384     }
385
386     // Do not break infinite loops.
387     BasicBlock *DestBB = BI->getSuccessor(0);
388     if (DestBB == BB)
389       continue;
390
391     if (!CanMergeBlocks(BB, DestBB))
392       continue;
393
394     EliminateMostlyEmptyBlock(BB);
395     MadeChange = true;
396   }
397   return MadeChange;
398 }
399
400 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
401 /// single uncond branch between them, and BB contains no other non-phi
402 /// instructions.
403 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
404                                     const BasicBlock *DestBB) const {
405   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
406   // the successor.  If there are more complex condition (e.g. preheaders),
407   // don't mess around with them.
408   BasicBlock::const_iterator BBI = BB->begin();
409   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
410     for (const User *U : PN->users()) {
411       const Instruction *UI = cast<Instruction>(U);
412       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
413         return false;
414       // If User is inside DestBB block and it is a PHINode then check
415       // incoming value. If incoming value is not from BB then this is
416       // a complex condition (e.g. preheaders) we want to avoid here.
417       if (UI->getParent() == DestBB) {
418         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
419           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
420             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
421             if (Insn && Insn->getParent() == BB &&
422                 Insn->getParent() != UPN->getIncomingBlock(I))
423               return false;
424           }
425       }
426     }
427   }
428
429   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
430   // and DestBB may have conflicting incoming values for the block.  If so, we
431   // can't merge the block.
432   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
433   if (!DestBBPN) return true;  // no conflict.
434
435   // Collect the preds of BB.
436   SmallPtrSet<const BasicBlock*, 16> BBPreds;
437   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
438     // It is faster to get preds from a PHI than with pred_iterator.
439     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
440       BBPreds.insert(BBPN->getIncomingBlock(i));
441   } else {
442     BBPreds.insert(pred_begin(BB), pred_end(BB));
443   }
444
445   // Walk the preds of DestBB.
446   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
447     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
448     if (BBPreds.count(Pred)) {   // Common predecessor?
449       BBI = DestBB->begin();
450       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
451         const Value *V1 = PN->getIncomingValueForBlock(Pred);
452         const Value *V2 = PN->getIncomingValueForBlock(BB);
453
454         // If V2 is a phi node in BB, look up what the mapped value will be.
455         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
456           if (V2PN->getParent() == BB)
457             V2 = V2PN->getIncomingValueForBlock(Pred);
458
459         // If there is a conflict, bail out.
460         if (V1 != V2) return false;
461       }
462     }
463   }
464
465   return true;
466 }
467
468
469 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
470 /// an unconditional branch in it.
471 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
472   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
473   BasicBlock *DestBB = BI->getSuccessor(0);
474
475   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
476
477   // If the destination block has a single pred, then this is a trivial edge,
478   // just collapse it.
479   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
480     if (SinglePred != DestBB) {
481       // Remember if SinglePred was the entry block of the function.  If so, we
482       // will need to move BB back to the entry position.
483       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
484       MergeBasicBlockIntoOnlyPred(DestBB, DT);
485
486       if (isEntry && BB != &BB->getParent()->getEntryBlock())
487         BB->moveBefore(&BB->getParent()->getEntryBlock());
488
489       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
490       return;
491     }
492   }
493
494   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
495   // to handle the new incoming edges it is about to have.
496   PHINode *PN;
497   for (BasicBlock::iterator BBI = DestBB->begin();
498        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
499     // Remove the incoming value for BB, and remember it.
500     Value *InVal = PN->removeIncomingValue(BB, false);
501
502     // Two options: either the InVal is a phi node defined in BB or it is some
503     // value that dominates BB.
504     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
505     if (InValPhi && InValPhi->getParent() == BB) {
506       // Add all of the input values of the input PHI as inputs of this phi.
507       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
508         PN->addIncoming(InValPhi->getIncomingValue(i),
509                         InValPhi->getIncomingBlock(i));
510     } else {
511       // Otherwise, add one instance of the dominating value for each edge that
512       // we will be adding.
513       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
514         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
515           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
516       } else {
517         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
518           PN->addIncoming(InVal, *PI);
519       }
520     }
521   }
522
523   // The PHIs are now updated, change everything that refers to BB to use
524   // DestBB and remove BB.
525   BB->replaceAllUsesWith(DestBB);
526   if (DT && !ModifiedDT) {
527     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
528     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
529     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
530     DT->changeImmediateDominator(DestBB, NewIDom);
531     DT->eraseNode(BB);
532   }
533   BB->eraseFromParent();
534   ++NumBlocksElim;
535
536   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
537 }
538
539 // Computes a map of base pointer relocation instructions to corresponding
540 // derived pointer relocation instructions given a vector of all relocate calls
541 static void computeBaseDerivedRelocateMap(
542     const SmallVectorImpl<User *> &AllRelocateCalls,
543     DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
544         RelocateInstMap) {
545   // Collect information in two maps: one primarily for locating the base object
546   // while filling the second map; the second map is the final structure holding
547   // a mapping between Base and corresponding Derived relocate calls
548   DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
549   for (auto &U : AllRelocateCalls) {
550     GCRelocateOperands ThisRelocate(U);
551     IntrinsicInst *I = cast<IntrinsicInst>(U);
552     auto K = std::make_pair(ThisRelocate.basePtrIndex(),
553                             ThisRelocate.derivedPtrIndex());
554     RelocateIdxMap.insert(std::make_pair(K, I));
555   }
556   for (auto &Item : RelocateIdxMap) {
557     std::pair<unsigned, unsigned> Key = Item.first;
558     if (Key.first == Key.second)
559       // Base relocation: nothing to insert
560       continue;
561
562     IntrinsicInst *I = Item.second;
563     auto BaseKey = std::make_pair(Key.first, Key.first);
564
565     // We're iterating over RelocateIdxMap so we cannot modify it.
566     auto MaybeBase = RelocateIdxMap.find(BaseKey);
567     if (MaybeBase == RelocateIdxMap.end())
568       // TODO: We might want to insert a new base object relocate and gep off
569       // that, if there are enough derived object relocates.
570       continue;
571
572     RelocateInstMap[MaybeBase->second].push_back(I);
573   }
574 }
575
576 // Accepts a GEP and extracts the operands into a vector provided they're all
577 // small integer constants
578 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
579                                           SmallVectorImpl<Value *> &OffsetV) {
580   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
581     // Only accept small constant integer operands
582     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
583     if (!Op || Op->getZExtValue() > 20)
584       return false;
585   }
586
587   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
588     OffsetV.push_back(GEP->getOperand(i));
589   return true;
590 }
591
592 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
593 // replace, computes a replacement, and affects it.
594 static bool
595 simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
596                           const SmallVectorImpl<IntrinsicInst *> &Targets) {
597   bool MadeChange = false;
598   for (auto &ToReplace : Targets) {
599     GCRelocateOperands MasterRelocate(RelocatedBase);
600     GCRelocateOperands ThisRelocate(ToReplace);
601
602     assert(ThisRelocate.basePtrIndex() == MasterRelocate.basePtrIndex() &&
603            "Not relocating a derived object of the original base object");
604     if (ThisRelocate.basePtrIndex() == ThisRelocate.derivedPtrIndex()) {
605       // A duplicate relocate call. TODO: coalesce duplicates.
606       continue;
607     }
608
609     Value *Base = ThisRelocate.basePtr();
610     auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.derivedPtr());
611     if (!Derived || Derived->getPointerOperand() != Base)
612       continue;
613
614     SmallVector<Value *, 2> OffsetV;
615     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
616       continue;
617
618     // Create a Builder and replace the target callsite with a gep
619     IRBuilder<> Builder(ToReplace);
620     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
621     Value *Replacement =
622         Builder.CreateGEP(RelocatedBase, makeArrayRef(OffsetV));
623     Instruction *ReplacementInst = cast<Instruction>(Replacement);
624     ReplacementInst->removeFromParent();
625     ReplacementInst->insertAfter(RelocatedBase);
626     Replacement->takeName(ToReplace);
627     ToReplace->replaceAllUsesWith(Replacement);
628     ToReplace->eraseFromParent();
629
630     MadeChange = true;
631   }
632   return MadeChange;
633 }
634
635 // Turns this:
636 //
637 // %base = ...
638 // %ptr = gep %base + 15
639 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
640 // %base' = relocate(%tok, i32 4, i32 4)
641 // %ptr' = relocate(%tok, i32 4, i32 5)
642 // %val = load %ptr'
643 //
644 // into this:
645 //
646 // %base = ...
647 // %ptr = gep %base + 15
648 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
649 // %base' = gc.relocate(%tok, i32 4, i32 4)
650 // %ptr' = gep %base' + 15
651 // %val = load %ptr'
652 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
653   bool MadeChange = false;
654   SmallVector<User *, 2> AllRelocateCalls;
655
656   for (auto *U : I.users())
657     if (isGCRelocate(dyn_cast<Instruction>(U)))
658       // Collect all the relocate calls associated with a statepoint
659       AllRelocateCalls.push_back(U);
660
661   // We need atleast one base pointer relocation + one derived pointer
662   // relocation to mangle
663   if (AllRelocateCalls.size() < 2)
664     return false;
665
666   // RelocateInstMap is a mapping from the base relocate instruction to the
667   // corresponding derived relocate instructions
668   DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
669   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
670   if (RelocateInstMap.empty())
671     return false;
672
673   for (auto &Item : RelocateInstMap)
674     // Item.first is the RelocatedBase to offset against
675     // Item.second is the vector of Targets to replace
676     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
677   return MadeChange;
678 }
679
680 /// SinkCast - Sink the specified cast instruction into its user blocks
681 static bool SinkCast(CastInst *CI) {
682   BasicBlock *DefBB = CI->getParent();
683
684   /// InsertedCasts - Only insert a cast in each block once.
685   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
686
687   bool MadeChange = false;
688   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
689        UI != E; ) {
690     Use &TheUse = UI.getUse();
691     Instruction *User = cast<Instruction>(*UI);
692
693     // Figure out which BB this cast is used in.  For PHI's this is the
694     // appropriate predecessor block.
695     BasicBlock *UserBB = User->getParent();
696     if (PHINode *PN = dyn_cast<PHINode>(User)) {
697       UserBB = PN->getIncomingBlock(TheUse);
698     }
699
700     // Preincrement use iterator so we don't invalidate it.
701     ++UI;
702
703     // If this user is in the same block as the cast, don't change the cast.
704     if (UserBB == DefBB) continue;
705
706     // If we have already inserted a cast into this block, use it.
707     CastInst *&InsertedCast = InsertedCasts[UserBB];
708
709     if (!InsertedCast) {
710       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
711       InsertedCast =
712         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
713                          InsertPt);
714       MadeChange = true;
715     }
716
717     // Replace a use of the cast with a use of the new cast.
718     TheUse = InsertedCast;
719     ++NumCastUses;
720   }
721
722   // If we removed all uses, nuke the cast.
723   if (CI->use_empty()) {
724     CI->eraseFromParent();
725     MadeChange = true;
726   }
727
728   return MadeChange;
729 }
730
731 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
732 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
733 /// sink it into user blocks to reduce the number of virtual
734 /// registers that must be created and coalesced.
735 ///
736 /// Return true if any changes are made.
737 ///
738 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
739   // If this is a noop copy,
740   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
741   EVT DstVT = TLI.getValueType(CI->getType());
742
743   // This is an fp<->int conversion?
744   if (SrcVT.isInteger() != DstVT.isInteger())
745     return false;
746
747   // If this is an extension, it will be a zero or sign extension, which
748   // isn't a noop.
749   if (SrcVT.bitsLT(DstVT)) return false;
750
751   // If these values will be promoted, find out what they will be promoted
752   // to.  This helps us consider truncates on PPC as noop copies when they
753   // are.
754   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
755       TargetLowering::TypePromoteInteger)
756     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
757   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
758       TargetLowering::TypePromoteInteger)
759     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
760
761   // If, after promotion, these are the same types, this is a noop copy.
762   if (SrcVT != DstVT)
763     return false;
764
765   return SinkCast(CI);
766 }
767
768 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
769 /// the number of virtual registers that must be created and coalesced.  This is
770 /// a clear win except on targets with multiple condition code registers
771 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
772 ///
773 /// Return true if any changes are made.
774 static bool OptimizeCmpExpression(CmpInst *CI) {
775   BasicBlock *DefBB = CI->getParent();
776
777   /// InsertedCmp - Only insert a cmp in each block once.
778   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
779
780   bool MadeChange = false;
781   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
782        UI != E; ) {
783     Use &TheUse = UI.getUse();
784     Instruction *User = cast<Instruction>(*UI);
785
786     // Preincrement use iterator so we don't invalidate it.
787     ++UI;
788
789     // Don't bother for PHI nodes.
790     if (isa<PHINode>(User))
791       continue;
792
793     // Figure out which BB this cmp is used in.
794     BasicBlock *UserBB = User->getParent();
795
796     // If this user is in the same block as the cmp, don't change the cmp.
797     if (UserBB == DefBB) continue;
798
799     // If we have already inserted a cmp into this block, use it.
800     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
801
802     if (!InsertedCmp) {
803       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
804       InsertedCmp =
805         CmpInst::Create(CI->getOpcode(),
806                         CI->getPredicate(),  CI->getOperand(0),
807                         CI->getOperand(1), "", InsertPt);
808       MadeChange = true;
809     }
810
811     // Replace a use of the cmp with a use of the new cmp.
812     TheUse = InsertedCmp;
813     ++NumCmpUses;
814   }
815
816   // If we removed all uses, nuke the cmp.
817   if (CI->use_empty())
818     CI->eraseFromParent();
819
820   return MadeChange;
821 }
822
823 /// isExtractBitsCandidateUse - Check if the candidates could
824 /// be combined with shift instruction, which includes:
825 /// 1. Truncate instruction
826 /// 2. And instruction and the imm is a mask of the low bits:
827 /// imm & (imm+1) == 0
828 static bool isExtractBitsCandidateUse(Instruction *User) {
829   if (!isa<TruncInst>(User)) {
830     if (User->getOpcode() != Instruction::And ||
831         !isa<ConstantInt>(User->getOperand(1)))
832       return false;
833
834     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
835
836     if ((Cimm & (Cimm + 1)).getBoolValue())
837       return false;
838   }
839   return true;
840 }
841
842 /// SinkShiftAndTruncate - sink both shift and truncate instruction
843 /// to the use of truncate's BB.
844 static bool
845 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
846                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
847                      const TargetLowering &TLI) {
848   BasicBlock *UserBB = User->getParent();
849   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
850   TruncInst *TruncI = dyn_cast<TruncInst>(User);
851   bool MadeChange = false;
852
853   for (Value::user_iterator TruncUI = TruncI->user_begin(),
854                             TruncE = TruncI->user_end();
855        TruncUI != TruncE;) {
856
857     Use &TruncTheUse = TruncUI.getUse();
858     Instruction *TruncUser = cast<Instruction>(*TruncUI);
859     // Preincrement use iterator so we don't invalidate it.
860
861     ++TruncUI;
862
863     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
864     if (!ISDOpcode)
865       continue;
866
867     // If the use is actually a legal node, there will not be an
868     // implicit truncate.
869     // FIXME: always querying the result type is just an
870     // approximation; some nodes' legality is determined by the
871     // operand or other means. There's no good way to find out though.
872     if (TLI.isOperationLegalOrCustom(
873             ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
874       continue;
875
876     // Don't bother for PHI nodes.
877     if (isa<PHINode>(TruncUser))
878       continue;
879
880     BasicBlock *TruncUserBB = TruncUser->getParent();
881
882     if (UserBB == TruncUserBB)
883       continue;
884
885     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
886     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
887
888     if (!InsertedShift && !InsertedTrunc) {
889       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
890       // Sink the shift
891       if (ShiftI->getOpcode() == Instruction::AShr)
892         InsertedShift =
893             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
894       else
895         InsertedShift =
896             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
897
898       // Sink the trunc
899       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
900       TruncInsertPt++;
901
902       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
903                                        TruncI->getType(), "", TruncInsertPt);
904
905       MadeChange = true;
906
907       TruncTheUse = InsertedTrunc;
908     }
909   }
910   return MadeChange;
911 }
912
913 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
914 /// the uses could potentially be combined with this shift instruction and
915 /// generate BitExtract instruction. It will only be applied if the architecture
916 /// supports BitExtract instruction. Here is an example:
917 /// BB1:
918 ///   %x.extract.shift = lshr i64 %arg1, 32
919 /// BB2:
920 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
921 /// ==>
922 ///
923 /// BB2:
924 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
925 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
926 ///
927 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
928 /// instruction.
929 /// Return true if any changes are made.
930 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
931                                 const TargetLowering &TLI) {
932   BasicBlock *DefBB = ShiftI->getParent();
933
934   /// Only insert instructions in each block once.
935   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
936
937   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
938
939   bool MadeChange = false;
940   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
941        UI != E;) {
942     Use &TheUse = UI.getUse();
943     Instruction *User = cast<Instruction>(*UI);
944     // Preincrement use iterator so we don't invalidate it.
945     ++UI;
946
947     // Don't bother for PHI nodes.
948     if (isa<PHINode>(User))
949       continue;
950
951     if (!isExtractBitsCandidateUse(User))
952       continue;
953
954     BasicBlock *UserBB = User->getParent();
955
956     if (UserBB == DefBB) {
957       // If the shift and truncate instruction are in the same BB. The use of
958       // the truncate(TruncUse) may still introduce another truncate if not
959       // legal. In this case, we would like to sink both shift and truncate
960       // instruction to the BB of TruncUse.
961       // for example:
962       // BB1:
963       // i64 shift.result = lshr i64 opnd, imm
964       // trunc.result = trunc shift.result to i16
965       //
966       // BB2:
967       //   ----> We will have an implicit truncate here if the architecture does
968       //   not have i16 compare.
969       // cmp i16 trunc.result, opnd2
970       //
971       if (isa<TruncInst>(User) && shiftIsLegal
972           // If the type of the truncate is legal, no trucate will be
973           // introduced in other basic blocks.
974           && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
975         MadeChange =
976             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
977
978       continue;
979     }
980     // If we have already inserted a shift into this block, use it.
981     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
982
983     if (!InsertedShift) {
984       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
985
986       if (ShiftI->getOpcode() == Instruction::AShr)
987         InsertedShift =
988             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
989       else
990         InsertedShift =
991             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
992
993       MadeChange = true;
994     }
995
996     // Replace a use of the shift with a use of the new shift.
997     TheUse = InsertedShift;
998   }
999
1000   // If we removed all uses, nuke the shift.
1001   if (ShiftI->use_empty())
1002     ShiftI->eraseFromParent();
1003
1004   return MadeChange;
1005 }
1006
1007 //  ScalarizeMaskedLoad() translates masked load intrinsic, like 
1008 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1009 //                               <16 x i1> %mask, <16 x i32> %passthru)
1010 // to a chain of basic blocks, whith loading element one-by-one if
1011 // the appropriate mask bit is set
1012 // 
1013 //  %1 = bitcast i8* %addr to i32*
1014 //  %2 = extractelement <16 x i1> %mask, i32 0
1015 //  %3 = icmp eq i1 %2, true
1016 //  br i1 %3, label %cond.load, label %else
1017 //
1018 //cond.load:                                        ; preds = %0
1019 //  %4 = getelementptr i32* %1, i32 0
1020 //  %5 = load i32* %4
1021 //  %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1022 //  br label %else
1023 //
1024 //else:                                             ; preds = %0, %cond.load
1025 //  %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1026 //  %7 = extractelement <16 x i1> %mask, i32 1
1027 //  %8 = icmp eq i1 %7, true
1028 //  br i1 %8, label %cond.load1, label %else2
1029 //
1030 //cond.load1:                                       ; preds = %else
1031 //  %9 = getelementptr i32* %1, i32 1
1032 //  %10 = load i32* %9
1033 //  %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1034 //  br label %else2
1035 //
1036 //else2:                                            ; preds = %else, %cond.load1
1037 //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1038 //  %12 = extractelement <16 x i1> %mask, i32 2
1039 //  %13 = icmp eq i1 %12, true
1040 //  br i1 %13, label %cond.load4, label %else5
1041 //
1042 static void ScalarizeMaskedLoad(CallInst *CI) {
1043   Value *Ptr  = CI->getArgOperand(0);
1044   Value *Src0 = CI->getArgOperand(3);
1045   Value *Mask = CI->getArgOperand(2);
1046   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1047   Type *EltTy = VecType->getElementType();
1048
1049   assert(VecType && "Unexpected return type of masked load intrinsic");
1050
1051   IRBuilder<> Builder(CI->getContext());
1052   Instruction *InsertPt = CI;
1053   BasicBlock *IfBlock = CI->getParent();
1054   BasicBlock *CondBlock = nullptr;
1055   BasicBlock *PrevIfBlock = CI->getParent();
1056   Builder.SetInsertPoint(InsertPt);
1057
1058   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1059
1060   // Bitcast %addr fron i8* to EltTy*
1061   Type *NewPtrType =
1062     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1063   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1064   Value *UndefVal = UndefValue::get(VecType);
1065
1066   // The result vector
1067   Value *VResult = UndefVal;
1068
1069   PHINode *Phi = nullptr;
1070   Value *PrevPhi = UndefVal;
1071
1072   unsigned VectorWidth = VecType->getNumElements();
1073   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1074
1075     // Fill the "else" block, created in the previous iteration
1076     //
1077     //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1078     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1079     //  %to_load = icmp eq i1 %mask_1, true
1080     //  br i1 %to_load, label %cond.load, label %else
1081     //
1082     if (Idx > 0) {
1083       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1084       Phi->addIncoming(VResult, CondBlock);
1085       Phi->addIncoming(PrevPhi, PrevIfBlock);
1086       PrevPhi = Phi;
1087       VResult = Phi;
1088     }
1089
1090     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1091     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1092                                     ConstantInt::get(Predicate->getType(), 1));
1093
1094     // Create "cond" block
1095     //
1096     //  %EltAddr = getelementptr i32* %1, i32 0
1097     //  %Elt = load i32* %EltAddr
1098     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1099     //
1100     CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1101     Builder.SetInsertPoint(InsertPt);
1102     
1103     Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1104     LoadInst* Load = Builder.CreateLoad(Gep, false);
1105     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1106
1107     // Create "else" block, fill it in the next iteration
1108     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1109     Builder.SetInsertPoint(InsertPt);
1110     Instruction *OldBr = IfBlock->getTerminator();
1111     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1112     OldBr->eraseFromParent();
1113     PrevIfBlock = IfBlock;
1114     IfBlock = NewIfBlock;
1115   }
1116
1117   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1118   Phi->addIncoming(VResult, CondBlock);
1119   Phi->addIncoming(PrevPhi, PrevIfBlock);
1120   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1121   CI->replaceAllUsesWith(NewI);
1122   CI->eraseFromParent();
1123 }
1124
1125 //  ScalarizeMaskedStore() translates masked store intrinsic, like
1126 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1127 //                               <16 x i1> %mask)
1128 // to a chain of basic blocks, that stores element one-by-one if
1129 // the appropriate mask bit is set
1130 //
1131 //   %1 = bitcast i8* %addr to i32*
1132 //   %2 = extractelement <16 x i1> %mask, i32 0
1133 //   %3 = icmp eq i1 %2, true
1134 //   br i1 %3, label %cond.store, label %else
1135 //
1136 // cond.store:                                       ; preds = %0
1137 //   %4 = extractelement <16 x i32> %val, i32 0
1138 //   %5 = getelementptr i32* %1, i32 0
1139 //   store i32 %4, i32* %5
1140 //   br label %else
1141 // 
1142 // else:                                             ; preds = %0, %cond.store
1143 //   %6 = extractelement <16 x i1> %mask, i32 1
1144 //   %7 = icmp eq i1 %6, true
1145 //   br i1 %7, label %cond.store1, label %else2
1146 // 
1147 // cond.store1:                                      ; preds = %else
1148 //   %8 = extractelement <16 x i32> %val, i32 1
1149 //   %9 = getelementptr i32* %1, i32 1
1150 //   store i32 %8, i32* %9
1151 //   br label %else2
1152 //   . . .
1153 static void ScalarizeMaskedStore(CallInst *CI) {
1154   Value *Ptr  = CI->getArgOperand(1);
1155   Value *Src = CI->getArgOperand(0);
1156   Value *Mask = CI->getArgOperand(3);
1157
1158   VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1159   Type *EltTy = VecType->getElementType();
1160
1161   assert(VecType && "Unexpected data type in masked store intrinsic");
1162
1163   IRBuilder<> Builder(CI->getContext());
1164   Instruction *InsertPt = CI;
1165   BasicBlock *IfBlock = CI->getParent();
1166   Builder.SetInsertPoint(InsertPt);
1167   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1168
1169   // Bitcast %addr fron i8* to EltTy*
1170   Type *NewPtrType =
1171     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1172   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1173
1174   unsigned VectorWidth = VecType->getNumElements();
1175   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1176
1177     // Fill the "else" block, created in the previous iteration
1178     //
1179     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1180     //  %to_store = icmp eq i1 %mask_1, true
1181     //  br i1 %to_load, label %cond.store, label %else
1182     //
1183     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1184     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1185                                     ConstantInt::get(Predicate->getType(), 1));
1186
1187     // Create "cond" block
1188     //
1189     //  %OneElt = extractelement <16 x i32> %Src, i32 Idx
1190     //  %EltAddr = getelementptr i32* %1, i32 0
1191     //  %store i32 %OneElt, i32* %EltAddr
1192     //
1193     BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1194     Builder.SetInsertPoint(InsertPt);
1195     
1196     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1197     Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1198     Builder.CreateStore(OneElt, Gep);
1199
1200     // Create "else" block, fill it in the next iteration
1201     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1202     Builder.SetInsertPoint(InsertPt);
1203     Instruction *OldBr = IfBlock->getTerminator();
1204     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1205     OldBr->eraseFromParent();
1206     IfBlock = NewIfBlock;
1207   }
1208   CI->eraseFromParent();
1209 }
1210
1211 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
1212   BasicBlock *BB = CI->getParent();
1213
1214   // Lower inline assembly if we can.
1215   // If we found an inline asm expession, and if the target knows how to
1216   // lower it to normal LLVM code, do so now.
1217   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1218     if (TLI->ExpandInlineAsm(CI)) {
1219       // Avoid invalidating the iterator.
1220       CurInstIterator = BB->begin();
1221       // Avoid processing instructions out of order, which could cause
1222       // reuse before a value is defined.
1223       SunkAddrs.clear();
1224       return true;
1225     }
1226     // Sink address computing for memory operands into the block.
1227     if (OptimizeInlineAsmInst(CI))
1228       return true;
1229   }
1230
1231   const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
1232
1233   // Align the pointer arguments to this call if the target thinks it's a good
1234   // idea
1235   unsigned MinSize, PrefAlign;
1236   if (TLI && TD && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1237     for (auto &Arg : CI->arg_operands()) {
1238       // We want to align both objects whose address is used directly and
1239       // objects whose address is used in casts and GEPs, though it only makes
1240       // sense for GEPs if the offset is a multiple of the desired alignment and
1241       // if size - offset meets the size threshold.
1242       if (!Arg->getType()->isPointerTy())
1243         continue;
1244       APInt Offset(TD->getPointerSizeInBits(
1245                      cast<PointerType>(Arg->getType())->getAddressSpace()), 0);
1246       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*TD, Offset);
1247       uint64_t Offset2 = Offset.getLimitedValue();
1248       AllocaInst *AI;
1249       if ((Offset2 & (PrefAlign-1)) == 0 &&
1250           (AI = dyn_cast<AllocaInst>(Val)) &&
1251           AI->getAlignment() < PrefAlign &&
1252           TD->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
1253         AI->setAlignment(PrefAlign);
1254       // TODO: Also align GlobalVariables
1255     }
1256     // If this is a memcpy (or similar) then we may be able to improve the
1257     // alignment
1258     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
1259       unsigned Align = getKnownAlignment(MI->getDest(), *TD);
1260       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
1261         Align = std::min(Align, getKnownAlignment(MTI->getSource(), *TD));
1262       if (Align > MI->getAlignment())
1263         MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1264     }
1265   }
1266
1267   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
1268   if (II) {
1269     switch (II->getIntrinsicID()) {
1270     default: break;
1271     case Intrinsic::objectsize: {
1272       // Lower all uses of llvm.objectsize.*
1273       bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1274       Type *ReturnTy = CI->getType();
1275       Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
1276
1277       // Substituting this can cause recursive simplifications, which can
1278       // invalidate our iterator.  Use a WeakVH to hold onto it in case this
1279       // happens.
1280       WeakVH IterHandle(CurInstIterator);
1281
1282       replaceAndRecursivelySimplify(CI, RetVal,
1283                                     TLInfo, ModifiedDT ? nullptr : DT);
1284
1285       // If the iterator instruction was recursively deleted, start over at the
1286       // start of the block.
1287       if (IterHandle != CurInstIterator) {
1288         CurInstIterator = BB->begin();
1289         SunkAddrs.clear();
1290       }
1291       return true;
1292     }
1293     case Intrinsic::masked_load: {
1294       // Scalarize unsupported vector masked load
1295       if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1296         ScalarizeMaskedLoad(CI);
1297         ModifiedDT = true;
1298         return true;
1299       }
1300       return false;
1301     }
1302     case Intrinsic::masked_store: {
1303       if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1304         ScalarizeMaskedStore(CI);
1305         ModifiedDT = true;
1306         return true;
1307       }
1308       return false;
1309     }
1310     }
1311
1312     if (TLI) {
1313       SmallVector<Value*, 2> PtrOps;
1314       Type *AccessTy;
1315       if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
1316         while (!PtrOps.empty())
1317           if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
1318             return true;
1319     }
1320   }
1321
1322   // From here on out we're working with named functions.
1323   if (!CI->getCalledFunction()) return false;
1324
1325   // Lower all default uses of _chk calls.  This is very similar
1326   // to what InstCombineCalls does, but here we are only lowering calls
1327   // to fortified library functions (e.g. __memcpy_chk) that have the default
1328   // "don't know" as the objectsize.  Anything else should be left alone.
1329   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
1330   if (Value *V = Simplifier.optimizeCall(CI)) {
1331     CI->replaceAllUsesWith(V);
1332     CI->eraseFromParent();
1333     return true;
1334   }
1335   return false;
1336 }
1337
1338 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1339 /// instructions to the predecessor to enable tail call optimizations. The
1340 /// case it is currently looking for is:
1341 /// @code
1342 /// bb0:
1343 ///   %tmp0 = tail call i32 @f0()
1344 ///   br label %return
1345 /// bb1:
1346 ///   %tmp1 = tail call i32 @f1()
1347 ///   br label %return
1348 /// bb2:
1349 ///   %tmp2 = tail call i32 @f2()
1350 ///   br label %return
1351 /// return:
1352 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1353 ///   ret i32 %retval
1354 /// @endcode
1355 ///
1356 /// =>
1357 ///
1358 /// @code
1359 /// bb0:
1360 ///   %tmp0 = tail call i32 @f0()
1361 ///   ret i32 %tmp0
1362 /// bb1:
1363 ///   %tmp1 = tail call i32 @f1()
1364 ///   ret i32 %tmp1
1365 /// bb2:
1366 ///   %tmp2 = tail call i32 @f2()
1367 ///   ret i32 %tmp2
1368 /// @endcode
1369 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
1370   if (!TLI)
1371     return false;
1372
1373   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1374   if (!RI)
1375     return false;
1376
1377   PHINode *PN = nullptr;
1378   BitCastInst *BCI = nullptr;
1379   Value *V = RI->getReturnValue();
1380   if (V) {
1381     BCI = dyn_cast<BitCastInst>(V);
1382     if (BCI)
1383       V = BCI->getOperand(0);
1384
1385     PN = dyn_cast<PHINode>(V);
1386     if (!PN)
1387       return false;
1388   }
1389
1390   if (PN && PN->getParent() != BB)
1391     return false;
1392
1393   // It's not safe to eliminate the sign / zero extension of the return value.
1394   // See llvm::isInTailCallPosition().
1395   const Function *F = BB->getParent();
1396   AttributeSet CallerAttrs = F->getAttributes();
1397   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1398       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
1399     return false;
1400
1401   // Make sure there are no instructions between the PHI and return, or that the
1402   // return is the first instruction in the block.
1403   if (PN) {
1404     BasicBlock::iterator BI = BB->begin();
1405     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
1406     if (&*BI == BCI)
1407       // Also skip over the bitcast.
1408       ++BI;
1409     if (&*BI != RI)
1410       return false;
1411   } else {
1412     BasicBlock::iterator BI = BB->begin();
1413     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1414     if (&*BI != RI)
1415       return false;
1416   }
1417
1418   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1419   /// call.
1420   SmallVector<CallInst*, 4> TailCalls;
1421   if (PN) {
1422     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1423       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1424       // Make sure the phi value is indeed produced by the tail call.
1425       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1426           TLI->mayBeEmittedAsTailCall(CI))
1427         TailCalls.push_back(CI);
1428     }
1429   } else {
1430     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1431     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1432       if (!VisitedBBs.insert(*PI).second)
1433         continue;
1434
1435       BasicBlock::InstListType &InstList = (*PI)->getInstList();
1436       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1437       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1438       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1439       if (RI == RE)
1440         continue;
1441
1442       CallInst *CI = dyn_cast<CallInst>(&*RI);
1443       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1444         TailCalls.push_back(CI);
1445     }
1446   }
1447
1448   bool Changed = false;
1449   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1450     CallInst *CI = TailCalls[i];
1451     CallSite CS(CI);
1452
1453     // Conservatively require the attributes of the call to match those of the
1454     // return. Ignore noalias because it doesn't affect the call sequence.
1455     AttributeSet CalleeAttrs = CS.getAttributes();
1456     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1457           removeAttribute(Attribute::NoAlias) !=
1458         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1459           removeAttribute(Attribute::NoAlias))
1460       continue;
1461
1462     // Make sure the call instruction is followed by an unconditional branch to
1463     // the return block.
1464     BasicBlock *CallBB = CI->getParent();
1465     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1466     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1467       continue;
1468
1469     // Duplicate the return into CallBB.
1470     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1471     ModifiedDT = Changed = true;
1472     ++NumRetsDup;
1473   }
1474
1475   // If we eliminated all predecessors of the block, delete the block now.
1476   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1477     BB->eraseFromParent();
1478
1479   return Changed;
1480 }
1481
1482 //===----------------------------------------------------------------------===//
1483 // Memory Optimization
1484 //===----------------------------------------------------------------------===//
1485
1486 namespace {
1487
1488 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1489 /// which holds actual Value*'s for register values.
1490 struct ExtAddrMode : public TargetLowering::AddrMode {
1491   Value *BaseReg;
1492   Value *ScaledReg;
1493   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1494   void print(raw_ostream &OS) const;
1495   void dump() const;
1496
1497   bool operator==(const ExtAddrMode& O) const {
1498     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1499            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1500            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1501   }
1502 };
1503
1504 #ifndef NDEBUG
1505 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1506   AM.print(OS);
1507   return OS;
1508 }
1509 #endif
1510
1511 void ExtAddrMode::print(raw_ostream &OS) const {
1512   bool NeedPlus = false;
1513   OS << "[";
1514   if (BaseGV) {
1515     OS << (NeedPlus ? " + " : "")
1516        << "GV:";
1517     BaseGV->printAsOperand(OS, /*PrintType=*/false);
1518     NeedPlus = true;
1519   }
1520
1521   if (BaseOffs) {
1522     OS << (NeedPlus ? " + " : "")
1523        << BaseOffs;
1524     NeedPlus = true;
1525   }
1526
1527   if (BaseReg) {
1528     OS << (NeedPlus ? " + " : "")
1529        << "Base:";
1530     BaseReg->printAsOperand(OS, /*PrintType=*/false);
1531     NeedPlus = true;
1532   }
1533   if (Scale) {
1534     OS << (NeedPlus ? " + " : "")
1535        << Scale << "*";
1536     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1537   }
1538
1539   OS << ']';
1540 }
1541
1542 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1543 void ExtAddrMode::dump() const {
1544   print(dbgs());
1545   dbgs() << '\n';
1546 }
1547 #endif
1548
1549 /// \brief This class provides transaction based operation on the IR.
1550 /// Every change made through this class is recorded in the internal state and
1551 /// can be undone (rollback) until commit is called.
1552 class TypePromotionTransaction {
1553
1554   /// \brief This represents the common interface of the individual transaction.
1555   /// Each class implements the logic for doing one specific modification on
1556   /// the IR via the TypePromotionTransaction.
1557   class TypePromotionAction {
1558   protected:
1559     /// The Instruction modified.
1560     Instruction *Inst;
1561
1562   public:
1563     /// \brief Constructor of the action.
1564     /// The constructor performs the related action on the IR.
1565     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1566
1567     virtual ~TypePromotionAction() {}
1568
1569     /// \brief Undo the modification done by this action.
1570     /// When this method is called, the IR must be in the same state as it was
1571     /// before this action was applied.
1572     /// \pre Undoing the action works if and only if the IR is in the exact same
1573     /// state as it was directly after this action was applied.
1574     virtual void undo() = 0;
1575
1576     /// \brief Advocate every change made by this action.
1577     /// When the results on the IR of the action are to be kept, it is important
1578     /// to call this function, otherwise hidden information may be kept forever.
1579     virtual void commit() {
1580       // Nothing to be done, this action is not doing anything.
1581     }
1582   };
1583
1584   /// \brief Utility to remember the position of an instruction.
1585   class InsertionHandler {
1586     /// Position of an instruction.
1587     /// Either an instruction:
1588     /// - Is the first in a basic block: BB is used.
1589     /// - Has a previous instructon: PrevInst is used.
1590     union {
1591       Instruction *PrevInst;
1592       BasicBlock *BB;
1593     } Point;
1594     /// Remember whether or not the instruction had a previous instruction.
1595     bool HasPrevInstruction;
1596
1597   public:
1598     /// \brief Record the position of \p Inst.
1599     InsertionHandler(Instruction *Inst) {
1600       BasicBlock::iterator It = Inst;
1601       HasPrevInstruction = (It != (Inst->getParent()->begin()));
1602       if (HasPrevInstruction)
1603         Point.PrevInst = --It;
1604       else
1605         Point.BB = Inst->getParent();
1606     }
1607
1608     /// \brief Insert \p Inst at the recorded position.
1609     void insert(Instruction *Inst) {
1610       if (HasPrevInstruction) {
1611         if (Inst->getParent())
1612           Inst->removeFromParent();
1613         Inst->insertAfter(Point.PrevInst);
1614       } else {
1615         Instruction *Position = Point.BB->getFirstInsertionPt();
1616         if (Inst->getParent())
1617           Inst->moveBefore(Position);
1618         else
1619           Inst->insertBefore(Position);
1620       }
1621     }
1622   };
1623
1624   /// \brief Move an instruction before another.
1625   class InstructionMoveBefore : public TypePromotionAction {
1626     /// Original position of the instruction.
1627     InsertionHandler Position;
1628
1629   public:
1630     /// \brief Move \p Inst before \p Before.
1631     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1632         : TypePromotionAction(Inst), Position(Inst) {
1633       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1634       Inst->moveBefore(Before);
1635     }
1636
1637     /// \brief Move the instruction back to its original position.
1638     void undo() override {
1639       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1640       Position.insert(Inst);
1641     }
1642   };
1643
1644   /// \brief Set the operand of an instruction with a new value.
1645   class OperandSetter : public TypePromotionAction {
1646     /// Original operand of the instruction.
1647     Value *Origin;
1648     /// Index of the modified instruction.
1649     unsigned Idx;
1650
1651   public:
1652     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1653     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1654         : TypePromotionAction(Inst), Idx(Idx) {
1655       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1656                    << "for:" << *Inst << "\n"
1657                    << "with:" << *NewVal << "\n");
1658       Origin = Inst->getOperand(Idx);
1659       Inst->setOperand(Idx, NewVal);
1660     }
1661
1662     /// \brief Restore the original value of the instruction.
1663     void undo() override {
1664       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1665                    << "for: " << *Inst << "\n"
1666                    << "with: " << *Origin << "\n");
1667       Inst->setOperand(Idx, Origin);
1668     }
1669   };
1670
1671   /// \brief Hide the operands of an instruction.
1672   /// Do as if this instruction was not using any of its operands.
1673   class OperandsHider : public TypePromotionAction {
1674     /// The list of original operands.
1675     SmallVector<Value *, 4> OriginalValues;
1676
1677   public:
1678     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1679     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1680       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1681       unsigned NumOpnds = Inst->getNumOperands();
1682       OriginalValues.reserve(NumOpnds);
1683       for (unsigned It = 0; It < NumOpnds; ++It) {
1684         // Save the current operand.
1685         Value *Val = Inst->getOperand(It);
1686         OriginalValues.push_back(Val);
1687         // Set a dummy one.
1688         // We could use OperandSetter here, but that would implied an overhead
1689         // that we are not willing to pay.
1690         Inst->setOperand(It, UndefValue::get(Val->getType()));
1691       }
1692     }
1693
1694     /// \brief Restore the original list of uses.
1695     void undo() override {
1696       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1697       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1698         Inst->setOperand(It, OriginalValues[It]);
1699     }
1700   };
1701
1702   /// \brief Build a truncate instruction.
1703   class TruncBuilder : public TypePromotionAction {
1704     Value *Val;
1705   public:
1706     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1707     /// result.
1708     /// trunc Opnd to Ty.
1709     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1710       IRBuilder<> Builder(Opnd);
1711       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1712       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
1713     }
1714
1715     /// \brief Get the built value.
1716     Value *getBuiltValue() { return Val; }
1717
1718     /// \brief Remove the built instruction.
1719     void undo() override {
1720       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1721       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1722         IVal->eraseFromParent();
1723     }
1724   };
1725
1726   /// \brief Build a sign extension instruction.
1727   class SExtBuilder : public TypePromotionAction {
1728     Value *Val;
1729   public:
1730     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1731     /// result.
1732     /// sext Opnd to Ty.
1733     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1734         : TypePromotionAction(InsertPt) {
1735       IRBuilder<> Builder(InsertPt);
1736       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1737       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
1738     }
1739
1740     /// \brief Get the built value.
1741     Value *getBuiltValue() { return Val; }
1742
1743     /// \brief Remove the built instruction.
1744     void undo() override {
1745       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1746       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1747         IVal->eraseFromParent();
1748     }
1749   };
1750
1751   /// \brief Build a zero extension instruction.
1752   class ZExtBuilder : public TypePromotionAction {
1753     Value *Val;
1754   public:
1755     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1756     /// result.
1757     /// zext Opnd to Ty.
1758     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1759         : TypePromotionAction(InsertPt) {
1760       IRBuilder<> Builder(InsertPt);
1761       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1762       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1763     }
1764
1765     /// \brief Get the built value.
1766     Value *getBuiltValue() { return Val; }
1767
1768     /// \brief Remove the built instruction.
1769     void undo() override {
1770       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1771       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1772         IVal->eraseFromParent();
1773     }
1774   };
1775
1776   /// \brief Mutate an instruction to another type.
1777   class TypeMutator : public TypePromotionAction {
1778     /// Record the original type.
1779     Type *OrigTy;
1780
1781   public:
1782     /// \brief Mutate the type of \p Inst into \p NewTy.
1783     TypeMutator(Instruction *Inst, Type *NewTy)
1784         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1785       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1786                    << "\n");
1787       Inst->mutateType(NewTy);
1788     }
1789
1790     /// \brief Mutate the instruction back to its original type.
1791     void undo() override {
1792       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1793                    << "\n");
1794       Inst->mutateType(OrigTy);
1795     }
1796   };
1797
1798   /// \brief Replace the uses of an instruction by another instruction.
1799   class UsesReplacer : public TypePromotionAction {
1800     /// Helper structure to keep track of the replaced uses.
1801     struct InstructionAndIdx {
1802       /// The instruction using the instruction.
1803       Instruction *Inst;
1804       /// The index where this instruction is used for Inst.
1805       unsigned Idx;
1806       InstructionAndIdx(Instruction *Inst, unsigned Idx)
1807           : Inst(Inst), Idx(Idx) {}
1808     };
1809
1810     /// Keep track of the original uses (pair Instruction, Index).
1811     SmallVector<InstructionAndIdx, 4> OriginalUses;
1812     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1813
1814   public:
1815     /// \brief Replace all the use of \p Inst by \p New.
1816     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1817       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1818                    << "\n");
1819       // Record the original uses.
1820       for (Use &U : Inst->uses()) {
1821         Instruction *UserI = cast<Instruction>(U.getUser());
1822         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1823       }
1824       // Now, we can replace the uses.
1825       Inst->replaceAllUsesWith(New);
1826     }
1827
1828     /// \brief Reassign the original uses of Inst to Inst.
1829     void undo() override {
1830       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1831       for (use_iterator UseIt = OriginalUses.begin(),
1832                         EndIt = OriginalUses.end();
1833            UseIt != EndIt; ++UseIt) {
1834         UseIt->Inst->setOperand(UseIt->Idx, Inst);
1835       }
1836     }
1837   };
1838
1839   /// \brief Remove an instruction from the IR.
1840   class InstructionRemover : public TypePromotionAction {
1841     /// Original position of the instruction.
1842     InsertionHandler Inserter;
1843     /// Helper structure to hide all the link to the instruction. In other
1844     /// words, this helps to do as if the instruction was removed.
1845     OperandsHider Hider;
1846     /// Keep track of the uses replaced, if any.
1847     UsesReplacer *Replacer;
1848
1849   public:
1850     /// \brief Remove all reference of \p Inst and optinally replace all its
1851     /// uses with New.
1852     /// \pre If !Inst->use_empty(), then New != nullptr
1853     InstructionRemover(Instruction *Inst, Value *New = nullptr)
1854         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1855           Replacer(nullptr) {
1856       if (New)
1857         Replacer = new UsesReplacer(Inst, New);
1858       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1859       Inst->removeFromParent();
1860     }
1861
1862     ~InstructionRemover() { delete Replacer; }
1863
1864     /// \brief Really remove the instruction.
1865     void commit() override { delete Inst; }
1866
1867     /// \brief Resurrect the instruction and reassign it to the proper uses if
1868     /// new value was provided when build this action.
1869     void undo() override {
1870       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1871       Inserter.insert(Inst);
1872       if (Replacer)
1873         Replacer->undo();
1874       Hider.undo();
1875     }
1876   };
1877
1878 public:
1879   /// Restoration point.
1880   /// The restoration point is a pointer to an action instead of an iterator
1881   /// because the iterator may be invalidated but not the pointer.
1882   typedef const TypePromotionAction *ConstRestorationPt;
1883   /// Advocate every changes made in that transaction.
1884   void commit();
1885   /// Undo all the changes made after the given point.
1886   void rollback(ConstRestorationPt Point);
1887   /// Get the current restoration point.
1888   ConstRestorationPt getRestorationPoint() const;
1889
1890   /// \name API for IR modification with state keeping to support rollback.
1891   /// @{
1892   /// Same as Instruction::setOperand.
1893   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1894   /// Same as Instruction::eraseFromParent.
1895   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1896   /// Same as Value::replaceAllUsesWith.
1897   void replaceAllUsesWith(Instruction *Inst, Value *New);
1898   /// Same as Value::mutateType.
1899   void mutateType(Instruction *Inst, Type *NewTy);
1900   /// Same as IRBuilder::createTrunc.
1901   Value *createTrunc(Instruction *Opnd, Type *Ty);
1902   /// Same as IRBuilder::createSExt.
1903   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1904   /// Same as IRBuilder::createZExt.
1905   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
1906   /// Same as Instruction::moveBefore.
1907   void moveBefore(Instruction *Inst, Instruction *Before);
1908   /// @}
1909
1910 private:
1911   /// The ordered list of actions made so far.
1912   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1913   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1914 };
1915
1916 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1917                                           Value *NewVal) {
1918   Actions.push_back(
1919       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1920 }
1921
1922 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1923                                                 Value *NewVal) {
1924   Actions.push_back(
1925       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1926 }
1927
1928 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1929                                                   Value *New) {
1930   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1931 }
1932
1933 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1934   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1935 }
1936
1937 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1938                                              Type *Ty) {
1939   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1940   Value *Val = Ptr->getBuiltValue();
1941   Actions.push_back(std::move(Ptr));
1942   return Val;
1943 }
1944
1945 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1946                                             Value *Opnd, Type *Ty) {
1947   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1948   Value *Val = Ptr->getBuiltValue();
1949   Actions.push_back(std::move(Ptr));
1950   return Val;
1951 }
1952
1953 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1954                                             Value *Opnd, Type *Ty) {
1955   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
1956   Value *Val = Ptr->getBuiltValue();
1957   Actions.push_back(std::move(Ptr));
1958   return Val;
1959 }
1960
1961 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1962                                           Instruction *Before) {
1963   Actions.push_back(
1964       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1965 }
1966
1967 TypePromotionTransaction::ConstRestorationPt
1968 TypePromotionTransaction::getRestorationPoint() const {
1969   return !Actions.empty() ? Actions.back().get() : nullptr;
1970 }
1971
1972 void TypePromotionTransaction::commit() {
1973   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1974        ++It)
1975     (*It)->commit();
1976   Actions.clear();
1977 }
1978
1979 void TypePromotionTransaction::rollback(
1980     TypePromotionTransaction::ConstRestorationPt Point) {
1981   while (!Actions.empty() && Point != Actions.back().get()) {
1982     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1983     Curr->undo();
1984   }
1985 }
1986
1987 /// \brief A helper class for matching addressing modes.
1988 ///
1989 /// This encapsulates the logic for matching the target-legal addressing modes.
1990 class AddressingModeMatcher {
1991   SmallVectorImpl<Instruction*> &AddrModeInsts;
1992   const TargetMachine &TM;
1993   const TargetLowering &TLI;
1994
1995   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1996   /// the memory instruction that we're computing this address for.
1997   Type *AccessTy;
1998   Instruction *MemoryInst;
1999
2000   /// AddrMode - This is the addressing mode that we're building up.  This is
2001   /// part of the return value of this addressing mode matching stuff.
2002   ExtAddrMode &AddrMode;
2003
2004   /// The truncate instruction inserted by other CodeGenPrepare optimizations.
2005   const SetOfInstrs &InsertedTruncs;
2006   /// A map from the instructions to their type before promotion.
2007   InstrToOrigTy &PromotedInsts;
2008   /// The ongoing transaction where every action should be registered.
2009   TypePromotionTransaction &TPT;
2010
2011   /// IgnoreProfitability - This is set to true when we should not do
2012   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
2013   /// always returns true.
2014   bool IgnoreProfitability;
2015
2016   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
2017                         const TargetMachine &TM, Type *AT, Instruction *MI,
2018                         ExtAddrMode &AM, const SetOfInstrs &InsertedTruncs,
2019                         InstrToOrigTy &PromotedInsts,
2020                         TypePromotionTransaction &TPT)
2021       : AddrModeInsts(AMI), TM(TM),
2022         TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2023                  ->getTargetLowering()),
2024         AccessTy(AT), MemoryInst(MI), AddrMode(AM),
2025         InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
2026     IgnoreProfitability = false;
2027   }
2028 public:
2029
2030   /// Match - Find the maximal addressing mode that a load/store of V can fold,
2031   /// give an access type of AccessTy.  This returns a list of involved
2032   /// instructions in AddrModeInsts.
2033   /// \p InsertedTruncs The truncate instruction inserted by other
2034   /// CodeGenPrepare
2035   /// optimizations.
2036   /// \p PromotedInsts maps the instructions to their type before promotion.
2037   /// \p The ongoing transaction where every action should be registered.
2038   static ExtAddrMode Match(Value *V, Type *AccessTy,
2039                            Instruction *MemoryInst,
2040                            SmallVectorImpl<Instruction*> &AddrModeInsts,
2041                            const TargetMachine &TM,
2042                            const SetOfInstrs &InsertedTruncs,
2043                            InstrToOrigTy &PromotedInsts,
2044                            TypePromotionTransaction &TPT) {
2045     ExtAddrMode Result;
2046
2047     bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy,
2048                                          MemoryInst, Result, InsertedTruncs,
2049                                          PromotedInsts, TPT).MatchAddr(V, 0);
2050     (void)Success; assert(Success && "Couldn't select *anything*?");
2051     return Result;
2052   }
2053 private:
2054   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2055   bool MatchAddr(Value *V, unsigned Depth);
2056   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
2057                           bool *MovedAway = nullptr);
2058   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
2059                                             ExtAddrMode &AMBefore,
2060                                             ExtAddrMode &AMAfter);
2061   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2062   bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost,
2063                              Value *PromotedOperand) const;
2064 };
2065
2066 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
2067 /// Return true and update AddrMode if this addr mode is legal for the target,
2068 /// false if not.
2069 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
2070                                              unsigned Depth) {
2071   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2072   // mode.  Just process that directly.
2073   if (Scale == 1)
2074     return MatchAddr(ScaleReg, Depth);
2075
2076   // If the scale is 0, it takes nothing to add this.
2077   if (Scale == 0)
2078     return true;
2079
2080   // If we already have a scale of this value, we can add to it, otherwise, we
2081   // need an available scale field.
2082   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2083     return false;
2084
2085   ExtAddrMode TestAddrMode = AddrMode;
2086
2087   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
2088   // [A+B + A*7] -> [B+A*8].
2089   TestAddrMode.Scale += Scale;
2090   TestAddrMode.ScaledReg = ScaleReg;
2091
2092   // If the new address isn't legal, bail out.
2093   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
2094     return false;
2095
2096   // It was legal, so commit it.
2097   AddrMode = TestAddrMode;
2098
2099   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
2100   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
2101   // X*Scale + C*Scale to addr mode.
2102   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
2103   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
2104       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2105     TestAddrMode.ScaledReg = AddLHS;
2106     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
2107
2108     // If this addressing mode is legal, commit it and remember that we folded
2109     // this instruction.
2110     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
2111       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2112       AddrMode = TestAddrMode;
2113       return true;
2114     }
2115   }
2116
2117   // Otherwise, not (x+c)*scale, just return what we have.
2118   return true;
2119 }
2120
2121 /// MightBeFoldableInst - This is a little filter, which returns true if an
2122 /// addressing computation involving I might be folded into a load/store
2123 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
2124 /// the set of instructions that MatchOperationAddr can.
2125 static bool MightBeFoldableInst(Instruction *I) {
2126   switch (I->getOpcode()) {
2127   case Instruction::BitCast:
2128   case Instruction::AddrSpaceCast:
2129     // Don't touch identity bitcasts.
2130     if (I->getType() == I->getOperand(0)->getType())
2131       return false;
2132     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2133   case Instruction::PtrToInt:
2134     // PtrToInt is always a noop, as we know that the int type is pointer sized.
2135     return true;
2136   case Instruction::IntToPtr:
2137     // We know the input is intptr_t, so this is foldable.
2138     return true;
2139   case Instruction::Add:
2140     return true;
2141   case Instruction::Mul:
2142   case Instruction::Shl:
2143     // Can only handle X*C and X << C.
2144     return isa<ConstantInt>(I->getOperand(1));
2145   case Instruction::GetElementPtr:
2146     return true;
2147   default:
2148     return false;
2149   }
2150 }
2151
2152 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2153 /// \note \p Val is assumed to be the product of some type promotion.
2154 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2155 /// to be legal, as the non-promoted value would have had the same state.
2156 static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
2157   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2158   if (!PromotedInst)
2159     return false;
2160   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2161   // If the ISDOpcode is undefined, it was undefined before the promotion.
2162   if (!ISDOpcode)
2163     return true;
2164   // Otherwise, check if the promoted instruction is legal or not.
2165   return TLI.isOperationLegalOrCustom(
2166       ISDOpcode, TLI.getValueType(PromotedInst->getType()));
2167 }
2168
2169 /// \brief Hepler class to perform type promotion.
2170 class TypePromotionHelper {
2171   /// \brief Utility function to check whether or not a sign or zero extension
2172   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2173   /// either using the operands of \p Inst or promoting \p Inst.
2174   /// The type of the extension is defined by \p IsSExt.
2175   /// In other words, check if:
2176   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
2177   /// #1 Promotion applies:
2178   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
2179   /// #2 Operand reuses:
2180   /// ext opnd1 to ConsideredExtType.
2181   /// \p PromotedInsts maps the instructions to their type before promotion.
2182   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2183                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
2184
2185   /// \brief Utility function to determine if \p OpIdx should be promoted when
2186   /// promoting \p Inst.
2187   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
2188     if (isa<SelectInst>(Inst) && OpIdx == 0)
2189       return false;
2190     return true;
2191   }
2192
2193   /// \brief Utility function to promote the operand of \p Ext when this
2194   /// operand is a promotable trunc or sext or zext.
2195   /// \p PromotedInsts maps the instructions to their type before promotion.
2196   /// \p CreatedInstsCost[out] contains the cost of all instructions
2197   /// created to promote the operand of Ext.
2198   /// Newly added extensions are inserted in \p Exts.
2199   /// Newly added truncates are inserted in \p Truncs.
2200   /// Should never be called directly.
2201   /// \return The promoted value which is used instead of Ext.
2202   static Value *promoteOperandForTruncAndAnyExt(
2203       Instruction *Ext, TypePromotionTransaction &TPT,
2204       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2205       SmallVectorImpl<Instruction *> *Exts,
2206       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
2207
2208   /// \brief Utility function to promote the operand of \p Ext when this
2209   /// operand is promotable and is not a supported trunc or sext.
2210   /// \p PromotedInsts maps the instructions to their type before promotion.
2211   /// \p CreatedInstsCost[out] contains the cost of all the instructions
2212   /// created to promote the operand of Ext.
2213   /// Newly added extensions are inserted in \p Exts.
2214   /// Newly added truncates are inserted in \p Truncs.
2215   /// Should never be called directly.
2216   /// \return The promoted value which is used instead of Ext.
2217   static Value *promoteOperandForOther(Instruction *Ext,
2218                                        TypePromotionTransaction &TPT,
2219                                        InstrToOrigTy &PromotedInsts,
2220                                        unsigned &CreatedInstsCost,
2221                                        SmallVectorImpl<Instruction *> *Exts,
2222                                        SmallVectorImpl<Instruction *> *Truncs,
2223                                        const TargetLowering &TLI, bool IsSExt);
2224
2225   /// \see promoteOperandForOther.
2226   static Value *signExtendOperandForOther(
2227       Instruction *Ext, TypePromotionTransaction &TPT,
2228       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2229       SmallVectorImpl<Instruction *> *Exts,
2230       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2231     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2232                                   Exts, Truncs, TLI, true);
2233   }
2234
2235   /// \see promoteOperandForOther.
2236   static Value *zeroExtendOperandForOther(
2237       Instruction *Ext, TypePromotionTransaction &TPT,
2238       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2239       SmallVectorImpl<Instruction *> *Exts,
2240       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2241     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2242                                   Exts, Truncs, TLI, false);
2243   }
2244
2245 public:
2246   /// Type for the utility function that promotes the operand of Ext.
2247   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
2248                            InstrToOrigTy &PromotedInsts,
2249                            unsigned &CreatedInstsCost,
2250                            SmallVectorImpl<Instruction *> *Exts,
2251                            SmallVectorImpl<Instruction *> *Truncs,
2252                            const TargetLowering &TLI);
2253   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2254   /// action to promote the operand of \p Ext instead of using Ext.
2255   /// \return NULL if no promotable action is possible with the current
2256   /// sign extension.
2257   /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
2258   /// the others CodeGenPrepare optimizations. This information is important
2259   /// because we do not want to promote these instructions as CodeGenPrepare
2260   /// will reinsert them later. Thus creating an infinite loop: create/remove.
2261   /// \p PromotedInsts maps the instructions to their type before promotion.
2262   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
2263                           const TargetLowering &TLI,
2264                           const InstrToOrigTy &PromotedInsts);
2265 };
2266
2267 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
2268                                         Type *ConsideredExtType,
2269                                         const InstrToOrigTy &PromotedInsts,
2270                                         bool IsSExt) {
2271   // The promotion helper does not know how to deal with vector types yet.
2272   // To be able to fix that, we would need to fix the places where we
2273   // statically extend, e.g., constants and such.
2274   if (Inst->getType()->isVectorTy())
2275     return false;
2276
2277   // We can always get through zext.
2278   if (isa<ZExtInst>(Inst))
2279     return true;
2280
2281   // sext(sext) is ok too.
2282   if (IsSExt && isa<SExtInst>(Inst))
2283     return true;
2284
2285   // We can get through binary operator, if it is legal. In other words, the
2286   // binary operator must have a nuw or nsw flag.
2287   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2288   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
2289       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2290        (IsSExt && BinOp->hasNoSignedWrap())))
2291     return true;
2292
2293   // Check if we can do the following simplification.
2294   // ext(trunc(opnd)) --> ext(opnd)
2295   if (!isa<TruncInst>(Inst))
2296     return false;
2297
2298   Value *OpndVal = Inst->getOperand(0);
2299   // Check if we can use this operand in the extension.
2300   // If the type is larger than the result type of the extension,
2301   // we cannot.
2302   if (!OpndVal->getType()->isIntegerTy() ||
2303       OpndVal->getType()->getIntegerBitWidth() >
2304           ConsideredExtType->getIntegerBitWidth())
2305     return false;
2306
2307   // If the operand of the truncate is not an instruction, we will not have
2308   // any information on the dropped bits.
2309   // (Actually we could for constant but it is not worth the extra logic).
2310   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2311   if (!Opnd)
2312     return false;
2313
2314   // Check if the source of the type is narrow enough.
2315   // I.e., check that trunc just drops extended bits of the same kind of
2316   // the extension.
2317   // #1 get the type of the operand and check the kind of the extended bits.
2318   const Type *OpndType;
2319   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
2320   if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
2321     OpndType = It->second.Ty;
2322   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2323     OpndType = Opnd->getOperand(0)->getType();
2324   else
2325     return false;
2326
2327   // #2 check that the truncate just drop extended bits.
2328   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2329     return true;
2330
2331   return false;
2332 }
2333
2334 TypePromotionHelper::Action TypePromotionHelper::getAction(
2335     Instruction *Ext, const SetOfInstrs &InsertedTruncs,
2336     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
2337   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2338          "Unexpected instruction type");
2339   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2340   Type *ExtTy = Ext->getType();
2341   bool IsSExt = isa<SExtInst>(Ext);
2342   // If the operand of the extension is not an instruction, we cannot
2343   // get through.
2344   // If it, check we can get through.
2345   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
2346     return nullptr;
2347
2348   // Do not promote if the operand has been added by codegenprepare.
2349   // Otherwise, it means we are undoing an optimization that is likely to be
2350   // redone, thus causing potential infinite loop.
2351   if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
2352     return nullptr;
2353
2354   // SExt or Trunc instructions.
2355   // Return the related handler.
2356   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2357       isa<ZExtInst>(ExtOpnd))
2358     return promoteOperandForTruncAndAnyExt;
2359
2360   // Regular instruction.
2361   // Abort early if we will have to insert non-free instructions.
2362   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
2363     return nullptr;
2364   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
2365 }
2366
2367 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
2368     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
2369     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2370     SmallVectorImpl<Instruction *> *Exts,
2371     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2372   // By construction, the operand of SExt is an instruction. Otherwise we cannot
2373   // get through it and this method should not be called.
2374   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
2375   Value *ExtVal = SExt;
2376   bool HasMergedNonFreeExt = false;
2377   if (isa<ZExtInst>(SExtOpnd)) {
2378     // Replace s|zext(zext(opnd))
2379     // => zext(opnd).
2380     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
2381     Value *ZExt =
2382         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2383     TPT.replaceAllUsesWith(SExt, ZExt);
2384     TPT.eraseInstruction(SExt);
2385     ExtVal = ZExt;
2386   } else {
2387     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2388     // => z|sext(opnd).
2389     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2390   }
2391   CreatedInstsCost = 0;
2392
2393   // Remove dead code.
2394   if (SExtOpnd->use_empty())
2395     TPT.eraseInstruction(SExtOpnd);
2396
2397   // Check if the extension is still needed.
2398   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
2399   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2400     if (ExtInst) {
2401       if (Exts)
2402         Exts->push_back(ExtInst);
2403       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2404     }
2405     return ExtVal;
2406   }
2407
2408   // At this point we have: ext ty opnd to ty.
2409   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2410   Value *NextVal = ExtInst->getOperand(0);
2411   TPT.eraseInstruction(ExtInst, NextVal);
2412   return NextVal;
2413 }
2414
2415 Value *TypePromotionHelper::promoteOperandForOther(
2416     Instruction *Ext, TypePromotionTransaction &TPT,
2417     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2418     SmallVectorImpl<Instruction *> *Exts,
2419     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2420     bool IsSExt) {
2421   // By construction, the operand of Ext is an instruction. Otherwise we cannot
2422   // get through it and this method should not be called.
2423   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
2424   CreatedInstsCost = 0;
2425   if (!ExtOpnd->hasOneUse()) {
2426     // ExtOpnd will be promoted.
2427     // All its uses, but Ext, will need to use a truncated value of the
2428     // promoted version.
2429     // Create the truncate now.
2430     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
2431     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2432       ITrunc->removeFromParent();
2433       // Insert it just after the definition.
2434       ITrunc->insertAfter(ExtOpnd);
2435       if (Truncs)
2436         Truncs->push_back(ITrunc);
2437     }
2438
2439     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2440     // Restore the operand of Ext (which has been replace by the previous call
2441     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
2442     TPT.setOperand(Ext, 0, ExtOpnd);
2443   }
2444
2445   // Get through the Instruction:
2446   // 1. Update its type.
2447   // 2. Replace the uses of Ext by Inst.
2448   // 3. Extend each operand that needs to be extended.
2449
2450   // Remember the original type of the instruction before promotion.
2451   // This is useful to know that the high bits are sign extended bits.
2452   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2453       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
2454   // Step #1.
2455   TPT.mutateType(ExtOpnd, Ext->getType());
2456   // Step #2.
2457   TPT.replaceAllUsesWith(Ext, ExtOpnd);
2458   // Step #3.
2459   Instruction *ExtForOpnd = Ext;
2460
2461   DEBUG(dbgs() << "Propagate Ext to operands\n");
2462   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
2463        ++OpIdx) {
2464     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2465     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2466         !shouldExtOperand(ExtOpnd, OpIdx)) {
2467       DEBUG(dbgs() << "No need to propagate\n");
2468       continue;
2469     }
2470     // Check if we can statically extend the operand.
2471     Value *Opnd = ExtOpnd->getOperand(OpIdx);
2472     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
2473       DEBUG(dbgs() << "Statically extend\n");
2474       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2475       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2476                             : Cst->getValue().zext(BitWidth);
2477       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
2478       continue;
2479     }
2480     // UndefValue are typed, so we have to statically sign extend them.
2481     if (isa<UndefValue>(Opnd)) {
2482       DEBUG(dbgs() << "Statically extend\n");
2483       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
2484       continue;
2485     }
2486
2487     // Otherwise we have to explicity sign extend the operand.
2488     // Check if Ext was reused to extend an operand.
2489     if (!ExtForOpnd) {
2490       // If yes, create a new one.
2491       DEBUG(dbgs() << "More operands to ext\n");
2492       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2493         : TPT.createZExt(Ext, Opnd, Ext->getType());
2494       if (!isa<Instruction>(ValForExtOpnd)) {
2495         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2496         continue;
2497       }
2498       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
2499     }
2500     if (Exts)
2501       Exts->push_back(ExtForOpnd);
2502     TPT.setOperand(ExtForOpnd, 0, Opnd);
2503
2504     // Move the sign extension before the insertion point.
2505     TPT.moveBefore(ExtForOpnd, ExtOpnd);
2506     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2507     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
2508     // If more sext are required, new instructions will have to be created.
2509     ExtForOpnd = nullptr;
2510   }
2511   if (ExtForOpnd == Ext) {
2512     DEBUG(dbgs() << "Extension is useless now\n");
2513     TPT.eraseInstruction(Ext);
2514   }
2515   return ExtOpnd;
2516 }
2517
2518 /// IsPromotionProfitable - Check whether or not promoting an instruction
2519 /// to a wider type was profitable.
2520 /// \p NewCost gives the cost of extension instructions created by the
2521 /// promotion.
2522 /// \p OldCost gives the cost of extension instructions before the promotion
2523 /// plus the number of instructions that have been
2524 /// matched in the addressing mode the promotion.
2525 /// \p PromotedOperand is the value that has been promoted.
2526 /// \return True if the promotion is profitable, false otherwise.
2527 bool AddressingModeMatcher::IsPromotionProfitable(
2528     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2529   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2530   // The cost of the new extensions is greater than the cost of the
2531   // old extension plus what we folded.
2532   // This is not profitable.
2533   if (NewCost > OldCost)
2534     return false;
2535   if (NewCost < OldCost)
2536     return true;
2537   // The promotion is neutral but it may help folding the sign extension in
2538   // loads for instance.
2539   // Check that we did not create an illegal instruction.
2540   return isPromotedInstructionLegal(TLI, PromotedOperand);
2541 }
2542
2543 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2544 /// fold the operation into the addressing mode.  If so, update the addressing
2545 /// mode and return true, otherwise return false without modifying AddrMode.
2546 /// If \p MovedAway is not NULL, it contains the information of whether or
2547 /// not AddrInst has to be folded into the addressing mode on success.
2548 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2549 /// because it has been moved away.
2550 /// Thus AddrInst must not be added in the matched instructions.
2551 /// This state can happen when AddrInst is a sext, since it may be moved away.
2552 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2553 /// not be referenced anymore.
2554 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2555                                                unsigned Depth,
2556                                                bool *MovedAway) {
2557   // Avoid exponential behavior on extremely deep expression trees.
2558   if (Depth >= 5) return false;
2559
2560   // By default, all matched instructions stay in place.
2561   if (MovedAway)
2562     *MovedAway = false;
2563
2564   switch (Opcode) {
2565   case Instruction::PtrToInt:
2566     // PtrToInt is always a noop, as we know that the int type is pointer sized.
2567     return MatchAddr(AddrInst->getOperand(0), Depth);
2568   case Instruction::IntToPtr:
2569     // This inttoptr is a no-op if the integer type is pointer sized.
2570     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
2571         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
2572       return MatchAddr(AddrInst->getOperand(0), Depth);
2573     return false;
2574   case Instruction::BitCast:
2575   case Instruction::AddrSpaceCast:
2576     // BitCast is always a noop, and we can handle it as long as it is
2577     // int->int or pointer->pointer (we don't want int<->fp or something).
2578     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2579          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2580         // Don't touch identity bitcasts.  These were probably put here by LSR,
2581         // and we don't want to mess around with them.  Assume it knows what it
2582         // is doing.
2583         AddrInst->getOperand(0)->getType() != AddrInst->getType())
2584       return MatchAddr(AddrInst->getOperand(0), Depth);
2585     return false;
2586   case Instruction::Add: {
2587     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
2588     ExtAddrMode BackupAddrMode = AddrMode;
2589     unsigned OldSize = AddrModeInsts.size();
2590     // Start a transaction at this point.
2591     // The LHS may match but not the RHS.
2592     // Therefore, we need a higher level restoration point to undo partially
2593     // matched operation.
2594     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2595         TPT.getRestorationPoint();
2596
2597     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2598         MatchAddr(AddrInst->getOperand(0), Depth+1))
2599       return true;
2600
2601     // Restore the old addr mode info.
2602     AddrMode = BackupAddrMode;
2603     AddrModeInsts.resize(OldSize);
2604     TPT.rollback(LastKnownGood);
2605
2606     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
2607     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2608         MatchAddr(AddrInst->getOperand(1), Depth+1))
2609       return true;
2610
2611     // Otherwise we definitely can't merge the ADD in.
2612     AddrMode = BackupAddrMode;
2613     AddrModeInsts.resize(OldSize);
2614     TPT.rollback(LastKnownGood);
2615     break;
2616   }
2617   //case Instruction::Or:
2618   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2619   //break;
2620   case Instruction::Mul:
2621   case Instruction::Shl: {
2622     // Can only handle X*C and X << C.
2623     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2624     if (!RHS)
2625       return false;
2626     int64_t Scale = RHS->getSExtValue();
2627     if (Opcode == Instruction::Shl)
2628       Scale = 1LL << Scale;
2629
2630     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2631   }
2632   case Instruction::GetElementPtr: {
2633     // Scan the GEP.  We check it if it contains constant offsets and at most
2634     // one variable offset.
2635     int VariableOperand = -1;
2636     unsigned VariableScale = 0;
2637
2638     int64_t ConstantOffset = 0;
2639     const DataLayout *TD = TLI.getDataLayout();
2640     gep_type_iterator GTI = gep_type_begin(AddrInst);
2641     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2642       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2643         const StructLayout *SL = TD->getStructLayout(STy);
2644         unsigned Idx =
2645           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2646         ConstantOffset += SL->getElementOffset(Idx);
2647       } else {
2648         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2649         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2650           ConstantOffset += CI->getSExtValue()*TypeSize;
2651         } else if (TypeSize) {  // Scales of zero don't do anything.
2652           // We only allow one variable index at the moment.
2653           if (VariableOperand != -1)
2654             return false;
2655
2656           // Remember the variable index.
2657           VariableOperand = i;
2658           VariableScale = TypeSize;
2659         }
2660       }
2661     }
2662
2663     // A common case is for the GEP to only do a constant offset.  In this case,
2664     // just add it to the disp field and check validity.
2665     if (VariableOperand == -1) {
2666       AddrMode.BaseOffs += ConstantOffset;
2667       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2668         // Check to see if we can fold the base pointer in too.
2669         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2670           return true;
2671       }
2672       AddrMode.BaseOffs -= ConstantOffset;
2673       return false;
2674     }
2675
2676     // Save the valid addressing mode in case we can't match.
2677     ExtAddrMode BackupAddrMode = AddrMode;
2678     unsigned OldSize = AddrModeInsts.size();
2679
2680     // See if the scale and offset amount is valid for this target.
2681     AddrMode.BaseOffs += ConstantOffset;
2682
2683     // Match the base operand of the GEP.
2684     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2685       // If it couldn't be matched, just stuff the value in a register.
2686       if (AddrMode.HasBaseReg) {
2687         AddrMode = BackupAddrMode;
2688         AddrModeInsts.resize(OldSize);
2689         return false;
2690       }
2691       AddrMode.HasBaseReg = true;
2692       AddrMode.BaseReg = AddrInst->getOperand(0);
2693     }
2694
2695     // Match the remaining variable portion of the GEP.
2696     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2697                           Depth)) {
2698       // If it couldn't be matched, try stuffing the base into a register
2699       // instead of matching it, and retrying the match of the scale.
2700       AddrMode = BackupAddrMode;
2701       AddrModeInsts.resize(OldSize);
2702       if (AddrMode.HasBaseReg)
2703         return false;
2704       AddrMode.HasBaseReg = true;
2705       AddrMode.BaseReg = AddrInst->getOperand(0);
2706       AddrMode.BaseOffs += ConstantOffset;
2707       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2708                             VariableScale, Depth)) {
2709         // If even that didn't work, bail.
2710         AddrMode = BackupAddrMode;
2711         AddrModeInsts.resize(OldSize);
2712         return false;
2713       }
2714     }
2715
2716     return true;
2717   }
2718   case Instruction::SExt:
2719   case Instruction::ZExt: {
2720     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2721     if (!Ext)
2722       return false;
2723
2724     // Try to move this ext out of the way of the addressing mode.
2725     // Ask for a method for doing so.
2726     TypePromotionHelper::Action TPH =
2727         TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
2728     if (!TPH)
2729       return false;
2730
2731     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2732         TPT.getRestorationPoint();
2733     unsigned CreatedInstsCost = 0;
2734     unsigned ExtCost = !TLI.isExtFree(Ext);
2735     Value *PromotedOperand =
2736         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
2737     // SExt has been moved away.
2738     // Thus either it will be rematched later in the recursive calls or it is
2739     // gone. Anyway, we must not fold it into the addressing mode at this point.
2740     // E.g.,
2741     // op = add opnd, 1
2742     // idx = ext op
2743     // addr = gep base, idx
2744     // is now:
2745     // promotedOpnd = ext opnd            <- no match here
2746     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
2747     // addr = gep base, op                <- match
2748     if (MovedAway)
2749       *MovedAway = true;
2750
2751     assert(PromotedOperand &&
2752            "TypePromotionHelper should have filtered out those cases");
2753
2754     ExtAddrMode BackupAddrMode = AddrMode;
2755     unsigned OldSize = AddrModeInsts.size();
2756
2757     if (!MatchAddr(PromotedOperand, Depth) ||
2758         // The total of the new cost is equals to the cost of the created
2759         // instructions.
2760         // The total of the old cost is equals to the cost of the extension plus
2761         // what we have saved in the addressing mode.
2762         !IsPromotionProfitable(CreatedInstsCost,
2763                                ExtCost + (AddrModeInsts.size() - OldSize),
2764                                PromotedOperand)) {
2765       AddrMode = BackupAddrMode;
2766       AddrModeInsts.resize(OldSize);
2767       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2768       TPT.rollback(LastKnownGood);
2769       return false;
2770     }
2771     return true;
2772   }
2773   }
2774   return false;
2775 }
2776
2777 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2778 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
2779 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
2780 /// or intptr_t for the target.
2781 ///
2782 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2783   // Start a transaction at this point that we will rollback if the matching
2784   // fails.
2785   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2786       TPT.getRestorationPoint();
2787   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2788     // Fold in immediates if legal for the target.
2789     AddrMode.BaseOffs += CI->getSExtValue();
2790     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2791       return true;
2792     AddrMode.BaseOffs -= CI->getSExtValue();
2793   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2794     // If this is a global variable, try to fold it into the addressing mode.
2795     if (!AddrMode.BaseGV) {
2796       AddrMode.BaseGV = GV;
2797       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2798         return true;
2799       AddrMode.BaseGV = nullptr;
2800     }
2801   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2802     ExtAddrMode BackupAddrMode = AddrMode;
2803     unsigned OldSize = AddrModeInsts.size();
2804
2805     // Check to see if it is possible to fold this operation.
2806     bool MovedAway = false;
2807     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2808       // This instruction may have been move away. If so, there is nothing
2809       // to check here.
2810       if (MovedAway)
2811         return true;
2812       // Okay, it's possible to fold this.  Check to see if it is actually
2813       // *profitable* to do so.  We use a simple cost model to avoid increasing
2814       // register pressure too much.
2815       if (I->hasOneUse() ||
2816           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2817         AddrModeInsts.push_back(I);
2818         return true;
2819       }
2820
2821       // It isn't profitable to do this, roll back.
2822       //cerr << "NOT FOLDING: " << *I;
2823       AddrMode = BackupAddrMode;
2824       AddrModeInsts.resize(OldSize);
2825       TPT.rollback(LastKnownGood);
2826     }
2827   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2828     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2829       return true;
2830     TPT.rollback(LastKnownGood);
2831   } else if (isa<ConstantPointerNull>(Addr)) {
2832     // Null pointer gets folded without affecting the addressing mode.
2833     return true;
2834   }
2835
2836   // Worse case, the target should support [reg] addressing modes. :)
2837   if (!AddrMode.HasBaseReg) {
2838     AddrMode.HasBaseReg = true;
2839     AddrMode.BaseReg = Addr;
2840     // Still check for legality in case the target supports [imm] but not [i+r].
2841     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2842       return true;
2843     AddrMode.HasBaseReg = false;
2844     AddrMode.BaseReg = nullptr;
2845   }
2846
2847   // If the base register is already taken, see if we can do [r+r].
2848   if (AddrMode.Scale == 0) {
2849     AddrMode.Scale = 1;
2850     AddrMode.ScaledReg = Addr;
2851     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2852       return true;
2853     AddrMode.Scale = 0;
2854     AddrMode.ScaledReg = nullptr;
2855   }
2856   // Couldn't match.
2857   TPT.rollback(LastKnownGood);
2858   return false;
2859 }
2860
2861 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2862 /// inline asm call are due to memory operands.  If so, return true, otherwise
2863 /// return false.
2864 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2865                                     const TargetMachine &TM) {
2866   const Function *F = CI->getParent()->getParent();
2867   const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2868   const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
2869   TargetLowering::AsmOperandInfoVector TargetConstraints =
2870       TLI->ParseConstraints(TRI, ImmutableCallSite(CI));
2871   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2872     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2873
2874     // Compute the constraint code and ConstraintType to use.
2875     TLI->ComputeConstraintToUse(OpInfo, SDValue());
2876
2877     // If this asm operand is our Value*, and if it isn't an indirect memory
2878     // operand, we can't fold it!
2879     if (OpInfo.CallOperandVal == OpVal &&
2880         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2881          !OpInfo.isIndirect))
2882       return false;
2883   }
2884
2885   return true;
2886 }
2887
2888 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2889 /// memory use.  If we find an obviously non-foldable instruction, return true.
2890 /// Add the ultimately found memory instructions to MemoryUses.
2891 static bool FindAllMemoryUses(
2892     Instruction *I,
2893     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
2894     SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
2895   // If we already considered this instruction, we're done.
2896   if (!ConsideredInsts.insert(I).second)
2897     return false;
2898
2899   // If this is an obviously unfoldable instruction, bail out.
2900   if (!MightBeFoldableInst(I))
2901     return true;
2902
2903   // Loop over all the uses, recursively processing them.
2904   for (Use &U : I->uses()) {
2905     Instruction *UserI = cast<Instruction>(U.getUser());
2906
2907     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2908       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2909       continue;
2910     }
2911
2912     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2913       unsigned opNo = U.getOperandNo();
2914       if (opNo == 0) return true; // Storing addr, not into addr.
2915       MemoryUses.push_back(std::make_pair(SI, opNo));
2916       continue;
2917     }
2918
2919     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2920       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2921       if (!IA) return true;
2922
2923       // If this is a memory operand, we're cool, otherwise bail out.
2924       if (!IsOperandAMemoryOperand(CI, IA, I, TM))
2925         return true;
2926       continue;
2927     }
2928
2929     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
2930       return true;
2931   }
2932
2933   return false;
2934 }
2935
2936 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2937 /// the use site that we're folding it into.  If so, there is no cost to
2938 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
2939 /// that we know are live at the instruction already.
2940 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2941                                                    Value *KnownLive2) {
2942   // If Val is either of the known-live values, we know it is live!
2943   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2944     return true;
2945
2946   // All values other than instructions and arguments (e.g. constants) are live.
2947   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2948
2949   // If Val is a constant sized alloca in the entry block, it is live, this is
2950   // true because it is just a reference to the stack/frame pointer, which is
2951   // live for the whole function.
2952   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2953     if (AI->isStaticAlloca())
2954       return true;
2955
2956   // Check to see if this value is already used in the memory instruction's
2957   // block.  If so, it's already live into the block at the very least, so we
2958   // can reasonably fold it.
2959   return Val->isUsedInBasicBlock(MemoryInst->getParent());
2960 }
2961
2962 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2963 /// mode of the machine to fold the specified instruction into a load or store
2964 /// that ultimately uses it.  However, the specified instruction has multiple
2965 /// uses.  Given this, it may actually increase register pressure to fold it
2966 /// into the load.  For example, consider this code:
2967 ///
2968 ///     X = ...
2969 ///     Y = X+1
2970 ///     use(Y)   -> nonload/store
2971 ///     Z = Y+1
2972 ///     load Z
2973 ///
2974 /// In this case, Y has multiple uses, and can be folded into the load of Z
2975 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
2976 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
2977 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
2978 /// number of computations either.
2979 ///
2980 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
2981 /// X was live across 'load Z' for other reasons, we actually *would* want to
2982 /// fold the addressing mode in the Z case.  This would make Y die earlier.
2983 bool AddressingModeMatcher::
2984 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2985                                      ExtAddrMode &AMAfter) {
2986   if (IgnoreProfitability) return true;
2987
2988   // AMBefore is the addressing mode before this instruction was folded into it,
2989   // and AMAfter is the addressing mode after the instruction was folded.  Get
2990   // the set of registers referenced by AMAfter and subtract out those
2991   // referenced by AMBefore: this is the set of values which folding in this
2992   // address extends the lifetime of.
2993   //
2994   // Note that there are only two potential values being referenced here,
2995   // BaseReg and ScaleReg (global addresses are always available, as are any
2996   // folded immediates).
2997   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2998
2999   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3000   // lifetime wasn't extended by adding this instruction.
3001   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
3002     BaseReg = nullptr;
3003   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
3004     ScaledReg = nullptr;
3005
3006   // If folding this instruction (and it's subexprs) didn't extend any live
3007   // ranges, we're ok with it.
3008   if (!BaseReg && !ScaledReg)
3009     return true;
3010
3011   // If all uses of this instruction are ultimately load/store/inlineasm's,
3012   // check to see if their addressing modes will include this instruction.  If
3013   // so, we can fold it into all uses, so it doesn't matter if it has multiple
3014   // uses.
3015   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3016   SmallPtrSet<Instruction*, 16> ConsideredInsts;
3017   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
3018     return false;  // Has a non-memory, non-foldable use!
3019
3020   // Now that we know that all uses of this instruction are part of a chain of
3021   // computation involving only operations that could theoretically be folded
3022   // into a memory use, loop over each of these uses and see if they could
3023   // *actually* fold the instruction.
3024   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3025   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3026     Instruction *User = MemoryUses[i].first;
3027     unsigned OpNo = MemoryUses[i].second;
3028
3029     // Get the access type of this use.  If the use isn't a pointer, we don't
3030     // know what it accesses.
3031     Value *Address = User->getOperand(OpNo);
3032     if (!Address->getType()->isPointerTy())
3033       return false;
3034     Type *AddressAccessTy = Address->getType()->getPointerElementType();
3035
3036     // Do a match against the root of this address, ignoring profitability. This
3037     // will tell us if the addressing mode for the memory operation will
3038     // *actually* cover the shared instruction.
3039     ExtAddrMode Result;
3040     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3041         TPT.getRestorationPoint();
3042     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy,
3043                                   MemoryInst, Result, InsertedTruncs,
3044                                   PromotedInsts, TPT);
3045     Matcher.IgnoreProfitability = true;
3046     bool Success = Matcher.MatchAddr(Address, 0);
3047     (void)Success; assert(Success && "Couldn't select *anything*?");
3048
3049     // The match was to check the profitability, the changes made are not
3050     // part of the original matcher. Therefore, they should be dropped
3051     // otherwise the original matcher will not present the right state.
3052     TPT.rollback(LastKnownGood);
3053
3054     // If the match didn't cover I, then it won't be shared by it.
3055     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3056                   I) == MatchedAddrModeInsts.end())
3057       return false;
3058
3059     MatchedAddrModeInsts.clear();
3060   }
3061
3062   return true;
3063 }
3064
3065 } // end anonymous namespace
3066
3067 /// IsNonLocalValue - Return true if the specified values are defined in a
3068 /// different basic block than BB.
3069 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3070   if (Instruction *I = dyn_cast<Instruction>(V))
3071     return I->getParent() != BB;
3072   return false;
3073 }
3074
3075 /// OptimizeMemoryInst - Load and Store Instructions often have
3076 /// addressing modes that can do significant amounts of computation.  As such,
3077 /// instruction selection will try to get the load or store to do as much
3078 /// computation as possible for the program.  The problem is that isel can only
3079 /// see within a single block.  As such, we sink as much legal addressing mode
3080 /// stuff into the block as possible.
3081 ///
3082 /// This method is used to optimize both load/store and inline asms with memory
3083 /// operands.
3084 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
3085                                         Type *AccessTy) {
3086   Value *Repl = Addr;
3087
3088   // Try to collapse single-value PHI nodes.  This is necessary to undo
3089   // unprofitable PRE transformations.
3090   SmallVector<Value*, 8> worklist;
3091   SmallPtrSet<Value*, 16> Visited;
3092   worklist.push_back(Addr);
3093
3094   // Use a worklist to iteratively look through PHI nodes, and ensure that
3095   // the addressing mode obtained from the non-PHI roots of the graph
3096   // are equivalent.
3097   Value *Consensus = nullptr;
3098   unsigned NumUsesConsensus = 0;
3099   bool IsNumUsesConsensusValid = false;
3100   SmallVector<Instruction*, 16> AddrModeInsts;
3101   ExtAddrMode AddrMode;
3102   TypePromotionTransaction TPT;
3103   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3104       TPT.getRestorationPoint();
3105   while (!worklist.empty()) {
3106     Value *V = worklist.back();
3107     worklist.pop_back();
3108
3109     // Break use-def graph loops.
3110     if (!Visited.insert(V).second) {
3111       Consensus = nullptr;
3112       break;
3113     }
3114
3115     // For a PHI node, push all of its incoming values.
3116     if (PHINode *P = dyn_cast<PHINode>(V)) {
3117       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
3118         worklist.push_back(P->getIncomingValue(i));
3119       continue;
3120     }
3121
3122     // For non-PHIs, determine the addressing mode being computed.
3123     SmallVector<Instruction*, 16> NewAddrModeInsts;
3124     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
3125         V, AccessTy, MemoryInst, NewAddrModeInsts, *TM, InsertedTruncsSet,
3126         PromotedInsts, TPT);
3127
3128     // This check is broken into two cases with very similar code to avoid using
3129     // getNumUses() as much as possible. Some values have a lot of uses, so
3130     // calling getNumUses() unconditionally caused a significant compile-time
3131     // regression.
3132     if (!Consensus) {
3133       Consensus = V;
3134       AddrMode = NewAddrMode;
3135       AddrModeInsts = NewAddrModeInsts;
3136       continue;
3137     } else if (NewAddrMode == AddrMode) {
3138       if (!IsNumUsesConsensusValid) {
3139         NumUsesConsensus = Consensus->getNumUses();
3140         IsNumUsesConsensusValid = true;
3141       }
3142
3143       // Ensure that the obtained addressing mode is equivalent to that obtained
3144       // for all other roots of the PHI traversal.  Also, when choosing one
3145       // such root as representative, select the one with the most uses in order
3146       // to keep the cost modeling heuristics in AddressingModeMatcher
3147       // applicable.
3148       unsigned NumUses = V->getNumUses();
3149       if (NumUses > NumUsesConsensus) {
3150         Consensus = V;
3151         NumUsesConsensus = NumUses;
3152         AddrModeInsts = NewAddrModeInsts;
3153       }
3154       continue;
3155     }
3156
3157     Consensus = nullptr;
3158     break;
3159   }
3160
3161   // If the addressing mode couldn't be determined, or if multiple different
3162   // ones were determined, bail out now.
3163   if (!Consensus) {
3164     TPT.rollback(LastKnownGood);
3165     return false;
3166   }
3167   TPT.commit();
3168
3169   // Check to see if any of the instructions supersumed by this addr mode are
3170   // non-local to I's BB.
3171   bool AnyNonLocal = false;
3172   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
3173     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
3174       AnyNonLocal = true;
3175       break;
3176     }
3177   }
3178
3179   // If all the instructions matched are already in this BB, don't do anything.
3180   if (!AnyNonLocal) {
3181     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
3182     return false;
3183   }
3184
3185   // Insert this computation right after this user.  Since our caller is
3186   // scanning from the top of the BB to the bottom, reuse of the expr are
3187   // guaranteed to happen later.
3188   IRBuilder<> Builder(MemoryInst);
3189
3190   // Now that we determined the addressing expression we want to use and know
3191   // that we have to sink it into this block.  Check to see if we have already
3192   // done this for some other load/store instr in this block.  If so, reuse the
3193   // computation.
3194   Value *&SunkAddr = SunkAddrs[Addr];
3195   if (SunkAddr) {
3196     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
3197                  << *MemoryInst << "\n");
3198     if (SunkAddr->getType() != Addr->getType())
3199       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3200   } else if (AddrSinkUsingGEPs ||
3201              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
3202               TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3203                   ->useAA())) {
3204     // By default, we use the GEP-based method when AA is used later. This
3205     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3206     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3207                  << *MemoryInst << "\n");
3208     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
3209     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
3210
3211     // First, find the pointer.
3212     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3213       ResultPtr = AddrMode.BaseReg;
3214       AddrMode.BaseReg = nullptr;
3215     }
3216
3217     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3218       // We can't add more than one pointer together, nor can we scale a
3219       // pointer (both of which seem meaningless).
3220       if (ResultPtr || AddrMode.Scale != 1)
3221         return false;
3222
3223       ResultPtr = AddrMode.ScaledReg;
3224       AddrMode.Scale = 0;
3225     }
3226
3227     if (AddrMode.BaseGV) {
3228       if (ResultPtr)
3229         return false;
3230
3231       ResultPtr = AddrMode.BaseGV;
3232     }
3233
3234     // If the real base value actually came from an inttoptr, then the matcher
3235     // will look through it and provide only the integer value. In that case,
3236     // use it here.
3237     if (!ResultPtr && AddrMode.BaseReg) {
3238       ResultPtr =
3239         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
3240       AddrMode.BaseReg = nullptr;
3241     } else if (!ResultPtr && AddrMode.Scale == 1) {
3242       ResultPtr =
3243         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3244       AddrMode.Scale = 0;
3245     }
3246
3247     if (!ResultPtr &&
3248         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3249       SunkAddr = Constant::getNullValue(Addr->getType());
3250     } else if (!ResultPtr) {
3251       return false;
3252     } else {
3253       Type *I8PtrTy =
3254         Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3255
3256       // Start with the base register. Do this first so that subsequent address
3257       // matching finds it last, which will prevent it from trying to match it
3258       // as the scaled value in case it happens to be a mul. That would be
3259       // problematic if we've sunk a different mul for the scale, because then
3260       // we'd end up sinking both muls.
3261       if (AddrMode.BaseReg) {
3262         Value *V = AddrMode.BaseReg;
3263         if (V->getType() != IntPtrTy)
3264           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3265
3266         ResultIndex = V;
3267       }
3268
3269       // Add the scale value.
3270       if (AddrMode.Scale) {
3271         Value *V = AddrMode.ScaledReg;
3272         if (V->getType() == IntPtrTy) {
3273           // done.
3274         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3275                    cast<IntegerType>(V->getType())->getBitWidth()) {
3276           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3277         } else {
3278           // It is only safe to sign extend the BaseReg if we know that the math
3279           // required to create it did not overflow before we extend it. Since
3280           // the original IR value was tossed in favor of a constant back when
3281           // the AddrMode was created we need to bail out gracefully if widths
3282           // do not match instead of extending it.
3283           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3284           if (I && (ResultIndex != AddrMode.BaseReg))
3285             I->eraseFromParent();
3286           return false;
3287         }
3288
3289         if (AddrMode.Scale != 1)
3290           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3291                                 "sunkaddr");
3292         if (ResultIndex)
3293           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3294         else
3295           ResultIndex = V;
3296       }
3297
3298       // Add in the Base Offset if present.
3299       if (AddrMode.BaseOffs) {
3300         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3301         if (ResultIndex) {
3302           // We need to add this separately from the scale above to help with
3303           // SDAG consecutive load/store merging.
3304           if (ResultPtr->getType() != I8PtrTy)
3305             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3306           ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3307         }
3308
3309         ResultIndex = V;
3310       }
3311
3312       if (!ResultIndex) {
3313         SunkAddr = ResultPtr;
3314       } else {
3315         if (ResultPtr->getType() != I8PtrTy)
3316           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3317         SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3318       }
3319
3320       if (SunkAddr->getType() != Addr->getType())
3321         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3322     }
3323   } else {
3324     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3325                  << *MemoryInst << "\n");
3326     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
3327     Value *Result = nullptr;
3328
3329     // Start with the base register. Do this first so that subsequent address
3330     // matching finds it last, which will prevent it from trying to match it
3331     // as the scaled value in case it happens to be a mul. That would be
3332     // problematic if we've sunk a different mul for the scale, because then
3333     // we'd end up sinking both muls.
3334     if (AddrMode.BaseReg) {
3335       Value *V = AddrMode.BaseReg;
3336       if (V->getType()->isPointerTy())
3337         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3338       if (V->getType() != IntPtrTy)
3339         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3340       Result = V;
3341     }
3342
3343     // Add the scale value.
3344     if (AddrMode.Scale) {
3345       Value *V = AddrMode.ScaledReg;
3346       if (V->getType() == IntPtrTy) {
3347         // done.
3348       } else if (V->getType()->isPointerTy()) {
3349         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3350       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3351                  cast<IntegerType>(V->getType())->getBitWidth()) {
3352         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3353       } else {
3354         // It is only safe to sign extend the BaseReg if we know that the math
3355         // required to create it did not overflow before we extend it. Since
3356         // the original IR value was tossed in favor of a constant back when
3357         // the AddrMode was created we need to bail out gracefully if widths
3358         // do not match instead of extending it.
3359         Instruction *I = dyn_cast_or_null<Instruction>(Result);
3360         if (I && (Result != AddrMode.BaseReg))
3361           I->eraseFromParent();
3362         return false;
3363       }
3364       if (AddrMode.Scale != 1)
3365         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3366                               "sunkaddr");
3367       if (Result)
3368         Result = Builder.CreateAdd(Result, V, "sunkaddr");
3369       else
3370         Result = V;
3371     }
3372
3373     // Add in the BaseGV if present.
3374     if (AddrMode.BaseGV) {
3375       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
3376       if (Result)
3377         Result = Builder.CreateAdd(Result, V, "sunkaddr");
3378       else
3379         Result = V;
3380     }
3381
3382     // Add in the Base Offset if present.
3383     if (AddrMode.BaseOffs) {
3384       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3385       if (Result)
3386         Result = Builder.CreateAdd(Result, V, "sunkaddr");
3387       else
3388         Result = V;
3389     }
3390
3391     if (!Result)
3392       SunkAddr = Constant::getNullValue(Addr->getType());
3393     else
3394       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
3395   }
3396
3397   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
3398
3399   // If we have no uses, recursively delete the value and all dead instructions
3400   // using it.
3401   if (Repl->use_empty()) {
3402     // This can cause recursive deletion, which can invalidate our iterator.
3403     // Use a WeakVH to hold onto it in case this happens.
3404     WeakVH IterHandle(CurInstIterator);
3405     BasicBlock *BB = CurInstIterator->getParent();
3406
3407     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
3408
3409     if (IterHandle != CurInstIterator) {
3410       // If the iterator instruction was recursively deleted, start over at the
3411       // start of the block.
3412       CurInstIterator = BB->begin();
3413       SunkAddrs.clear();
3414     }
3415   }
3416   ++NumMemoryInsts;
3417   return true;
3418 }
3419
3420 /// OptimizeInlineAsmInst - If there are any memory operands, use
3421 /// OptimizeMemoryInst to sink their address computing into the block when
3422 /// possible / profitable.
3423 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
3424   bool MadeChange = false;
3425
3426   const TargetRegisterInfo *TRI =
3427       TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
3428   TargetLowering::AsmOperandInfoVector
3429     TargetConstraints = TLI->ParseConstraints(TRI, CS);
3430   unsigned ArgNo = 0;
3431   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3432     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3433
3434     // Compute the constraint code and ConstraintType to use.
3435     TLI->ComputeConstraintToUse(OpInfo, SDValue());
3436
3437     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3438         OpInfo.isIndirect) {
3439       Value *OpVal = CS->getArgOperand(ArgNo++);
3440       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
3441     } else if (OpInfo.Type == InlineAsm::isInput)
3442       ArgNo++;
3443   }
3444
3445   return MadeChange;
3446 }
3447
3448 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3449 /// sign extensions.
3450 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3451   assert(!Inst->use_empty() && "Input must have at least one use");
3452   const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3453   bool IsSExt = isa<SExtInst>(FirstUser);
3454   Type *ExtTy = FirstUser->getType();
3455   for (const User *U : Inst->users()) {
3456     const Instruction *UI = cast<Instruction>(U);
3457     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3458       return false;
3459     Type *CurTy = UI->getType();
3460     // Same input and output types: Same instruction after CSE.
3461     if (CurTy == ExtTy)
3462       continue;
3463
3464     // If IsSExt is true, we are in this situation:
3465     // a = Inst
3466     // b = sext ty1 a to ty2
3467     // c = sext ty1 a to ty3
3468     // Assuming ty2 is shorter than ty3, this could be turned into:
3469     // a = Inst
3470     // b = sext ty1 a to ty2
3471     // c = sext ty2 b to ty3
3472     // However, the last sext is not free.
3473     if (IsSExt)
3474       return false;
3475
3476     // This is a ZExt, maybe this is free to extend from one type to another.
3477     // In that case, we would not account for a different use.
3478     Type *NarrowTy;
3479     Type *LargeTy;
3480     if (ExtTy->getScalarType()->getIntegerBitWidth() >
3481         CurTy->getScalarType()->getIntegerBitWidth()) {
3482       NarrowTy = CurTy;
3483       LargeTy = ExtTy;
3484     } else {
3485       NarrowTy = ExtTy;
3486       LargeTy = CurTy;
3487     }
3488
3489     if (!TLI.isZExtFree(NarrowTy, LargeTy))
3490       return false;
3491   }
3492   // All uses are the same or can be derived from one another for free.
3493   return true;
3494 }
3495
3496 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
3497 /// load instruction.
3498 /// If an ext(load) can be formed, it is returned via \p LI for the load
3499 /// and \p Inst for the extension.
3500 /// Otherwise LI == nullptr and Inst == nullptr.
3501 /// When some promotion happened, \p TPT contains the proper state to
3502 /// revert them.
3503 ///
3504 /// \return true when promoting was necessary to expose the ext(load)
3505 /// opportunity, false otherwise.
3506 ///
3507 /// Example:
3508 /// \code
3509 /// %ld = load i32* %addr
3510 /// %add = add nuw i32 %ld, 4
3511 /// %zext = zext i32 %add to i64
3512 /// \endcode
3513 /// =>
3514 /// \code
3515 /// %ld = load i32* %addr
3516 /// %zext = zext i32 %ld to i64
3517 /// %add = add nuw i64 %zext, 4
3518 /// \encode
3519 /// Thanks to the promotion, we can match zext(load i32*) to i64.
3520 bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3521                                     LoadInst *&LI, Instruction *&Inst,
3522                                     const SmallVectorImpl<Instruction *> &Exts,
3523                                     unsigned CreatedInstsCost = 0) {
3524   // Iterate over all the extensions to see if one form an ext(load).
3525   for (auto I : Exts) {
3526     // Check if we directly have ext(load).
3527     if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3528       Inst = I;
3529       // No promotion happened here.
3530       return false;
3531     }
3532     // Check whether or not we want to do any promotion.
3533     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3534       continue;
3535     // Get the action to perform the promotion.
3536     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3537         I, InsertedTruncsSet, *TLI, PromotedInsts);
3538     // Check if we can promote.
3539     if (!TPH)
3540       continue;
3541     // Save the current state.
3542     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3543         TPT.getRestorationPoint();
3544     SmallVector<Instruction *, 4> NewExts;
3545     unsigned NewCreatedInstsCost = 0;
3546     unsigned ExtCost = !TLI->isExtFree(I);
3547     // Promote.
3548     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3549                              &NewExts, nullptr, *TLI);
3550     assert(PromotedVal &&
3551            "TypePromotionHelper should have filtered out those cases");
3552
3553     // We would be able to merge only one extension in a load.
3554     // Therefore, if we have more than 1 new extension we heuristically
3555     // cut this search path, because it means we degrade the code quality.
3556     // With exactly 2, the transformation is neutral, because we will merge
3557     // one extension but leave one. However, we optimistically keep going,
3558     // because the new extension may be removed too.
3559     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3560     TotalCreatedInstsCost -= ExtCost;
3561     if (!StressExtLdPromotion &&
3562         (TotalCreatedInstsCost > 1 ||
3563          !isPromotedInstructionLegal(*TLI, PromotedVal))) {
3564       // The promotion is not profitable, rollback to the previous state.
3565       TPT.rollback(LastKnownGood);
3566       continue;
3567     }
3568     // The promotion is profitable.
3569     // Check if it exposes an ext(load).
3570     (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
3571     if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
3572                // If we have created a new extension, i.e., now we have two
3573                // extensions. We must make sure one of them is merged with
3574                // the load, otherwise we may degrade the code quality.
3575                (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3576       // Promotion happened.
3577       return true;
3578     // If this does not help to expose an ext(load) then, rollback.
3579     TPT.rollback(LastKnownGood);
3580   }
3581   // None of the extension can form an ext(load).
3582   LI = nullptr;
3583   Inst = nullptr;
3584   return false;
3585 }
3586
3587 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3588 /// basic block as the load, unless conditions are unfavorable. This allows
3589 /// SelectionDAG to fold the extend into the load.
3590 /// \p I[in/out] the extension may be modified during the process if some
3591 /// promotions apply.
3592 ///
3593 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3594   // Try to promote a chain of computation if it allows to form
3595   // an extended load.
3596   TypePromotionTransaction TPT;
3597   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3598     TPT.getRestorationPoint();
3599   SmallVector<Instruction *, 1> Exts;
3600   Exts.push_back(I);
3601   // Look for a load being extended.
3602   LoadInst *LI = nullptr;
3603   Instruction *OldExt = I;
3604   bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3605   if (!LI || !I) {
3606     assert(!HasPromoted && !LI && "If we did not match any load instruction "
3607                                   "the code must remain the same");
3608     I = OldExt;
3609     return false;
3610   }
3611
3612   // If they're already in the same block, there's nothing to do.
3613   // Make the cheap checks first if we did not promote.
3614   // If we promoted, we need to check if it is indeed profitable.
3615   if (!HasPromoted && LI->getParent() == I->getParent())
3616     return false;
3617
3618   EVT VT = TLI->getValueType(I->getType());
3619   EVT LoadVT = TLI->getValueType(LI->getType());
3620
3621   // If the load has other users and the truncate is not free, this probably
3622   // isn't worthwhile.
3623   if (!LI->hasOneUse() && TLI &&
3624       (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
3625       !TLI->isTruncateFree(I->getType(), LI->getType())) {
3626     I = OldExt;
3627     TPT.rollback(LastKnownGood);
3628     return false;
3629   }
3630
3631   // Check whether the target supports casts folded into loads.
3632   unsigned LType;
3633   if (isa<ZExtInst>(I))
3634     LType = ISD::ZEXTLOAD;
3635   else {
3636     assert(isa<SExtInst>(I) && "Unexpected ext type!");
3637     LType = ISD::SEXTLOAD;
3638   }
3639   if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
3640     I = OldExt;
3641     TPT.rollback(LastKnownGood);
3642     return false;
3643   }
3644
3645   // Move the extend into the same block as the load, so that SelectionDAG
3646   // can fold it.
3647   TPT.commit();
3648   I->removeFromParent();
3649   I->insertAfter(LI);
3650   ++NumExtsMoved;
3651   return true;
3652 }
3653
3654 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3655   BasicBlock *DefBB = I->getParent();
3656
3657   // If the result of a {s|z}ext and its source are both live out, rewrite all
3658   // other uses of the source with result of extension.
3659   Value *Src = I->getOperand(0);
3660   if (Src->hasOneUse())
3661     return false;
3662
3663   // Only do this xform if truncating is free.
3664   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
3665     return false;
3666
3667   // Only safe to perform the optimization if the source is also defined in
3668   // this block.
3669   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
3670     return false;
3671
3672   bool DefIsLiveOut = false;
3673   for (User *U : I->users()) {
3674     Instruction *UI = cast<Instruction>(U);
3675
3676     // Figure out which BB this ext is used in.
3677     BasicBlock *UserBB = UI->getParent();
3678     if (UserBB == DefBB) continue;
3679     DefIsLiveOut = true;
3680     break;
3681   }
3682   if (!DefIsLiveOut)
3683     return false;
3684
3685   // Make sure none of the uses are PHI nodes.
3686   for (User *U : Src->users()) {
3687     Instruction *UI = cast<Instruction>(U);
3688     BasicBlock *UserBB = UI->getParent();
3689     if (UserBB == DefBB) continue;
3690     // Be conservative. We don't want this xform to end up introducing
3691     // reloads just before load / store instructions.
3692     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
3693       return false;
3694   }
3695
3696   // InsertedTruncs - Only insert one trunc in each block once.
3697   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3698
3699   bool MadeChange = false;
3700   for (Use &U : Src->uses()) {
3701     Instruction *User = cast<Instruction>(U.getUser());
3702
3703     // Figure out which BB this ext is used in.
3704     BasicBlock *UserBB = User->getParent();
3705     if (UserBB == DefBB) continue;
3706
3707     // Both src and def are live in this block. Rewrite the use.
3708     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3709
3710     if (!InsertedTrunc) {
3711       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3712       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3713       InsertedTruncsSet.insert(InsertedTrunc);
3714     }
3715
3716     // Replace a use of the {s|z}ext source with a use of the result.
3717     U = InsertedTrunc;
3718     ++NumExtUses;
3719     MadeChange = true;
3720   }
3721
3722   return MadeChange;
3723 }
3724
3725 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3726 /// turned into an explicit branch.
3727 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3728   // FIXME: This should use the same heuristics as IfConversion to determine
3729   // whether a select is better represented as a branch.  This requires that
3730   // branch probability metadata is preserved for the select, which is not the
3731   // case currently.
3732
3733   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3734
3735   // If the branch is predicted right, an out of order CPU can avoid blocking on
3736   // the compare.  Emit cmovs on compares with a memory operand as branches to
3737   // avoid stalls on the load from memory.  If the compare has more than one use
3738   // there's probably another cmov or setcc around so it's not worth emitting a
3739   // branch.
3740   if (!Cmp)
3741     return false;
3742
3743   Value *CmpOp0 = Cmp->getOperand(0);
3744   Value *CmpOp1 = Cmp->getOperand(1);
3745
3746   // We check that the memory operand has one use to avoid uses of the loaded
3747   // value directly after the compare, making branches unprofitable.
3748   return Cmp->hasOneUse() &&
3749          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3750           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3751 }
3752
3753
3754 /// If we have a SelectInst that will likely profit from branch prediction,
3755 /// turn it into a branch.
3756 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3757   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3758
3759   // Can we convert the 'select' to CF ?
3760   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3761     return false;
3762
3763   TargetLowering::SelectSupportKind SelectKind;
3764   if (VectorCond)
3765     SelectKind = TargetLowering::VectorMaskSelect;
3766   else if (SI->getType()->isVectorTy())
3767     SelectKind = TargetLowering::ScalarCondVectorVal;
3768   else
3769     SelectKind = TargetLowering::ScalarValSelect;
3770
3771   // Do we have efficient codegen support for this kind of 'selects' ?
3772   if (TLI->isSelectSupported(SelectKind)) {
3773     // We have efficient codegen support for the select instruction.
3774     // Check if it is profitable to keep this 'select'.
3775     if (!TLI->isPredictableSelectExpensive() ||
3776         !isFormingBranchFromSelectProfitable(SI))
3777       return false;
3778   }
3779
3780   ModifiedDT = true;
3781
3782   // First, we split the block containing the select into 2 blocks.
3783   BasicBlock *StartBlock = SI->getParent();
3784   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3785   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3786
3787   // Create a new block serving as the landing pad for the branch.
3788   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3789                                              NextBlock->getParent(), NextBlock);
3790
3791   // Move the unconditional branch from the block with the select in it into our
3792   // landing pad block.
3793   StartBlock->getTerminator()->eraseFromParent();
3794   BranchInst::Create(NextBlock, SmallBlock);
3795
3796   // Insert the real conditional branch based on the original condition.
3797   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3798
3799   // The select itself is replaced with a PHI Node.
3800   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3801   PN->takeName(SI);
3802   PN->addIncoming(SI->getTrueValue(), StartBlock);
3803   PN->addIncoming(SI->getFalseValue(), SmallBlock);
3804   SI->replaceAllUsesWith(PN);
3805   SI->eraseFromParent();
3806
3807   // Instruct OptimizeBlock to skip to the next block.
3808   CurInstIterator = StartBlock->end();
3809   ++NumSelectsExpanded;
3810   return true;
3811 }
3812
3813 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3814   SmallVector<int, 16> Mask(SVI->getShuffleMask());
3815   int SplatElem = -1;
3816   for (unsigned i = 0; i < Mask.size(); ++i) {
3817     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3818       return false;
3819     SplatElem = Mask[i];
3820   }
3821
3822   return true;
3823 }
3824
3825 /// Some targets have expensive vector shifts if the lanes aren't all the same
3826 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3827 /// it's often worth sinking a shufflevector splat down to its use so that
3828 /// codegen can spot all lanes are identical.
3829 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3830   BasicBlock *DefBB = SVI->getParent();
3831
3832   // Only do this xform if variable vector shifts are particularly expensive.
3833   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3834     return false;
3835
3836   // We only expect better codegen by sinking a shuffle if we can recognise a
3837   // constant splat.
3838   if (!isBroadcastShuffle(SVI))
3839     return false;
3840
3841   // InsertedShuffles - Only insert a shuffle in each block once.
3842   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3843
3844   bool MadeChange = false;
3845   for (User *U : SVI->users()) {
3846     Instruction *UI = cast<Instruction>(U);
3847
3848     // Figure out which BB this ext is used in.
3849     BasicBlock *UserBB = UI->getParent();
3850     if (UserBB == DefBB) continue;
3851
3852     // For now only apply this when the splat is used by a shift instruction.
3853     if (!UI->isShift()) continue;
3854
3855     // Everything checks out, sink the shuffle if the user's block doesn't
3856     // already have a copy.
3857     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3858
3859     if (!InsertedShuffle) {
3860       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3861       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3862                                               SVI->getOperand(1),
3863                                               SVI->getOperand(2), "", InsertPt);
3864     }
3865
3866     UI->replaceUsesOfWith(SVI, InsertedShuffle);
3867     MadeChange = true;
3868   }
3869
3870   // If we removed all uses, nuke the shuffle.
3871   if (SVI->use_empty()) {
3872     SVI->eraseFromParent();
3873     MadeChange = true;
3874   }
3875
3876   return MadeChange;
3877 }
3878
3879 namespace {
3880 /// \brief Helper class to promote a scalar operation to a vector one.
3881 /// This class is used to move downward extractelement transition.
3882 /// E.g.,
3883 /// a = vector_op <2 x i32>
3884 /// b = extractelement <2 x i32> a, i32 0
3885 /// c = scalar_op b
3886 /// store c
3887 ///
3888 /// =>
3889 /// a = vector_op <2 x i32>
3890 /// c = vector_op a (equivalent to scalar_op on the related lane)
3891 /// * d = extractelement <2 x i32> c, i32 0
3892 /// * store d
3893 /// Assuming both extractelement and store can be combine, we get rid of the
3894 /// transition.
3895 class VectorPromoteHelper {
3896   /// Used to perform some checks on the legality of vector operations.
3897   const TargetLowering &TLI;
3898
3899   /// Used to estimated the cost of the promoted chain.
3900   const TargetTransformInfo &TTI;
3901
3902   /// The transition being moved downwards.
3903   Instruction *Transition;
3904   /// The sequence of instructions to be promoted.
3905   SmallVector<Instruction *, 4> InstsToBePromoted;
3906   /// Cost of combining a store and an extract.
3907   unsigned StoreExtractCombineCost;
3908   /// Instruction that will be combined with the transition.
3909   Instruction *CombineInst;
3910
3911   /// \brief The instruction that represents the current end of the transition.
3912   /// Since we are faking the promotion until we reach the end of the chain
3913   /// of computation, we need a way to get the current end of the transition.
3914   Instruction *getEndOfTransition() const {
3915     if (InstsToBePromoted.empty())
3916       return Transition;
3917     return InstsToBePromoted.back();
3918   }
3919
3920   /// \brief Return the index of the original value in the transition.
3921   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3922   /// c, is at index 0.
3923   unsigned getTransitionOriginalValueIdx() const {
3924     assert(isa<ExtractElementInst>(Transition) &&
3925            "Other kind of transitions are not supported yet");
3926     return 0;
3927   }
3928
3929   /// \brief Return the index of the index in the transition.
3930   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3931   /// is at index 1.
3932   unsigned getTransitionIdx() const {
3933     assert(isa<ExtractElementInst>(Transition) &&
3934            "Other kind of transitions are not supported yet");
3935     return 1;
3936   }
3937
3938   /// \brief Get the type of the transition.
3939   /// This is the type of the original value.
3940   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3941   /// transition is <2 x i32>.
3942   Type *getTransitionType() const {
3943     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3944   }
3945
3946   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3947   /// I.e., we have the following sequence:
3948   /// Def = Transition <ty1> a to <ty2>
3949   /// b = ToBePromoted <ty2> Def, ...
3950   /// =>
3951   /// b = ToBePromoted <ty1> a, ...
3952   /// Def = Transition <ty1> ToBePromoted to <ty2>
3953   void promoteImpl(Instruction *ToBePromoted);
3954
3955   /// \brief Check whether or not it is profitable to promote all the
3956   /// instructions enqueued to be promoted.
3957   bool isProfitableToPromote() {
3958     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3959     unsigned Index = isa<ConstantInt>(ValIdx)
3960                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
3961                          : -1;
3962     Type *PromotedType = getTransitionType();
3963
3964     StoreInst *ST = cast<StoreInst>(CombineInst);
3965     unsigned AS = ST->getPointerAddressSpace();
3966     unsigned Align = ST->getAlignment();
3967     // Check if this store is supported.
3968     if (!TLI.allowsMisalignedMemoryAccesses(
3969             TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
3970       // If this is not supported, there is no way we can combine
3971       // the extract with the store.
3972       return false;
3973     }
3974
3975     // The scalar chain of computation has to pay for the transition
3976     // scalar to vector.
3977     // The vector chain has to account for the combining cost.
3978     uint64_t ScalarCost =
3979         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3980     uint64_t VectorCost = StoreExtractCombineCost;
3981     for (const auto &Inst : InstsToBePromoted) {
3982       // Compute the cost.
3983       // By construction, all instructions being promoted are arithmetic ones.
3984       // Moreover, one argument is a constant that can be viewed as a splat
3985       // constant.
3986       Value *Arg0 = Inst->getOperand(0);
3987       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3988                             isa<ConstantFP>(Arg0);
3989       TargetTransformInfo::OperandValueKind Arg0OVK =
3990           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3991                          : TargetTransformInfo::OK_AnyValue;
3992       TargetTransformInfo::OperandValueKind Arg1OVK =
3993           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3994                           : TargetTransformInfo::OK_AnyValue;
3995       ScalarCost += TTI.getArithmeticInstrCost(
3996           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3997       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3998                                                Arg0OVK, Arg1OVK);
3999     }
4000     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4001                  << ScalarCost << "\nVector: " << VectorCost << '\n');
4002     return ScalarCost > VectorCost;
4003   }
4004
4005   /// \brief Generate a constant vector with \p Val with the same
4006   /// number of elements as the transition.
4007   /// \p UseSplat defines whether or not \p Val should be replicated
4008   /// accross the whole vector.
4009   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4010   /// otherwise we generate a vector with as many undef as possible:
4011   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4012   /// used at the index of the extract.
4013   Value *getConstantVector(Constant *Val, bool UseSplat) const {
4014     unsigned ExtractIdx = UINT_MAX;
4015     if (!UseSplat) {
4016       // If we cannot determine where the constant must be, we have to
4017       // use a splat constant.
4018       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4019       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4020         ExtractIdx = CstVal->getSExtValue();
4021       else
4022         UseSplat = true;
4023     }
4024
4025     unsigned End = getTransitionType()->getVectorNumElements();
4026     if (UseSplat)
4027       return ConstantVector::getSplat(End, Val);
4028
4029     SmallVector<Constant *, 4> ConstVec;
4030     UndefValue *UndefVal = UndefValue::get(Val->getType());
4031     for (unsigned Idx = 0; Idx != End; ++Idx) {
4032       if (Idx == ExtractIdx)
4033         ConstVec.push_back(Val);
4034       else
4035         ConstVec.push_back(UndefVal);
4036     }
4037     return ConstantVector::get(ConstVec);
4038   }
4039
4040   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4041   /// in \p Use can trigger undefined behavior.
4042   static bool canCauseUndefinedBehavior(const Instruction *Use,
4043                                         unsigned OperandIdx) {
4044     // This is not safe to introduce undef when the operand is on
4045     // the right hand side of a division-like instruction.
4046     if (OperandIdx != 1)
4047       return false;
4048     switch (Use->getOpcode()) {
4049     default:
4050       return false;
4051     case Instruction::SDiv:
4052     case Instruction::UDiv:
4053     case Instruction::SRem:
4054     case Instruction::URem:
4055       return true;
4056     case Instruction::FDiv:
4057     case Instruction::FRem:
4058       return !Use->hasNoNaNs();
4059     }
4060     llvm_unreachable(nullptr);
4061   }
4062
4063 public:
4064   VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
4065                       Instruction *Transition, unsigned CombineCost)
4066       : TLI(TLI), TTI(TTI), Transition(Transition),
4067         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4068     assert(Transition && "Do not know how to promote null");
4069   }
4070
4071   /// \brief Check if we can promote \p ToBePromoted to \p Type.
4072   bool canPromote(const Instruction *ToBePromoted) const {
4073     // We could support CastInst too.
4074     return isa<BinaryOperator>(ToBePromoted);
4075   }
4076
4077   /// \brief Check if it is profitable to promote \p ToBePromoted
4078   /// by moving downward the transition through.
4079   bool shouldPromote(const Instruction *ToBePromoted) const {
4080     // Promote only if all the operands can be statically expanded.
4081     // Indeed, we do not want to introduce any new kind of transitions.
4082     for (const Use &U : ToBePromoted->operands()) {
4083       const Value *Val = U.get();
4084       if (Val == getEndOfTransition()) {
4085         // If the use is a division and the transition is on the rhs,
4086         // we cannot promote the operation, otherwise we may create a
4087         // division by zero.
4088         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4089           return false;
4090         continue;
4091       }
4092       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4093           !isa<ConstantFP>(Val))
4094         return false;
4095     }
4096     // Check that the resulting operation is legal.
4097     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4098     if (!ISDOpcode)
4099       return false;
4100     return StressStoreExtract ||
4101            TLI.isOperationLegalOrCustom(
4102                ISDOpcode, TLI.getValueType(getTransitionType(), true));
4103   }
4104
4105   /// \brief Check whether or not \p Use can be combined
4106   /// with the transition.
4107   /// I.e., is it possible to do Use(Transition) => AnotherUse?
4108   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4109
4110   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4111   void enqueueForPromotion(Instruction *ToBePromoted) {
4112     InstsToBePromoted.push_back(ToBePromoted);
4113   }
4114
4115   /// \brief Set the instruction that will be combined with the transition.
4116   void recordCombineInstruction(Instruction *ToBeCombined) {
4117     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4118     CombineInst = ToBeCombined;
4119   }
4120
4121   /// \brief Promote all the instructions enqueued for promotion if it is
4122   /// is profitable.
4123   /// \return True if the promotion happened, false otherwise.
4124   bool promote() {
4125     // Check if there is something to promote.
4126     // Right now, if we do not have anything to combine with,
4127     // we assume the promotion is not profitable.
4128     if (InstsToBePromoted.empty() || !CombineInst)
4129       return false;
4130
4131     // Check cost.
4132     if (!StressStoreExtract && !isProfitableToPromote())
4133       return false;
4134
4135     // Promote.
4136     for (auto &ToBePromoted : InstsToBePromoted)
4137       promoteImpl(ToBePromoted);
4138     InstsToBePromoted.clear();
4139     return true;
4140   }
4141 };
4142 } // End of anonymous namespace.
4143
4144 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4145   // At this point, we know that all the operands of ToBePromoted but Def
4146   // can be statically promoted.
4147   // For Def, we need to use its parameter in ToBePromoted:
4148   // b = ToBePromoted ty1 a
4149   // Def = Transition ty1 b to ty2
4150   // Move the transition down.
4151   // 1. Replace all uses of the promoted operation by the transition.
4152   // = ... b => = ... Def.
4153   assert(ToBePromoted->getType() == Transition->getType() &&
4154          "The type of the result of the transition does not match "
4155          "the final type");
4156   ToBePromoted->replaceAllUsesWith(Transition);
4157   // 2. Update the type of the uses.
4158   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4159   Type *TransitionTy = getTransitionType();
4160   ToBePromoted->mutateType(TransitionTy);
4161   // 3. Update all the operands of the promoted operation with promoted
4162   // operands.
4163   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4164   for (Use &U : ToBePromoted->operands()) {
4165     Value *Val = U.get();
4166     Value *NewVal = nullptr;
4167     if (Val == Transition)
4168       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4169     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4170              isa<ConstantFP>(Val)) {
4171       // Use a splat constant if it is not safe to use undef.
4172       NewVal = getConstantVector(
4173           cast<Constant>(Val),
4174           isa<UndefValue>(Val) ||
4175               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4176     } else
4177       llvm_unreachable("Did you modified shouldPromote and forgot to update "
4178                        "this?");
4179     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4180   }
4181   Transition->removeFromParent();
4182   Transition->insertAfter(ToBePromoted);
4183   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4184 }
4185
4186 /// Some targets can do store(extractelement) with one instruction.
4187 /// Try to push the extractelement towards the stores when the target
4188 /// has this feature and this is profitable.
4189 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4190   unsigned CombineCost = UINT_MAX;
4191   if (DisableStoreExtract || !TLI ||
4192       (!StressStoreExtract &&
4193        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4194                                        Inst->getOperand(1), CombineCost)))
4195     return false;
4196
4197   // At this point we know that Inst is a vector to scalar transition.
4198   // Try to move it down the def-use chain, until:
4199   // - We can combine the transition with its single use
4200   //   => we got rid of the transition.
4201   // - We escape the current basic block
4202   //   => we would need to check that we are moving it at a cheaper place and
4203   //      we do not do that for now.
4204   BasicBlock *Parent = Inst->getParent();
4205   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4206   VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
4207   // If the transition has more than one use, assume this is not going to be
4208   // beneficial.
4209   while (Inst->hasOneUse()) {
4210     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4211     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4212
4213     if (ToBePromoted->getParent() != Parent) {
4214       DEBUG(dbgs() << "Instruction to promote is in a different block ("
4215                    << ToBePromoted->getParent()->getName()
4216                    << ") than the transition (" << Parent->getName() << ").\n");
4217       return false;
4218     }
4219
4220     if (VPH.canCombine(ToBePromoted)) {
4221       DEBUG(dbgs() << "Assume " << *Inst << '\n'
4222                    << "will be combined with: " << *ToBePromoted << '\n');
4223       VPH.recordCombineInstruction(ToBePromoted);
4224       bool Changed = VPH.promote();
4225       NumStoreExtractExposed += Changed;
4226       return Changed;
4227     }
4228
4229     DEBUG(dbgs() << "Try promoting.\n");
4230     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4231       return false;
4232
4233     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4234
4235     VPH.enqueueForPromotion(ToBePromoted);
4236     Inst = ToBePromoted;
4237   }
4238   return false;
4239 }
4240
4241 bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
4242   if (PHINode *P = dyn_cast<PHINode>(I)) {
4243     // It is possible for very late stage optimizations (such as SimplifyCFG)
4244     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
4245     // trivial PHI, go ahead and zap it here.
4246     const DataLayout &DL = I->getModule()->getDataLayout();
4247     if (Value *V = SimplifyInstruction(P, DL, TLInfo, DT)) {
4248       P->replaceAllUsesWith(V);
4249       P->eraseFromParent();
4250       ++NumPHIsElim;
4251       return true;
4252     }
4253     return false;
4254   }
4255
4256   if (CastInst *CI = dyn_cast<CastInst>(I)) {
4257     // If the source of the cast is a constant, then this should have
4258     // already been constant folded.  The only reason NOT to constant fold
4259     // it is if something (e.g. LSR) was careful to place the constant
4260     // evaluation in a block other than then one that uses it (e.g. to hoist
4261     // the address of globals out of a loop).  If this is the case, we don't
4262     // want to forward-subst the cast.
4263     if (isa<Constant>(CI->getOperand(0)))
4264       return false;
4265
4266     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
4267       return true;
4268
4269     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
4270       /// Sink a zext or sext into its user blocks if the target type doesn't
4271       /// fit in one register
4272       if (TLI && TLI->getTypeAction(CI->getContext(),
4273                                     TLI->getValueType(CI->getType())) ==
4274                      TargetLowering::TypeExpandInteger) {
4275         return SinkCast(CI);
4276       } else {
4277         bool MadeChange = MoveExtToFormExtLoad(I);
4278         return MadeChange | OptimizeExtUses(I);
4279       }
4280     }
4281     return false;
4282   }
4283
4284   if (CmpInst *CI = dyn_cast<CmpInst>(I))
4285     if (!TLI || !TLI->hasMultipleConditionRegisters())
4286       return OptimizeCmpExpression(CI);
4287
4288   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4289     if (TLI)
4290       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
4291     return false;
4292   }
4293
4294   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4295     if (TLI)
4296       return OptimizeMemoryInst(I, SI->getOperand(1),
4297                                 SI->getOperand(0)->getType());
4298     return false;
4299   }
4300
4301   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4302
4303   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4304                 BinOp->getOpcode() == Instruction::LShr)) {
4305     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4306     if (TLI && CI && TLI->hasExtractBitsInsn())
4307       return OptimizeExtractBits(BinOp, CI, *TLI);
4308
4309     return false;
4310   }
4311
4312   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
4313     if (GEPI->hasAllZeroIndices()) {
4314       /// The GEP operand must be a pointer, so must its result -> BitCast
4315       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4316                                         GEPI->getName(), GEPI);
4317       GEPI->replaceAllUsesWith(NC);
4318       GEPI->eraseFromParent();
4319       ++NumGEPsElim;
4320       OptimizeInst(NC, ModifiedDT);
4321       return true;
4322     }
4323     return false;
4324   }
4325
4326   if (CallInst *CI = dyn_cast<CallInst>(I))
4327     return OptimizeCallInst(CI, ModifiedDT);
4328
4329   if (SelectInst *SI = dyn_cast<SelectInst>(I))
4330     return OptimizeSelectInst(SI);
4331
4332   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4333     return OptimizeShuffleVectorInst(SVI);
4334
4335   if (isa<ExtractElementInst>(I))
4336     return OptimizeExtractElementInst(I);
4337
4338   return false;
4339 }
4340
4341 // In this pass we look for GEP and cast instructions that are used
4342 // across basic blocks and rewrite them to improve basic-block-at-a-time
4343 // selection.
4344 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
4345   SunkAddrs.clear();
4346   bool MadeChange = false;
4347
4348   CurInstIterator = BB.begin();
4349   while (CurInstIterator != BB.end()) {
4350     MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4351     if (ModifiedDT)
4352       return true;
4353   }
4354   MadeChange |= DupRetToEnableTailCallOpts(&BB);
4355
4356   return MadeChange;
4357 }
4358
4359 // llvm.dbg.value is far away from the value then iSel may not be able
4360 // handle it properly. iSel will drop llvm.dbg.value if it can not
4361 // find a node corresponding to the value.
4362 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4363   bool MadeChange = false;
4364   for (BasicBlock &BB : F) {
4365     Instruction *PrevNonDbgInst = nullptr;
4366     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
4367       Instruction *Insn = BI++;
4368       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
4369       // Leave dbg.values that refer to an alloca alone. These
4370       // instrinsics describe the address of a variable (= the alloca)
4371       // being taken.  They should not be moved next to the alloca
4372       // (and to the beginning of the scope), but rather stay close to
4373       // where said address is used.
4374       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
4375         PrevNonDbgInst = Insn;
4376         continue;
4377       }
4378
4379       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4380       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4381         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4382         DVI->removeFromParent();
4383         if (isa<PHINode>(VI))
4384           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4385         else
4386           DVI->insertAfter(VI);
4387         MadeChange = true;
4388         ++NumDbgValueMoved;
4389       }
4390     }
4391   }
4392   return MadeChange;
4393 }
4394
4395 // If there is a sequence that branches based on comparing a single bit
4396 // against zero that can be combined into a single instruction, and the
4397 // target supports folding these into a single instruction, sink the
4398 // mask and compare into the branch uses. Do this before OptimizeBlock ->
4399 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4400 // searched for.
4401 bool CodeGenPrepare::sinkAndCmp(Function &F) {
4402   if (!EnableAndCmpSinking)
4403     return false;
4404   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4405     return false;
4406   bool MadeChange = false;
4407   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4408     BasicBlock *BB = I++;
4409
4410     // Does this BB end with the following?
4411     //   %andVal = and %val, #single-bit-set
4412     //   %icmpVal = icmp %andResult, 0
4413     //   br i1 %cmpVal label %dest1, label %dest2"
4414     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4415     if (!Brcc || !Brcc->isConditional())
4416       continue;
4417     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4418     if (!Cmp || Cmp->getParent() != BB)
4419       continue;
4420     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4421     if (!Zero || !Zero->isZero())
4422       continue;
4423     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4424     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4425       continue;
4426     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4427     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4428       continue;
4429     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4430
4431     // Push the "and; icmp" for any users that are conditional branches.
4432     // Since there can only be one branch use per BB, we don't need to keep
4433     // track of which BBs we insert into.
4434     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4435          UI != E; ) {
4436       Use &TheUse = *UI;
4437       // Find brcc use.
4438       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4439       ++UI;
4440       if (!BrccUser || !BrccUser->isConditional())
4441         continue;
4442       BasicBlock *UserBB = BrccUser->getParent();
4443       if (UserBB == BB) continue;
4444       DEBUG(dbgs() << "found Brcc use\n");
4445
4446       // Sink the "and; icmp" to use.
4447       MadeChange = true;
4448       BinaryOperator *NewAnd =
4449         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4450                                   BrccUser);
4451       CmpInst *NewCmp =
4452         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4453                         "", BrccUser);
4454       TheUse = NewCmp;
4455       ++NumAndCmpsMoved;
4456       DEBUG(BrccUser->getParent()->dump());
4457     }
4458   }
4459   return MadeChange;
4460 }
4461
4462 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
4463 /// success, or returns false if no or invalid metadata was found.
4464 static bool extractBranchMetadata(BranchInst *BI,
4465                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
4466   assert(BI->isConditional() &&
4467          "Looking for probabilities on unconditional branch?");
4468   auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4469   if (!ProfileData || ProfileData->getNumOperands() != 3)
4470     return false;
4471
4472   const auto *CITrue =
4473       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4474   const auto *CIFalse =
4475       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
4476   if (!CITrue || !CIFalse)
4477     return false;
4478
4479   ProbTrue = CITrue->getValue().getZExtValue();
4480   ProbFalse = CIFalse->getValue().getZExtValue();
4481
4482   return true;
4483 }
4484
4485 /// \brief Scale down both weights to fit into uint32_t.
4486 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4487   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4488   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4489   NewTrue = NewTrue / Scale;
4490   NewFalse = NewFalse / Scale;
4491 }
4492
4493 /// \brief Some targets prefer to split a conditional branch like:
4494 /// \code
4495 ///   %0 = icmp ne i32 %a, 0
4496 ///   %1 = icmp ne i32 %b, 0
4497 ///   %or.cond = or i1 %0, %1
4498 ///   br i1 %or.cond, label %TrueBB, label %FalseBB
4499 /// \endcode
4500 /// into multiple branch instructions like:
4501 /// \code
4502 ///   bb1:
4503 ///     %0 = icmp ne i32 %a, 0
4504 ///     br i1 %0, label %TrueBB, label %bb2
4505 ///   bb2:
4506 ///     %1 = icmp ne i32 %b, 0
4507 ///     br i1 %1, label %TrueBB, label %FalseBB
4508 /// \endcode
4509 /// This usually allows instruction selection to do even further optimizations
4510 /// and combine the compare with the branch instruction. Currently this is
4511 /// applied for targets which have "cheap" jump instructions.
4512 ///
4513 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4514 ///
4515 bool CodeGenPrepare::splitBranchCondition(Function &F) {
4516   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
4517     return false;
4518
4519   bool MadeChange = false;
4520   for (auto &BB : F) {
4521     // Does this BB end with the following?
4522     //   %cond1 = icmp|fcmp|binary instruction ...
4523     //   %cond2 = icmp|fcmp|binary instruction ...
4524     //   %cond.or = or|and i1 %cond1, cond2
4525     //   br i1 %cond.or label %dest1, label %dest2"
4526     BinaryOperator *LogicOp;
4527     BasicBlock *TBB, *FBB;
4528     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4529       continue;
4530
4531     unsigned Opc;
4532     Value *Cond1, *Cond2;
4533     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4534                              m_OneUse(m_Value(Cond2)))))
4535       Opc = Instruction::And;
4536     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4537                                  m_OneUse(m_Value(Cond2)))))
4538       Opc = Instruction::Or;
4539     else
4540       continue;
4541
4542     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4543         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
4544       continue;
4545
4546     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4547
4548     // Create a new BB.
4549     auto *InsertBefore = std::next(Function::iterator(BB))
4550         .getNodePtrUnchecked();
4551     auto TmpBB = BasicBlock::Create(BB.getContext(),
4552                                     BB.getName() + ".cond.split",
4553                                     BB.getParent(), InsertBefore);
4554
4555     // Update original basic block by using the first condition directly by the
4556     // branch instruction and removing the no longer needed and/or instruction.
4557     auto *Br1 = cast<BranchInst>(BB.getTerminator());
4558     Br1->setCondition(Cond1);
4559     LogicOp->eraseFromParent();
4560
4561     // Depending on the conditon we have to either replace the true or the false
4562     // successor of the original branch instruction.
4563     if (Opc == Instruction::And)
4564       Br1->setSuccessor(0, TmpBB);
4565     else
4566       Br1->setSuccessor(1, TmpBB);
4567
4568     // Fill in the new basic block.
4569     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
4570     if (auto *I = dyn_cast<Instruction>(Cond2)) {
4571       I->removeFromParent();
4572       I->insertBefore(Br2);
4573     }
4574
4575     // Update PHI nodes in both successors. The original BB needs to be
4576     // replaced in one succesor's PHI nodes, because the branch comes now from
4577     // the newly generated BB (NewBB). In the other successor we need to add one
4578     // incoming edge to the PHI nodes, because both branch instructions target
4579     // now the same successor. Depending on the original branch condition
4580     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4581     // we perfrom the correct update for the PHI nodes.
4582     // This doesn't change the successor order of the just created branch
4583     // instruction (or any other instruction).
4584     if (Opc == Instruction::Or)
4585       std::swap(TBB, FBB);
4586
4587     // Replace the old BB with the new BB.
4588     for (auto &I : *TBB) {
4589       PHINode *PN = dyn_cast<PHINode>(&I);
4590       if (!PN)
4591         break;
4592       int i;
4593       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4594         PN->setIncomingBlock(i, TmpBB);
4595     }
4596
4597     // Add another incoming edge form the new BB.
4598     for (auto &I : *FBB) {
4599       PHINode *PN = dyn_cast<PHINode>(&I);
4600       if (!PN)
4601         break;
4602       auto *Val = PN->getIncomingValueForBlock(&BB);
4603       PN->addIncoming(Val, TmpBB);
4604     }
4605
4606     // Update the branch weights (from SelectionDAGBuilder::
4607     // FindMergedConditions).
4608     if (Opc == Instruction::Or) {
4609       // Codegen X | Y as:
4610       // BB1:
4611       //   jmp_if_X TBB
4612       //   jmp TmpBB
4613       // TmpBB:
4614       //   jmp_if_Y TBB
4615       //   jmp FBB
4616       //
4617
4618       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4619       // The requirement is that
4620       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4621       //     = TrueProb for orignal BB.
4622       // Assuming the orignal weights are A and B, one choice is to set BB1's
4623       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4624       // assumes that
4625       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4626       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4627       // TmpBB, but the math is more complicated.
4628       uint64_t TrueWeight, FalseWeight;
4629       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4630         uint64_t NewTrueWeight = TrueWeight;
4631         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4632         scaleWeights(NewTrueWeight, NewFalseWeight);
4633         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4634                          .createBranchWeights(TrueWeight, FalseWeight));
4635
4636         NewTrueWeight = TrueWeight;
4637         NewFalseWeight = 2 * FalseWeight;
4638         scaleWeights(NewTrueWeight, NewFalseWeight);
4639         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4640                          .createBranchWeights(TrueWeight, FalseWeight));
4641       }
4642     } else {
4643       // Codegen X & Y as:
4644       // BB1:
4645       //   jmp_if_X TmpBB
4646       //   jmp FBB
4647       // TmpBB:
4648       //   jmp_if_Y TBB
4649       //   jmp FBB
4650       //
4651       //  This requires creation of TmpBB after CurBB.
4652
4653       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4654       // The requirement is that
4655       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4656       //     = FalseProb for orignal BB.
4657       // Assuming the orignal weights are A and B, one choice is to set BB1's
4658       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4659       // assumes that
4660       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4661       uint64_t TrueWeight, FalseWeight;
4662       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4663         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4664         uint64_t NewFalseWeight = FalseWeight;
4665         scaleWeights(NewTrueWeight, NewFalseWeight);
4666         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4667                          .createBranchWeights(TrueWeight, FalseWeight));
4668
4669         NewTrueWeight = 2 * TrueWeight;
4670         NewFalseWeight = FalseWeight;
4671         scaleWeights(NewTrueWeight, NewFalseWeight);
4672         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4673                          .createBranchWeights(TrueWeight, FalseWeight));
4674       }
4675     }
4676
4677     // Request DOM Tree update.
4678     // Note: No point in getting fancy here, since the DT info is never
4679     // available to CodeGenPrepare and the existing update code is broken
4680     // anyways.
4681     ModifiedDT = true;
4682
4683     MadeChange = true;
4684
4685     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4686           TmpBB->dump());
4687   }
4688   return MadeChange;
4689 }