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