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