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