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