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