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