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