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