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