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