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