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