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       SmallVector<Value*, 2> PtrOps;
2037       Type *AccessTy;
2038       if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2039         while (!PtrOps.empty()) {
2040           Value *PtrVal = PtrOps.pop_back_val();
2041           unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2042           if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2043             return true;
2044         }
2045     }
2046   }
2047 
2048   // From here on out we're working with named functions.
2049   if (!CI->getCalledFunction()) return false;
2050 
2051   // Lower all default uses of _chk calls.  This is very similar
2052   // to what InstCombineCalls does, but here we are only lowering calls
2053   // to fortified library functions (e.g. __memcpy_chk) that have the default
2054   // "don't know" as the objectsize.  Anything else should be left alone.
2055   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2056   if (Value *V = Simplifier.optimizeCall(CI)) {
2057     CI->replaceAllUsesWith(V);
2058     CI->eraseFromParent();
2059     return true;
2060   }
2061   return false;
2062 }
2063 
2064 /// Look for opportunities to duplicate return instructions to the predecessor
2065 /// to enable tail call optimizations. The case it is currently looking for is:
2066 /// @code
2067 /// bb0:
2068 ///   %tmp0 = tail call i32 @f0()
2069 ///   br label %return
2070 /// bb1:
2071 ///   %tmp1 = tail call i32 @f1()
2072 ///   br label %return
2073 /// bb2:
2074 ///   %tmp2 = tail call i32 @f2()
2075 ///   br label %return
2076 /// return:
2077 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2078 ///   ret i32 %retval
2079 /// @endcode
2080 ///
2081 /// =>
2082 ///
2083 /// @code
2084 /// bb0:
2085 ///   %tmp0 = tail call i32 @f0()
2086 ///   ret i32 %tmp0
2087 /// bb1:
2088 ///   %tmp1 = tail call i32 @f1()
2089 ///   ret i32 %tmp1
2090 /// bb2:
2091 ///   %tmp2 = tail call i32 @f2()
2092 ///   ret i32 %tmp2
2093 /// @endcode
2094 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
2095   if (!TLI)
2096     return false;
2097 
2098   ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2099   if (!RetI)
2100     return false;
2101 
2102   PHINode *PN = nullptr;
2103   BitCastInst *BCI = nullptr;
2104   Value *V = RetI->getReturnValue();
2105   if (V) {
2106     BCI = dyn_cast<BitCastInst>(V);
2107     if (BCI)
2108       V = BCI->getOperand(0);
2109 
2110     PN = dyn_cast<PHINode>(V);
2111     if (!PN)
2112       return false;
2113   }
2114 
2115   if (PN && PN->getParent() != BB)
2116     return false;
2117 
2118   // Make sure there are no instructions between the PHI and return, or that the
2119   // return is the first instruction in the block.
2120   if (PN) {
2121     BasicBlock::iterator BI = BB->begin();
2122     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
2123     if (&*BI == BCI)
2124       // Also skip over the bitcast.
2125       ++BI;
2126     if (&*BI != RetI)
2127       return false;
2128   } else {
2129     BasicBlock::iterator BI = BB->begin();
2130     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2131     if (&*BI != RetI)
2132       return false;
2133   }
2134 
2135   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2136   /// call.
2137   const Function *F = BB->getParent();
2138   SmallVector<CallInst*, 4> TailCalls;
2139   if (PN) {
2140     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2141       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2142       // Make sure the phi value is indeed produced by the tail call.
2143       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2144           TLI->mayBeEmittedAsTailCall(CI) &&
2145           attributesPermitTailCall(F, CI, RetI, *TLI))
2146         TailCalls.push_back(CI);
2147     }
2148   } else {
2149     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
2150     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
2151       if (!VisitedBBs.insert(*PI).second)
2152         continue;
2153 
2154       BasicBlock::InstListType &InstList = (*PI)->getInstList();
2155       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2156       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
2157       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2158       if (RI == RE)
2159         continue;
2160 
2161       CallInst *CI = dyn_cast<CallInst>(&*RI);
2162       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2163           attributesPermitTailCall(F, CI, RetI, *TLI))
2164         TailCalls.push_back(CI);
2165     }
2166   }
2167 
2168   bool Changed = false;
2169   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2170     CallInst *CI = TailCalls[i];
2171     CallSite CS(CI);
2172 
2173     // Conservatively require the attributes of the call to match those of the
2174     // return. Ignore noalias because it doesn't affect the call sequence.
2175     AttributeSet CalleeAttrs = CS.getAttributes();
2176     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
2177           removeAttribute(Attribute::NoAlias) !=
2178         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
2179           removeAttribute(Attribute::NoAlias))
2180       continue;
2181 
2182     // Make sure the call instruction is followed by an unconditional branch to
2183     // the return block.
2184     BasicBlock *CallBB = CI->getParent();
2185     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2186     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2187       continue;
2188 
2189     // Duplicate the return into CallBB.
2190     (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
2191     ModifiedDT = Changed = true;
2192     ++NumRetsDup;
2193   }
2194 
2195   // If we eliminated all predecessors of the block, delete the block now.
2196   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
2197     BB->eraseFromParent();
2198 
2199   return Changed;
2200 }
2201 
2202 //===----------------------------------------------------------------------===//
2203 // Memory Optimization
2204 //===----------------------------------------------------------------------===//
2205 
2206 namespace {
2207 
2208 /// This is an extended version of TargetLowering::AddrMode
2209 /// which holds actual Value*'s for register values.
2210 struct ExtAddrMode : public TargetLowering::AddrMode {
2211   Value *BaseReg;
2212   Value *ScaledReg;
2213   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
2214   void print(raw_ostream &OS) const;
2215   void dump() const;
2216 
2217   bool operator==(const ExtAddrMode& O) const {
2218     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2219            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2220            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2221   }
2222 };
2223 
2224 #ifndef NDEBUG
2225 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2226   AM.print(OS);
2227   return OS;
2228 }
2229 #endif
2230 
2231 void ExtAddrMode::print(raw_ostream &OS) const {
2232   bool NeedPlus = false;
2233   OS << "[";
2234   if (BaseGV) {
2235     OS << (NeedPlus ? " + " : "")
2236        << "GV:";
2237     BaseGV->printAsOperand(OS, /*PrintType=*/false);
2238     NeedPlus = true;
2239   }
2240 
2241   if (BaseOffs) {
2242     OS << (NeedPlus ? " + " : "")
2243        << BaseOffs;
2244     NeedPlus = true;
2245   }
2246 
2247   if (BaseReg) {
2248     OS << (NeedPlus ? " + " : "")
2249        << "Base:";
2250     BaseReg->printAsOperand(OS, /*PrintType=*/false);
2251     NeedPlus = true;
2252   }
2253   if (Scale) {
2254     OS << (NeedPlus ? " + " : "")
2255        << Scale << "*";
2256     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2257   }
2258 
2259   OS << ']';
2260 }
2261 
2262 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2263 LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
2264   print(dbgs());
2265   dbgs() << '\n';
2266 }
2267 #endif
2268 
2269 /// \brief This class provides transaction based operation on the IR.
2270 /// Every change made through this class is recorded in the internal state and
2271 /// can be undone (rollback) until commit is called.
2272 class TypePromotionTransaction {
2273 
2274   /// \brief This represents the common interface of the individual transaction.
2275   /// Each class implements the logic for doing one specific modification on
2276   /// the IR via the TypePromotionTransaction.
2277   class TypePromotionAction {
2278   protected:
2279     /// The Instruction modified.
2280     Instruction *Inst;
2281 
2282   public:
2283     /// \brief Constructor of the action.
2284     /// The constructor performs the related action on the IR.
2285     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2286 
2287     virtual ~TypePromotionAction() {}
2288 
2289     /// \brief Undo the modification done by this action.
2290     /// When this method is called, the IR must be in the same state as it was
2291     /// before this action was applied.
2292     /// \pre Undoing the action works if and only if the IR is in the exact same
2293     /// state as it was directly after this action was applied.
2294     virtual void undo() = 0;
2295 
2296     /// \brief Advocate every change made by this action.
2297     /// When the results on the IR of the action are to be kept, it is important
2298     /// to call this function, otherwise hidden information may be kept forever.
2299     virtual void commit() {
2300       // Nothing to be done, this action is not doing anything.
2301     }
2302   };
2303 
2304   /// \brief Utility to remember the position of an instruction.
2305   class InsertionHandler {
2306     /// Position of an instruction.
2307     /// Either an instruction:
2308     /// - Is the first in a basic block: BB is used.
2309     /// - Has a previous instructon: PrevInst is used.
2310     union {
2311       Instruction *PrevInst;
2312       BasicBlock *BB;
2313     } Point;
2314     /// Remember whether or not the instruction had a previous instruction.
2315     bool HasPrevInstruction;
2316 
2317   public:
2318     /// \brief Record the position of \p Inst.
2319     InsertionHandler(Instruction *Inst) {
2320       BasicBlock::iterator It = Inst->getIterator();
2321       HasPrevInstruction = (It != (Inst->getParent()->begin()));
2322       if (HasPrevInstruction)
2323         Point.PrevInst = &*--It;
2324       else
2325         Point.BB = Inst->getParent();
2326     }
2327 
2328     /// \brief Insert \p Inst at the recorded position.
2329     void insert(Instruction *Inst) {
2330       if (HasPrevInstruction) {
2331         if (Inst->getParent())
2332           Inst->removeFromParent();
2333         Inst->insertAfter(Point.PrevInst);
2334       } else {
2335         Instruction *Position = &*Point.BB->getFirstInsertionPt();
2336         if (Inst->getParent())
2337           Inst->moveBefore(Position);
2338         else
2339           Inst->insertBefore(Position);
2340       }
2341     }
2342   };
2343 
2344   /// \brief Move an instruction before another.
2345   class InstructionMoveBefore : public TypePromotionAction {
2346     /// Original position of the instruction.
2347     InsertionHandler Position;
2348 
2349   public:
2350     /// \brief Move \p Inst before \p Before.
2351     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2352         : TypePromotionAction(Inst), Position(Inst) {
2353       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2354       Inst->moveBefore(Before);
2355     }
2356 
2357     /// \brief Move the instruction back to its original position.
2358     void undo() override {
2359       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2360       Position.insert(Inst);
2361     }
2362   };
2363 
2364   /// \brief Set the operand of an instruction with a new value.
2365   class OperandSetter : public TypePromotionAction {
2366     /// Original operand of the instruction.
2367     Value *Origin;
2368     /// Index of the modified instruction.
2369     unsigned Idx;
2370 
2371   public:
2372     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2373     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2374         : TypePromotionAction(Inst), Idx(Idx) {
2375       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2376                    << "for:" << *Inst << "\n"
2377                    << "with:" << *NewVal << "\n");
2378       Origin = Inst->getOperand(Idx);
2379       Inst->setOperand(Idx, NewVal);
2380     }
2381 
2382     /// \brief Restore the original value of the instruction.
2383     void undo() override {
2384       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2385                    << "for: " << *Inst << "\n"
2386                    << "with: " << *Origin << "\n");
2387       Inst->setOperand(Idx, Origin);
2388     }
2389   };
2390 
2391   /// \brief Hide the operands of an instruction.
2392   /// Do as if this instruction was not using any of its operands.
2393   class OperandsHider : public TypePromotionAction {
2394     /// The list of original operands.
2395     SmallVector<Value *, 4> OriginalValues;
2396 
2397   public:
2398     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2399     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2400       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2401       unsigned NumOpnds = Inst->getNumOperands();
2402       OriginalValues.reserve(NumOpnds);
2403       for (unsigned It = 0; It < NumOpnds; ++It) {
2404         // Save the current operand.
2405         Value *Val = Inst->getOperand(It);
2406         OriginalValues.push_back(Val);
2407         // Set a dummy one.
2408         // We could use OperandSetter here, but that would imply an overhead
2409         // that we are not willing to pay.
2410         Inst->setOperand(It, UndefValue::get(Val->getType()));
2411       }
2412     }
2413 
2414     /// \brief Restore the original list of uses.
2415     void undo() override {
2416       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2417       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2418         Inst->setOperand(It, OriginalValues[It]);
2419     }
2420   };
2421 
2422   /// \brief Build a truncate instruction.
2423   class TruncBuilder : public TypePromotionAction {
2424     Value *Val;
2425   public:
2426     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2427     /// result.
2428     /// trunc Opnd to Ty.
2429     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2430       IRBuilder<> Builder(Opnd);
2431       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2432       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
2433     }
2434 
2435     /// \brief Get the built value.
2436     Value *getBuiltValue() { return Val; }
2437 
2438     /// \brief Remove the built instruction.
2439     void undo() override {
2440       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2441       if (Instruction *IVal = dyn_cast<Instruction>(Val))
2442         IVal->eraseFromParent();
2443     }
2444   };
2445 
2446   /// \brief Build a sign extension instruction.
2447   class SExtBuilder : public TypePromotionAction {
2448     Value *Val;
2449   public:
2450     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2451     /// result.
2452     /// sext Opnd to Ty.
2453     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2454         : TypePromotionAction(InsertPt) {
2455       IRBuilder<> Builder(InsertPt);
2456       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2457       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
2458     }
2459 
2460     /// \brief Get the built value.
2461     Value *getBuiltValue() { return Val; }
2462 
2463     /// \brief Remove the built instruction.
2464     void undo() override {
2465       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2466       if (Instruction *IVal = dyn_cast<Instruction>(Val))
2467         IVal->eraseFromParent();
2468     }
2469   };
2470 
2471   /// \brief Build a zero extension instruction.
2472   class ZExtBuilder : public TypePromotionAction {
2473     Value *Val;
2474   public:
2475     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2476     /// result.
2477     /// zext Opnd to Ty.
2478     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2479         : TypePromotionAction(InsertPt) {
2480       IRBuilder<> Builder(InsertPt);
2481       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2482       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
2483     }
2484 
2485     /// \brief Get the built value.
2486     Value *getBuiltValue() { return Val; }
2487 
2488     /// \brief Remove the built instruction.
2489     void undo() override {
2490       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2491       if (Instruction *IVal = dyn_cast<Instruction>(Val))
2492         IVal->eraseFromParent();
2493     }
2494   };
2495 
2496   /// \brief Mutate an instruction to another type.
2497   class TypeMutator : public TypePromotionAction {
2498     /// Record the original type.
2499     Type *OrigTy;
2500 
2501   public:
2502     /// \brief Mutate the type of \p Inst into \p NewTy.
2503     TypeMutator(Instruction *Inst, Type *NewTy)
2504         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2505       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2506                    << "\n");
2507       Inst->mutateType(NewTy);
2508     }
2509 
2510     /// \brief Mutate the instruction back to its original type.
2511     void undo() override {
2512       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2513                    << "\n");
2514       Inst->mutateType(OrigTy);
2515     }
2516   };
2517 
2518   /// \brief Replace the uses of an instruction by another instruction.
2519   class UsesReplacer : public TypePromotionAction {
2520     /// Helper structure to keep track of the replaced uses.
2521     struct InstructionAndIdx {
2522       /// The instruction using the instruction.
2523       Instruction *Inst;
2524       /// The index where this instruction is used for Inst.
2525       unsigned Idx;
2526       InstructionAndIdx(Instruction *Inst, unsigned Idx)
2527           : Inst(Inst), Idx(Idx) {}
2528     };
2529 
2530     /// Keep track of the original uses (pair Instruction, Index).
2531     SmallVector<InstructionAndIdx, 4> OriginalUses;
2532     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2533 
2534   public:
2535     /// \brief Replace all the use of \p Inst by \p New.
2536     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2537       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2538                    << "\n");
2539       // Record the original uses.
2540       for (Use &U : Inst->uses()) {
2541         Instruction *UserI = cast<Instruction>(U.getUser());
2542         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2543       }
2544       // Now, we can replace the uses.
2545       Inst->replaceAllUsesWith(New);
2546     }
2547 
2548     /// \brief Reassign the original uses of Inst to Inst.
2549     void undo() override {
2550       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2551       for (use_iterator UseIt = OriginalUses.begin(),
2552                         EndIt = OriginalUses.end();
2553            UseIt != EndIt; ++UseIt) {
2554         UseIt->Inst->setOperand(UseIt->Idx, Inst);
2555       }
2556     }
2557   };
2558 
2559   /// \brief Remove an instruction from the IR.
2560   class InstructionRemover : public TypePromotionAction {
2561     /// Original position of the instruction.
2562     InsertionHandler Inserter;
2563     /// Helper structure to hide all the link to the instruction. In other
2564     /// words, this helps to do as if the instruction was removed.
2565     OperandsHider Hider;
2566     /// Keep track of the uses replaced, if any.
2567     UsesReplacer *Replacer;
2568 
2569   public:
2570     /// \brief Remove all reference of \p Inst and optinally replace all its
2571     /// uses with New.
2572     /// \pre If !Inst->use_empty(), then New != nullptr
2573     InstructionRemover(Instruction *Inst, Value *New = nullptr)
2574         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
2575           Replacer(nullptr) {
2576       if (New)
2577         Replacer = new UsesReplacer(Inst, New);
2578       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2579       Inst->removeFromParent();
2580     }
2581 
2582     ~InstructionRemover() override { delete Replacer; }
2583 
2584     /// \brief Really remove the instruction.
2585     void commit() override { delete Inst; }
2586 
2587     /// \brief Resurrect the instruction and reassign it to the proper uses if
2588     /// new value was provided when build this action.
2589     void undo() override {
2590       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2591       Inserter.insert(Inst);
2592       if (Replacer)
2593         Replacer->undo();
2594       Hider.undo();
2595     }
2596   };
2597 
2598 public:
2599   /// Restoration point.
2600   /// The restoration point is a pointer to an action instead of an iterator
2601   /// because the iterator may be invalidated but not the pointer.
2602   typedef const TypePromotionAction *ConstRestorationPt;
2603   /// Advocate every changes made in that transaction.
2604   void commit();
2605   /// Undo all the changes made after the given point.
2606   void rollback(ConstRestorationPt Point);
2607   /// Get the current restoration point.
2608   ConstRestorationPt getRestorationPoint() const;
2609 
2610   /// \name API for IR modification with state keeping to support rollback.
2611   /// @{
2612   /// Same as Instruction::setOperand.
2613   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2614   /// Same as Instruction::eraseFromParent.
2615   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
2616   /// Same as Value::replaceAllUsesWith.
2617   void replaceAllUsesWith(Instruction *Inst, Value *New);
2618   /// Same as Value::mutateType.
2619   void mutateType(Instruction *Inst, Type *NewTy);
2620   /// Same as IRBuilder::createTrunc.
2621   Value *createTrunc(Instruction *Opnd, Type *Ty);
2622   /// Same as IRBuilder::createSExt.
2623   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
2624   /// Same as IRBuilder::createZExt.
2625   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
2626   /// Same as Instruction::moveBefore.
2627   void moveBefore(Instruction *Inst, Instruction *Before);
2628   /// @}
2629 
2630 private:
2631   /// The ordered list of actions made so far.
2632   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2633   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
2634 };
2635 
2636 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2637                                           Value *NewVal) {
2638   Actions.push_back(
2639       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
2640 }
2641 
2642 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2643                                                 Value *NewVal) {
2644   Actions.push_back(
2645       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
2646 }
2647 
2648 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2649                                                   Value *New) {
2650   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
2651 }
2652 
2653 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
2654   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
2655 }
2656 
2657 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2658                                              Type *Ty) {
2659   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
2660   Value *Val = Ptr->getBuiltValue();
2661   Actions.push_back(std::move(Ptr));
2662   return Val;
2663 }
2664 
2665 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2666                                             Value *Opnd, Type *Ty) {
2667   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
2668   Value *Val = Ptr->getBuiltValue();
2669   Actions.push_back(std::move(Ptr));
2670   return Val;
2671 }
2672 
2673 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2674                                             Value *Opnd, Type *Ty) {
2675   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
2676   Value *Val = Ptr->getBuiltValue();
2677   Actions.push_back(std::move(Ptr));
2678   return Val;
2679 }
2680 
2681 void TypePromotionTransaction::moveBefore(Instruction *Inst,
2682                                           Instruction *Before) {
2683   Actions.push_back(
2684       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
2685 }
2686 
2687 TypePromotionTransaction::ConstRestorationPt
2688 TypePromotionTransaction::getRestorationPoint() const {
2689   return !Actions.empty() ? Actions.back().get() : nullptr;
2690 }
2691 
2692 void TypePromotionTransaction::commit() {
2693   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
2694        ++It)
2695     (*It)->commit();
2696   Actions.clear();
2697 }
2698 
2699 void TypePromotionTransaction::rollback(
2700     TypePromotionTransaction::ConstRestorationPt Point) {
2701   while (!Actions.empty() && Point != Actions.back().get()) {
2702     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
2703     Curr->undo();
2704   }
2705 }
2706 
2707 /// \brief A helper class for matching addressing modes.
2708 ///
2709 /// This encapsulates the logic for matching the target-legal addressing modes.
2710 class AddressingModeMatcher {
2711   SmallVectorImpl<Instruction*> &AddrModeInsts;
2712   const TargetLowering &TLI;
2713   const TargetRegisterInfo &TRI;
2714   const DataLayout &DL;
2715 
2716   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2717   /// the memory instruction that we're computing this address for.
2718   Type *AccessTy;
2719   unsigned AddrSpace;
2720   Instruction *MemoryInst;
2721 
2722   /// This is the addressing mode that we're building up. This is
2723   /// part of the return value of this addressing mode matching stuff.
2724   ExtAddrMode &AddrMode;
2725 
2726   /// The instructions inserted by other CodeGenPrepare optimizations.
2727   const SetOfInstrs &InsertedInsts;
2728   /// A map from the instructions to their type before promotion.
2729   InstrToOrigTy &PromotedInsts;
2730   /// The ongoing transaction where every action should be registered.
2731   TypePromotionTransaction &TPT;
2732 
2733   /// This is set to true when we should not do profitability checks.
2734   /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
2735   bool IgnoreProfitability;
2736 
2737   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
2738                         const TargetLowering &TLI,
2739                         const TargetRegisterInfo &TRI,
2740                         Type *AT, unsigned AS,
2741                         Instruction *MI, ExtAddrMode &AM,
2742                         const SetOfInstrs &InsertedInsts,
2743                         InstrToOrigTy &PromotedInsts,
2744                         TypePromotionTransaction &TPT)
2745       : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
2746         DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2747         MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2748         PromotedInsts(PromotedInsts), TPT(TPT) {
2749     IgnoreProfitability = false;
2750   }
2751 public:
2752 
2753   /// Find the maximal addressing mode that a load/store of V can fold,
2754   /// give an access type of AccessTy.  This returns a list of involved
2755   /// instructions in AddrModeInsts.
2756   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
2757   /// optimizations.
2758   /// \p PromotedInsts maps the instructions to their type before promotion.
2759   /// \p The ongoing transaction where every action should be registered.
2760   static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
2761                            Instruction *MemoryInst,
2762                            SmallVectorImpl<Instruction*> &AddrModeInsts,
2763                            const TargetLowering &TLI,
2764                            const TargetRegisterInfo &TRI,
2765                            const SetOfInstrs &InsertedInsts,
2766                            InstrToOrigTy &PromotedInsts,
2767                            TypePromotionTransaction &TPT) {
2768     ExtAddrMode Result;
2769 
2770     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2771                                          AccessTy, AS,
2772                                          MemoryInst, Result, InsertedInsts,
2773                                          PromotedInsts, TPT).matchAddr(V, 0);
2774     (void)Success; assert(Success && "Couldn't select *anything*?");
2775     return Result;
2776   }
2777 private:
2778   bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2779   bool matchAddr(Value *V, unsigned Depth);
2780   bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
2781                           bool *MovedAway = nullptr);
2782   bool isProfitableToFoldIntoAddressingMode(Instruction *I,
2783                                             ExtAddrMode &AMBefore,
2784                                             ExtAddrMode &AMAfter);
2785   bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2786   bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
2787                              Value *PromotedOperand) const;
2788 };
2789 
2790 /// Try adding ScaleReg*Scale to the current addressing mode.
2791 /// Return true and update AddrMode if this addr mode is legal for the target,
2792 /// false if not.
2793 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
2794                                              unsigned Depth) {
2795   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2796   // mode.  Just process that directly.
2797   if (Scale == 1)
2798     return matchAddr(ScaleReg, Depth);
2799 
2800   // If the scale is 0, it takes nothing to add this.
2801   if (Scale == 0)
2802     return true;
2803 
2804   // If we already have a scale of this value, we can add to it, otherwise, we
2805   // need an available scale field.
2806   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2807     return false;
2808 
2809   ExtAddrMode TestAddrMode = AddrMode;
2810 
2811   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
2812   // [A+B + A*7] -> [B+A*8].
2813   TestAddrMode.Scale += Scale;
2814   TestAddrMode.ScaledReg = ScaleReg;
2815 
2816   // If the new address isn't legal, bail out.
2817   if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
2818     return false;
2819 
2820   // It was legal, so commit it.
2821   AddrMode = TestAddrMode;
2822 
2823   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
2824   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
2825   // X*Scale + C*Scale to addr mode.
2826   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
2827   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
2828       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2829     TestAddrMode.ScaledReg = AddLHS;
2830     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
2831 
2832     // If this addressing mode is legal, commit it and remember that we folded
2833     // this instruction.
2834     if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
2835       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2836       AddrMode = TestAddrMode;
2837       return true;
2838     }
2839   }
2840 
2841   // Otherwise, not (x+c)*scale, just return what we have.
2842   return true;
2843 }
2844 
2845 /// This is a little filter, which returns true if an addressing computation
2846 /// involving I might be folded into a load/store accessing it.
2847 /// This doesn't need to be perfect, but needs to accept at least
2848 /// the set of instructions that MatchOperationAddr can.
2849 static bool MightBeFoldableInst(Instruction *I) {
2850   switch (I->getOpcode()) {
2851   case Instruction::BitCast:
2852   case Instruction::AddrSpaceCast:
2853     // Don't touch identity bitcasts.
2854     if (I->getType() == I->getOperand(0)->getType())
2855       return false;
2856     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2857   case Instruction::PtrToInt:
2858     // PtrToInt is always a noop, as we know that the int type is pointer sized.
2859     return true;
2860   case Instruction::IntToPtr:
2861     // We know the input is intptr_t, so this is foldable.
2862     return true;
2863   case Instruction::Add:
2864     return true;
2865   case Instruction::Mul:
2866   case Instruction::Shl:
2867     // Can only handle X*C and X << C.
2868     return isa<ConstantInt>(I->getOperand(1));
2869   case Instruction::GetElementPtr:
2870     return true;
2871   default:
2872     return false;
2873   }
2874 }
2875 
2876 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2877 /// \note \p Val is assumed to be the product of some type promotion.
2878 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2879 /// to be legal, as the non-promoted value would have had the same state.
2880 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2881                                        const DataLayout &DL, Value *Val) {
2882   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2883   if (!PromotedInst)
2884     return false;
2885   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2886   // If the ISDOpcode is undefined, it was undefined before the promotion.
2887   if (!ISDOpcode)
2888     return true;
2889   // Otherwise, check if the promoted instruction is legal or not.
2890   return TLI.isOperationLegalOrCustom(
2891       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
2892 }
2893 
2894 /// \brief Hepler class to perform type promotion.
2895 class TypePromotionHelper {
2896   /// \brief Utility function to check whether or not a sign or zero extension
2897   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2898   /// either using the operands of \p Inst or promoting \p Inst.
2899   /// The type of the extension is defined by \p IsSExt.
2900   /// In other words, check if:
2901   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
2902   /// #1 Promotion applies:
2903   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
2904   /// #2 Operand reuses:
2905   /// ext opnd1 to ConsideredExtType.
2906   /// \p PromotedInsts maps the instructions to their type before promotion.
2907   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2908                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
2909 
2910   /// \brief Utility function to determine if \p OpIdx should be promoted when
2911   /// promoting \p Inst.
2912   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
2913     return !(isa<SelectInst>(Inst) && OpIdx == 0);
2914   }
2915 
2916   /// \brief Utility function to promote the operand of \p Ext when this
2917   /// operand is a promotable trunc or sext or zext.
2918   /// \p PromotedInsts maps the instructions to their type before promotion.
2919   /// \p CreatedInstsCost[out] contains the cost of all instructions
2920   /// created to promote the operand of Ext.
2921   /// Newly added extensions are inserted in \p Exts.
2922   /// Newly added truncates are inserted in \p Truncs.
2923   /// Should never be called directly.
2924   /// \return The promoted value which is used instead of Ext.
2925   static Value *promoteOperandForTruncAndAnyExt(
2926       Instruction *Ext, TypePromotionTransaction &TPT,
2927       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2928       SmallVectorImpl<Instruction *> *Exts,
2929       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
2930 
2931   /// \brief Utility function to promote the operand of \p Ext when this
2932   /// operand is promotable and is not a supported trunc or sext.
2933   /// \p PromotedInsts maps the instructions to their type before promotion.
2934   /// \p CreatedInstsCost[out] contains the cost of all the instructions
2935   /// created to promote the operand of Ext.
2936   /// Newly added extensions are inserted in \p Exts.
2937   /// Newly added truncates are inserted in \p Truncs.
2938   /// Should never be called directly.
2939   /// \return The promoted value which is used instead of Ext.
2940   static Value *promoteOperandForOther(Instruction *Ext,
2941                                        TypePromotionTransaction &TPT,
2942                                        InstrToOrigTy &PromotedInsts,
2943                                        unsigned &CreatedInstsCost,
2944                                        SmallVectorImpl<Instruction *> *Exts,
2945                                        SmallVectorImpl<Instruction *> *Truncs,
2946                                        const TargetLowering &TLI, bool IsSExt);
2947 
2948   /// \see promoteOperandForOther.
2949   static Value *signExtendOperandForOther(
2950       Instruction *Ext, TypePromotionTransaction &TPT,
2951       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2952       SmallVectorImpl<Instruction *> *Exts,
2953       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2954     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2955                                   Exts, Truncs, TLI, true);
2956   }
2957 
2958   /// \see promoteOperandForOther.
2959   static Value *zeroExtendOperandForOther(
2960       Instruction *Ext, TypePromotionTransaction &TPT,
2961       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2962       SmallVectorImpl<Instruction *> *Exts,
2963       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2964     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2965                                   Exts, Truncs, TLI, false);
2966   }
2967 
2968 public:
2969   /// Type for the utility function that promotes the operand of Ext.
2970   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
2971                            InstrToOrigTy &PromotedInsts,
2972                            unsigned &CreatedInstsCost,
2973                            SmallVectorImpl<Instruction *> *Exts,
2974                            SmallVectorImpl<Instruction *> *Truncs,
2975                            const TargetLowering &TLI);
2976   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2977   /// action to promote the operand of \p Ext instead of using Ext.
2978   /// \return NULL if no promotable action is possible with the current
2979   /// sign extension.
2980   /// \p InsertedInsts keeps track of all the instructions inserted by the
2981   /// other CodeGenPrepare optimizations. This information is important
2982   /// because we do not want to promote these instructions as CodeGenPrepare
2983   /// will reinsert them later. Thus creating an infinite loop: create/remove.
2984   /// \p PromotedInsts maps the instructions to their type before promotion.
2985   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
2986                           const TargetLowering &TLI,
2987                           const InstrToOrigTy &PromotedInsts);
2988 };
2989 
2990 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
2991                                         Type *ConsideredExtType,
2992                                         const InstrToOrigTy &PromotedInsts,
2993                                         bool IsSExt) {
2994   // The promotion helper does not know how to deal with vector types yet.
2995   // To be able to fix that, we would need to fix the places where we
2996   // statically extend, e.g., constants and such.
2997   if (Inst->getType()->isVectorTy())
2998     return false;
2999 
3000   // We can always get through zext.
3001   if (isa<ZExtInst>(Inst))
3002     return true;
3003 
3004   // sext(sext) is ok too.
3005   if (IsSExt && isa<SExtInst>(Inst))
3006     return true;
3007 
3008   // We can get through binary operator, if it is legal. In other words, the
3009   // binary operator must have a nuw or nsw flag.
3010   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3011   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3012       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3013        (IsSExt && BinOp->hasNoSignedWrap())))
3014     return true;
3015 
3016   // Check if we can do the following simplification.
3017   // ext(trunc(opnd)) --> ext(opnd)
3018   if (!isa<TruncInst>(Inst))
3019     return false;
3020 
3021   Value *OpndVal = Inst->getOperand(0);
3022   // Check if we can use this operand in the extension.
3023   // If the type is larger than the result type of the extension, we cannot.
3024   if (!OpndVal->getType()->isIntegerTy() ||
3025       OpndVal->getType()->getIntegerBitWidth() >
3026           ConsideredExtType->getIntegerBitWidth())
3027     return false;
3028 
3029   // If the operand of the truncate is not an instruction, we will not have
3030   // any information on the dropped bits.
3031   // (Actually we could for constant but it is not worth the extra logic).
3032   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3033   if (!Opnd)
3034     return false;
3035 
3036   // Check if the source of the type is narrow enough.
3037   // I.e., check that trunc just drops extended bits of the same kind of
3038   // the extension.
3039   // #1 get the type of the operand and check the kind of the extended bits.
3040   const Type *OpndType;
3041   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3042   if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3043     OpndType = It->second.getPointer();
3044   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3045     OpndType = Opnd->getOperand(0)->getType();
3046   else
3047     return false;
3048 
3049   // #2 check that the truncate just drops extended bits.
3050   return Inst->getType()->getIntegerBitWidth() >=
3051          OpndType->getIntegerBitWidth();
3052 }
3053 
3054 TypePromotionHelper::Action TypePromotionHelper::getAction(
3055     Instruction *Ext, const SetOfInstrs &InsertedInsts,
3056     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3057   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3058          "Unexpected instruction type");
3059   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3060   Type *ExtTy = Ext->getType();
3061   bool IsSExt = isa<SExtInst>(Ext);
3062   // If the operand of the extension is not an instruction, we cannot
3063   // get through.
3064   // If it, check we can get through.
3065   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3066     return nullptr;
3067 
3068   // Do not promote if the operand has been added by codegenprepare.
3069   // Otherwise, it means we are undoing an optimization that is likely to be
3070   // redone, thus causing potential infinite loop.
3071   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3072     return nullptr;
3073 
3074   // SExt or Trunc instructions.
3075   // Return the related handler.
3076   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3077       isa<ZExtInst>(ExtOpnd))
3078     return promoteOperandForTruncAndAnyExt;
3079 
3080   // Regular instruction.
3081   // Abort early if we will have to insert non-free instructions.
3082   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
3083     return nullptr;
3084   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3085 }
3086 
3087 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3088     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
3089     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3090     SmallVectorImpl<Instruction *> *Exts,
3091     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3092   // By construction, the operand of SExt is an instruction. Otherwise we cannot
3093   // get through it and this method should not be called.
3094   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
3095   Value *ExtVal = SExt;
3096   bool HasMergedNonFreeExt = false;
3097   if (isa<ZExtInst>(SExtOpnd)) {
3098     // Replace s|zext(zext(opnd))
3099     // => zext(opnd).
3100     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
3101     Value *ZExt =
3102         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3103     TPT.replaceAllUsesWith(SExt, ZExt);
3104     TPT.eraseInstruction(SExt);
3105     ExtVal = ZExt;
3106   } else {
3107     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3108     // => z|sext(opnd).
3109     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3110   }
3111   CreatedInstsCost = 0;
3112 
3113   // Remove dead code.
3114   if (SExtOpnd->use_empty())
3115     TPT.eraseInstruction(SExtOpnd);
3116 
3117   // Check if the extension is still needed.
3118   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
3119   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3120     if (ExtInst) {
3121       if (Exts)
3122         Exts->push_back(ExtInst);
3123       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3124     }
3125     return ExtVal;
3126   }
3127 
3128   // At this point we have: ext ty opnd to ty.
3129   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3130   Value *NextVal = ExtInst->getOperand(0);
3131   TPT.eraseInstruction(ExtInst, NextVal);
3132   return NextVal;
3133 }
3134 
3135 Value *TypePromotionHelper::promoteOperandForOther(
3136     Instruction *Ext, TypePromotionTransaction &TPT,
3137     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3138     SmallVectorImpl<Instruction *> *Exts,
3139     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3140     bool IsSExt) {
3141   // By construction, the operand of Ext is an instruction. Otherwise we cannot
3142   // get through it and this method should not be called.
3143   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3144   CreatedInstsCost = 0;
3145   if (!ExtOpnd->hasOneUse()) {
3146     // ExtOpnd will be promoted.
3147     // All its uses, but Ext, will need to use a truncated value of the
3148     // promoted version.
3149     // Create the truncate now.
3150     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
3151     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3152       ITrunc->removeFromParent();
3153       // Insert it just after the definition.
3154       ITrunc->insertAfter(ExtOpnd);
3155       if (Truncs)
3156         Truncs->push_back(ITrunc);
3157     }
3158 
3159     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
3160     // Restore the operand of Ext (which has been replaced by the previous call
3161     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
3162     TPT.setOperand(Ext, 0, ExtOpnd);
3163   }
3164 
3165   // Get through the Instruction:
3166   // 1. Update its type.
3167   // 2. Replace the uses of Ext by Inst.
3168   // 3. Extend each operand that needs to be extended.
3169 
3170   // Remember the original type of the instruction before promotion.
3171   // This is useful to know that the high bits are sign extended bits.
3172   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3173       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
3174   // Step #1.
3175   TPT.mutateType(ExtOpnd, Ext->getType());
3176   // Step #2.
3177   TPT.replaceAllUsesWith(Ext, ExtOpnd);
3178   // Step #3.
3179   Instruction *ExtForOpnd = Ext;
3180 
3181   DEBUG(dbgs() << "Propagate Ext to operands\n");
3182   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
3183        ++OpIdx) {
3184     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3185     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3186         !shouldExtOperand(ExtOpnd, OpIdx)) {
3187       DEBUG(dbgs() << "No need to propagate\n");
3188       continue;
3189     }
3190     // Check if we can statically extend the operand.
3191     Value *Opnd = ExtOpnd->getOperand(OpIdx);
3192     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
3193       DEBUG(dbgs() << "Statically extend\n");
3194       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3195       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3196                             : Cst->getValue().zext(BitWidth);
3197       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
3198       continue;
3199     }
3200     // UndefValue are typed, so we have to statically sign extend them.
3201     if (isa<UndefValue>(Opnd)) {
3202       DEBUG(dbgs() << "Statically extend\n");
3203       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
3204       continue;
3205     }
3206 
3207     // Otherwise we have to explicity sign extend the operand.
3208     // Check if Ext was reused to extend an operand.
3209     if (!ExtForOpnd) {
3210       // If yes, create a new one.
3211       DEBUG(dbgs() << "More operands to ext\n");
3212       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3213         : TPT.createZExt(Ext, Opnd, Ext->getType());
3214       if (!isa<Instruction>(ValForExtOpnd)) {
3215         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3216         continue;
3217       }
3218       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
3219     }
3220     if (Exts)
3221       Exts->push_back(ExtForOpnd);
3222     TPT.setOperand(ExtForOpnd, 0, Opnd);
3223 
3224     // Move the sign extension before the insertion point.
3225     TPT.moveBefore(ExtForOpnd, ExtOpnd);
3226     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3227     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
3228     // If more sext are required, new instructions will have to be created.
3229     ExtForOpnd = nullptr;
3230   }
3231   if (ExtForOpnd == Ext) {
3232     DEBUG(dbgs() << "Extension is useless now\n");
3233     TPT.eraseInstruction(Ext);
3234   }
3235   return ExtOpnd;
3236 }
3237 
3238 /// Check whether or not promoting an instruction to a wider type is profitable.
3239 /// \p NewCost gives the cost of extension instructions created by the
3240 /// promotion.
3241 /// \p OldCost gives the cost of extension instructions before the promotion
3242 /// plus the number of instructions that have been
3243 /// matched in the addressing mode the promotion.
3244 /// \p PromotedOperand is the value that has been promoted.
3245 /// \return True if the promotion is profitable, false otherwise.
3246 bool AddressingModeMatcher::isPromotionProfitable(
3247     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3248   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3249   // The cost of the new extensions is greater than the cost of the
3250   // old extension plus what we folded.
3251   // This is not profitable.
3252   if (NewCost > OldCost)
3253     return false;
3254   if (NewCost < OldCost)
3255     return true;
3256   // The promotion is neutral but it may help folding the sign extension in
3257   // loads for instance.
3258   // Check that we did not create an illegal instruction.
3259   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
3260 }
3261 
3262 /// Given an instruction or constant expr, see if we can fold the operation
3263 /// into the addressing mode. If so, update the addressing mode and return
3264 /// true, otherwise return false without modifying AddrMode.
3265 /// If \p MovedAway is not NULL, it contains the information of whether or
3266 /// not AddrInst has to be folded into the addressing mode on success.
3267 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3268 /// because it has been moved away.
3269 /// Thus AddrInst must not be added in the matched instructions.
3270 /// This state can happen when AddrInst is a sext, since it may be moved away.
3271 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
3272 /// not be referenced anymore.
3273 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
3274                                                unsigned Depth,
3275                                                bool *MovedAway) {
3276   // Avoid exponential behavior on extremely deep expression trees.
3277   if (Depth >= 5) return false;
3278 
3279   // By default, all matched instructions stay in place.
3280   if (MovedAway)
3281     *MovedAway = false;
3282 
3283   switch (Opcode) {
3284   case Instruction::PtrToInt:
3285     // PtrToInt is always a noop, as we know that the int type is pointer sized.
3286     return matchAddr(AddrInst->getOperand(0), Depth);
3287   case Instruction::IntToPtr: {
3288     auto AS = AddrInst->getType()->getPointerAddressSpace();
3289     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
3290     // This inttoptr is a no-op if the integer type is pointer sized.
3291     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
3292       return matchAddr(AddrInst->getOperand(0), Depth);
3293     return false;
3294   }
3295   case Instruction::BitCast:
3296     // BitCast is always a noop, and we can handle it as long as it is
3297     // int->int or pointer->pointer (we don't want int<->fp or something).
3298     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3299          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3300         // Don't touch identity bitcasts.  These were probably put here by LSR,
3301         // and we don't want to mess around with them.  Assume it knows what it
3302         // is doing.
3303         AddrInst->getOperand(0)->getType() != AddrInst->getType())
3304       return matchAddr(AddrInst->getOperand(0), Depth);
3305     return false;
3306   case Instruction::AddrSpaceCast: {
3307     unsigned SrcAS
3308       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3309     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3310     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3311       return matchAddr(AddrInst->getOperand(0), Depth);
3312     return false;
3313   }
3314   case Instruction::Add: {
3315     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
3316     ExtAddrMode BackupAddrMode = AddrMode;
3317     unsigned OldSize = AddrModeInsts.size();
3318     // Start a transaction at this point.
3319     // The LHS may match but not the RHS.
3320     // Therefore, we need a higher level restoration point to undo partially
3321     // matched operation.
3322     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3323         TPT.getRestorationPoint();
3324 
3325     if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3326         matchAddr(AddrInst->getOperand(0), Depth+1))
3327       return true;
3328 
3329     // Restore the old addr mode info.
3330     AddrMode = BackupAddrMode;
3331     AddrModeInsts.resize(OldSize);
3332     TPT.rollback(LastKnownGood);
3333 
3334     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
3335     if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3336         matchAddr(AddrInst->getOperand(1), Depth+1))
3337       return true;
3338 
3339     // Otherwise we definitely can't merge the ADD in.
3340     AddrMode = BackupAddrMode;
3341     AddrModeInsts.resize(OldSize);
3342     TPT.rollback(LastKnownGood);
3343     break;
3344   }
3345   //case Instruction::Or:
3346   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3347   //break;
3348   case Instruction::Mul:
3349   case Instruction::Shl: {
3350     // Can only handle X*C and X << C.
3351     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
3352     if (!RHS)
3353       return false;
3354     int64_t Scale = RHS->getSExtValue();
3355     if (Opcode == Instruction::Shl)
3356       Scale = 1LL << Scale;
3357 
3358     return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
3359   }
3360   case Instruction::GetElementPtr: {
3361     // Scan the GEP.  We check it if it contains constant offsets and at most
3362     // one variable offset.
3363     int VariableOperand = -1;
3364     unsigned VariableScale = 0;
3365 
3366     int64_t ConstantOffset = 0;
3367     gep_type_iterator GTI = gep_type_begin(AddrInst);
3368     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3369       if (StructType *STy = GTI.getStructTypeOrNull()) {
3370         const StructLayout *SL = DL.getStructLayout(STy);
3371         unsigned Idx =
3372           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3373         ConstantOffset += SL->getElementOffset(Idx);
3374       } else {
3375         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
3376         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3377           ConstantOffset += CI->getSExtValue()*TypeSize;
3378         } else if (TypeSize) {  // Scales of zero don't do anything.
3379           // We only allow one variable index at the moment.
3380           if (VariableOperand != -1)
3381             return false;
3382 
3383           // Remember the variable index.
3384           VariableOperand = i;
3385           VariableScale = TypeSize;
3386         }
3387       }
3388     }
3389 
3390     // A common case is for the GEP to only do a constant offset.  In this case,
3391     // just add it to the disp field and check validity.
3392     if (VariableOperand == -1) {
3393       AddrMode.BaseOffs += ConstantOffset;
3394       if (ConstantOffset == 0 ||
3395           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
3396         // Check to see if we can fold the base pointer in too.
3397         if (matchAddr(AddrInst->getOperand(0), Depth+1))
3398           return true;
3399       }
3400       AddrMode.BaseOffs -= ConstantOffset;
3401       return false;
3402     }
3403 
3404     // Save the valid addressing mode in case we can't match.
3405     ExtAddrMode BackupAddrMode = AddrMode;
3406     unsigned OldSize = AddrModeInsts.size();
3407 
3408     // See if the scale and offset amount is valid for this target.
3409     AddrMode.BaseOffs += ConstantOffset;
3410 
3411     // Match the base operand of the GEP.
3412     if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
3413       // If it couldn't be matched, just stuff the value in a register.
3414       if (AddrMode.HasBaseReg) {
3415         AddrMode = BackupAddrMode;
3416         AddrModeInsts.resize(OldSize);
3417         return false;
3418       }
3419       AddrMode.HasBaseReg = true;
3420       AddrMode.BaseReg = AddrInst->getOperand(0);
3421     }
3422 
3423     // Match the remaining variable portion of the GEP.
3424     if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
3425                           Depth)) {
3426       // If it couldn't be matched, try stuffing the base into a register
3427       // instead of matching it, and retrying the match of the scale.
3428       AddrMode = BackupAddrMode;
3429       AddrModeInsts.resize(OldSize);
3430       if (AddrMode.HasBaseReg)
3431         return false;
3432       AddrMode.HasBaseReg = true;
3433       AddrMode.BaseReg = AddrInst->getOperand(0);
3434       AddrMode.BaseOffs += ConstantOffset;
3435       if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
3436                             VariableScale, Depth)) {
3437         // If even that didn't work, bail.
3438         AddrMode = BackupAddrMode;
3439         AddrModeInsts.resize(OldSize);
3440         return false;
3441       }
3442     }
3443 
3444     return true;
3445   }
3446   case Instruction::SExt:
3447   case Instruction::ZExt: {
3448     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3449     if (!Ext)
3450       return false;
3451 
3452     // Try to move this ext out of the way of the addressing mode.
3453     // Ask for a method for doing so.
3454     TypePromotionHelper::Action TPH =
3455         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
3456     if (!TPH)
3457       return false;
3458 
3459     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3460         TPT.getRestorationPoint();
3461     unsigned CreatedInstsCost = 0;
3462     unsigned ExtCost = !TLI.isExtFree(Ext);
3463     Value *PromotedOperand =
3464         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
3465     // SExt has been moved away.
3466     // Thus either it will be rematched later in the recursive calls or it is
3467     // gone. Anyway, we must not fold it into the addressing mode at this point.
3468     // E.g.,
3469     // op = add opnd, 1
3470     // idx = ext op
3471     // addr = gep base, idx
3472     // is now:
3473     // promotedOpnd = ext opnd            <- no match here
3474     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
3475     // addr = gep base, op                <- match
3476     if (MovedAway)
3477       *MovedAway = true;
3478 
3479     assert(PromotedOperand &&
3480            "TypePromotionHelper should have filtered out those cases");
3481 
3482     ExtAddrMode BackupAddrMode = AddrMode;
3483     unsigned OldSize = AddrModeInsts.size();
3484 
3485     if (!matchAddr(PromotedOperand, Depth) ||
3486         // The total of the new cost is equal to the cost of the created
3487         // instructions.
3488         // The total of the old cost is equal to the cost of the extension plus
3489         // what we have saved in the addressing mode.
3490         !isPromotionProfitable(CreatedInstsCost,
3491                                ExtCost + (AddrModeInsts.size() - OldSize),
3492                                PromotedOperand)) {
3493       AddrMode = BackupAddrMode;
3494       AddrModeInsts.resize(OldSize);
3495       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3496       TPT.rollback(LastKnownGood);
3497       return false;
3498     }
3499     return true;
3500   }
3501   }
3502   return false;
3503 }
3504 
3505 /// If we can, try to add the value of 'Addr' into the current addressing mode.
3506 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3507 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
3508 /// for the target.
3509 ///
3510 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
3511   // Start a transaction at this point that we will rollback if the matching
3512   // fails.
3513   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3514       TPT.getRestorationPoint();
3515   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3516     // Fold in immediates if legal for the target.
3517     AddrMode.BaseOffs += CI->getSExtValue();
3518     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3519       return true;
3520     AddrMode.BaseOffs -= CI->getSExtValue();
3521   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3522     // If this is a global variable, try to fold it into the addressing mode.
3523     if (!AddrMode.BaseGV) {
3524       AddrMode.BaseGV = GV;
3525       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3526         return true;
3527       AddrMode.BaseGV = nullptr;
3528     }
3529   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3530     ExtAddrMode BackupAddrMode = AddrMode;
3531     unsigned OldSize = AddrModeInsts.size();
3532 
3533     // Check to see if it is possible to fold this operation.
3534     bool MovedAway = false;
3535     if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
3536       // This instruction may have been moved away. If so, there is nothing
3537       // to check here.
3538       if (MovedAway)
3539         return true;
3540       // Okay, it's possible to fold this.  Check to see if it is actually
3541       // *profitable* to do so.  We use a simple cost model to avoid increasing
3542       // register pressure too much.
3543       if (I->hasOneUse() ||
3544           isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
3545         AddrModeInsts.push_back(I);
3546         return true;
3547       }
3548 
3549       // It isn't profitable to do this, roll back.
3550       //cerr << "NOT FOLDING: " << *I;
3551       AddrMode = BackupAddrMode;
3552       AddrModeInsts.resize(OldSize);
3553       TPT.rollback(LastKnownGood);
3554     }
3555   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
3556     if (matchOperationAddr(CE, CE->getOpcode(), Depth))
3557       return true;
3558     TPT.rollback(LastKnownGood);
3559   } else if (isa<ConstantPointerNull>(Addr)) {
3560     // Null pointer gets folded without affecting the addressing mode.
3561     return true;
3562   }
3563 
3564   // Worse case, the target should support [reg] addressing modes. :)
3565   if (!AddrMode.HasBaseReg) {
3566     AddrMode.HasBaseReg = true;
3567     AddrMode.BaseReg = Addr;
3568     // Still check for legality in case the target supports [imm] but not [i+r].
3569     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3570       return true;
3571     AddrMode.HasBaseReg = false;
3572     AddrMode.BaseReg = nullptr;
3573   }
3574 
3575   // If the base register is already taken, see if we can do [r+r].
3576   if (AddrMode.Scale == 0) {
3577     AddrMode.Scale = 1;
3578     AddrMode.ScaledReg = Addr;
3579     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3580       return true;
3581     AddrMode.Scale = 0;
3582     AddrMode.ScaledReg = nullptr;
3583   }
3584   // Couldn't match.
3585   TPT.rollback(LastKnownGood);
3586   return false;
3587 }
3588 
3589 /// Check to see if all uses of OpVal by the specified inline asm call are due
3590 /// to memory operands. If so, return true, otherwise return false.
3591 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
3592                                     const TargetLowering &TLI,
3593                                     const TargetRegisterInfo &TRI) {
3594   const Function *F = CI->getParent()->getParent();
3595   TargetLowering::AsmOperandInfoVector TargetConstraints =
3596       TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
3597                             ImmutableCallSite(CI));
3598 
3599   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3600     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3601 
3602     // Compute the constraint code and ConstraintType to use.
3603     TLI.ComputeConstraintToUse(OpInfo, SDValue());
3604 
3605     // If this asm operand is our Value*, and if it isn't an indirect memory
3606     // operand, we can't fold it!
3607     if (OpInfo.CallOperandVal == OpVal &&
3608         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3609          !OpInfo.isIndirect))
3610       return false;
3611   }
3612 
3613   return true;
3614 }
3615 
3616 /// Recursively walk all the uses of I until we find a memory use.
3617 /// If we find an obviously non-foldable instruction, return true.
3618 /// Add the ultimately found memory instructions to MemoryUses.
3619 static bool FindAllMemoryUses(
3620     Instruction *I,
3621     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3622     SmallPtrSetImpl<Instruction *> &ConsideredInsts,
3623     const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
3624   // If we already considered this instruction, we're done.
3625   if (!ConsideredInsts.insert(I).second)
3626     return false;
3627 
3628   // If this is an obviously unfoldable instruction, bail out.
3629   if (!MightBeFoldableInst(I))
3630     return true;
3631 
3632   const bool OptSize = I->getFunction()->optForSize();
3633 
3634   // Loop over all the uses, recursively processing them.
3635   for (Use &U : I->uses()) {
3636     Instruction *UserI = cast<Instruction>(U.getUser());
3637 
3638     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3639       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
3640       continue;
3641     }
3642 
3643     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3644       unsigned opNo = U.getOperandNo();
3645       if (opNo == 0) return true; // Storing addr, not into addr.
3646       MemoryUses.push_back(std::make_pair(SI, opNo));
3647       continue;
3648     }
3649 
3650     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
3651       // If this is a cold call, we can sink the addressing calculation into
3652       // the cold path.  See optimizeCallInst
3653       if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3654         continue;
3655 
3656       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3657       if (!IA) return true;
3658 
3659       // If this is a memory operand, we're cool, otherwise bail out.
3660       if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
3661         return true;
3662       continue;
3663     }
3664 
3665     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
3666       return true;
3667   }
3668 
3669   return false;
3670 }
3671 
3672 /// Return true if Val is already known to be live at the use site that we're
3673 /// folding it into. If so, there is no cost to include it in the addressing
3674 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3675 /// instruction already.
3676 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
3677                                                    Value *KnownLive2) {
3678   // If Val is either of the known-live values, we know it is live!
3679   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
3680     return true;
3681 
3682   // All values other than instructions and arguments (e.g. constants) are live.
3683   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
3684 
3685   // If Val is a constant sized alloca in the entry block, it is live, this is
3686   // true because it is just a reference to the stack/frame pointer, which is
3687   // live for the whole function.
3688   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3689     if (AI->isStaticAlloca())
3690       return true;
3691 
3692   // Check to see if this value is already used in the memory instruction's
3693   // block.  If so, it's already live into the block at the very least, so we
3694   // can reasonably fold it.
3695   return Val->isUsedInBasicBlock(MemoryInst->getParent());
3696 }
3697 
3698 /// It is possible for the addressing mode of the machine to fold the specified
3699 /// instruction into a load or store that ultimately uses it.
3700 /// However, the specified instruction has multiple uses.
3701 /// Given this, it may actually increase register pressure to fold it
3702 /// into the load. For example, consider this code:
3703 ///
3704 ///     X = ...
3705 ///     Y = X+1
3706 ///     use(Y)   -> nonload/store
3707 ///     Z = Y+1
3708 ///     load Z
3709 ///
3710 /// In this case, Y has multiple uses, and can be folded into the load of Z
3711 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
3712 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
3713 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
3714 /// number of computations either.
3715 ///
3716 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
3717 /// X was live across 'load Z' for other reasons, we actually *would* want to
3718 /// fold the addressing mode in the Z case.  This would make Y die earlier.
3719 bool AddressingModeMatcher::
3720 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
3721                                      ExtAddrMode &AMAfter) {
3722   if (IgnoreProfitability) return true;
3723 
3724   // AMBefore is the addressing mode before this instruction was folded into it,
3725   // and AMAfter is the addressing mode after the instruction was folded.  Get
3726   // the set of registers referenced by AMAfter and subtract out those
3727   // referenced by AMBefore: this is the set of values which folding in this
3728   // address extends the lifetime of.
3729   //
3730   // Note that there are only two potential values being referenced here,
3731   // BaseReg and ScaleReg (global addresses are always available, as are any
3732   // folded immediates).
3733   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
3734 
3735   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3736   // lifetime wasn't extended by adding this instruction.
3737   if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
3738     BaseReg = nullptr;
3739   if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
3740     ScaledReg = nullptr;
3741 
3742   // If folding this instruction (and it's subexprs) didn't extend any live
3743   // ranges, we're ok with it.
3744   if (!BaseReg && !ScaledReg)
3745     return true;
3746 
3747   // If all uses of this instruction can have the address mode sunk into them,
3748   // we can remove the addressing mode and effectively trade one live register
3749   // for another (at worst.)  In this context, folding an addressing mode into
3750   // the use is just a particularly nice way of sinking it.
3751   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3752   SmallPtrSet<Instruction*, 16> ConsideredInsts;
3753   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
3754     return false;  // Has a non-memory, non-foldable use!
3755 
3756   // Now that we know that all uses of this instruction are part of a chain of
3757   // computation involving only operations that could theoretically be folded
3758   // into a memory use, loop over each of these memory operation uses and see
3759   // if they could  *actually* fold the instruction.  The assumption is that
3760   // addressing modes are cheap and that duplicating the computation involved
3761   // many times is worthwhile, even on a fastpath. For sinking candidates
3762   // (i.e. cold call sites), this serves as a way to prevent excessive code
3763   // growth since most architectures have some reasonable small and fast way to
3764   // compute an effective address.  (i.e LEA on x86)
3765   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3766   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3767     Instruction *User = MemoryUses[i].first;
3768     unsigned OpNo = MemoryUses[i].second;
3769 
3770     // Get the access type of this use.  If the use isn't a pointer, we don't
3771     // know what it accesses.
3772     Value *Address = User->getOperand(OpNo);
3773     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3774     if (!AddrTy)
3775       return false;
3776     Type *AddressAccessTy = AddrTy->getElementType();
3777     unsigned AS = AddrTy->getAddressSpace();
3778 
3779     // Do a match against the root of this address, ignoring profitability. This
3780     // will tell us if the addressing mode for the memory operation will
3781     // *actually* cover the shared instruction.
3782     ExtAddrMode Result;
3783     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3784         TPT.getRestorationPoint();
3785     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
3786                                   AddressAccessTy, AS,
3787                                   MemoryInst, Result, InsertedInsts,
3788                                   PromotedInsts, TPT);
3789     Matcher.IgnoreProfitability = true;
3790     bool Success = Matcher.matchAddr(Address, 0);
3791     (void)Success; assert(Success && "Couldn't select *anything*?");
3792 
3793     // The match was to check the profitability, the changes made are not
3794     // part of the original matcher. Therefore, they should be dropped
3795     // otherwise the original matcher will not present the right state.
3796     TPT.rollback(LastKnownGood);
3797 
3798     // If the match didn't cover I, then it won't be shared by it.
3799     if (!is_contained(MatchedAddrModeInsts, I))
3800       return false;
3801 
3802     MatchedAddrModeInsts.clear();
3803   }
3804 
3805   return true;
3806 }
3807 
3808 } // end anonymous namespace
3809 
3810 /// Return true if the specified values are defined in a
3811 /// different basic block than BB.
3812 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3813   if (Instruction *I = dyn_cast<Instruction>(V))
3814     return I->getParent() != BB;
3815   return false;
3816 }
3817 
3818 /// Sink addressing mode computation immediate before MemoryInst if doing so
3819 /// can be done without increasing register pressure.  The need for the
3820 /// register pressure constraint means this can end up being an all or nothing
3821 /// decision for all uses of the same addressing computation.
3822 ///
3823 /// Load and Store Instructions often have addressing modes that can do
3824 /// significant amounts of computation. As such, instruction selection will try
3825 /// to get the load or store to do as much computation as possible for the
3826 /// program. The problem is that isel can only see within a single block. As
3827 /// such, we sink as much legal addressing mode work into the block as possible.
3828 ///
3829 /// This method is used to optimize both load/store and inline asms with memory
3830 /// operands.  It's also used to sink addressing computations feeding into cold
3831 /// call sites into their (cold) basic block.
3832 ///
3833 /// The motivation for handling sinking into cold blocks is that doing so can
3834 /// both enable other address mode sinking (by satisfying the register pressure
3835 /// constraint above), and reduce register pressure globally (by removing the
3836 /// addressing mode computation from the fast path entirely.).
3837 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
3838                                         Type *AccessTy, unsigned AddrSpace) {
3839   Value *Repl = Addr;
3840 
3841   // Try to collapse single-value PHI nodes.  This is necessary to undo
3842   // unprofitable PRE transformations.
3843   SmallVector<Value*, 8> worklist;
3844   SmallPtrSet<Value*, 16> Visited;
3845   worklist.push_back(Addr);
3846 
3847   // Use a worklist to iteratively look through PHI nodes, and ensure that
3848   // the addressing mode obtained from the non-PHI roots of the graph
3849   // are equivalent.
3850   Value *Consensus = nullptr;
3851   unsigned NumUsesConsensus = 0;
3852   bool IsNumUsesConsensusValid = false;
3853   SmallVector<Instruction*, 16> AddrModeInsts;
3854   ExtAddrMode AddrMode;
3855   TypePromotionTransaction TPT;
3856   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3857       TPT.getRestorationPoint();
3858   while (!worklist.empty()) {
3859     Value *V = worklist.back();
3860     worklist.pop_back();
3861 
3862     // Break use-def graph loops.
3863     if (!Visited.insert(V).second) {
3864       Consensus = nullptr;
3865       break;
3866     }
3867 
3868     // For a PHI node, push all of its incoming values.
3869     if (PHINode *P = dyn_cast<PHINode>(V)) {
3870       for (Value *IncValue : P->incoming_values())
3871         worklist.push_back(IncValue);
3872       continue;
3873     }
3874 
3875     // For non-PHIs, determine the addressing mode being computed.  Note that
3876     // the result may differ depending on what other uses our candidate
3877     // addressing instructions might have.
3878     SmallVector<Instruction*, 16> NewAddrModeInsts;
3879     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
3880       V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
3881       InsertedInsts, PromotedInsts, TPT);
3882 
3883     // This check is broken into two cases with very similar code to avoid using
3884     // getNumUses() as much as possible. Some values have a lot of uses, so
3885     // calling getNumUses() unconditionally caused a significant compile-time
3886     // regression.
3887     if (!Consensus) {
3888       Consensus = V;
3889       AddrMode = NewAddrMode;
3890       AddrModeInsts = NewAddrModeInsts;
3891       continue;
3892     } else if (NewAddrMode == AddrMode) {
3893       if (!IsNumUsesConsensusValid) {
3894         NumUsesConsensus = Consensus->getNumUses();
3895         IsNumUsesConsensusValid = true;
3896       }
3897 
3898       // Ensure that the obtained addressing mode is equivalent to that obtained
3899       // for all other roots of the PHI traversal.  Also, when choosing one
3900       // such root as representative, select the one with the most uses in order
3901       // to keep the cost modeling heuristics in AddressingModeMatcher
3902       // applicable.
3903       unsigned NumUses = V->getNumUses();
3904       if (NumUses > NumUsesConsensus) {
3905         Consensus = V;
3906         NumUsesConsensus = NumUses;
3907         AddrModeInsts = NewAddrModeInsts;
3908       }
3909       continue;
3910     }
3911 
3912     Consensus = nullptr;
3913     break;
3914   }
3915 
3916   // If the addressing mode couldn't be determined, or if multiple different
3917   // ones were determined, bail out now.
3918   if (!Consensus) {
3919     TPT.rollback(LastKnownGood);
3920     return false;
3921   }
3922   TPT.commit();
3923 
3924   // If all the instructions matched are already in this BB, don't do anything.
3925   if (none_of(AddrModeInsts, [&](Value *V) {
3926         return IsNonLocalValue(V, MemoryInst->getParent());
3927       })) {
3928     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
3929     return false;
3930   }
3931 
3932   // Insert this computation right after this user.  Since our caller is
3933   // scanning from the top of the BB to the bottom, reuse of the expr are
3934   // guaranteed to happen later.
3935   IRBuilder<> Builder(MemoryInst);
3936 
3937   // Now that we determined the addressing expression we want to use and know
3938   // that we have to sink it into this block.  Check to see if we have already
3939   // done this for some other load/store instr in this block.  If so, reuse the
3940   // computation.
3941   Value *&SunkAddr = SunkAddrs[Addr];
3942   if (SunkAddr) {
3943     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
3944                  << *MemoryInst << "\n");
3945     if (SunkAddr->getType() != Addr->getType())
3946       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3947   } else if (AddrSinkUsingGEPs ||
3948              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
3949               SubtargetInfo->useAA())) {
3950     // By default, we use the GEP-based method when AA is used later. This
3951     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3952     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3953                  << *MemoryInst << "\n");
3954     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
3955     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
3956 
3957     // First, find the pointer.
3958     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3959       ResultPtr = AddrMode.BaseReg;
3960       AddrMode.BaseReg = nullptr;
3961     }
3962 
3963     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3964       // We can't add more than one pointer together, nor can we scale a
3965       // pointer (both of which seem meaningless).
3966       if (ResultPtr || AddrMode.Scale != 1)
3967         return false;
3968 
3969       ResultPtr = AddrMode.ScaledReg;
3970       AddrMode.Scale = 0;
3971     }
3972 
3973     if (AddrMode.BaseGV) {
3974       if (ResultPtr)
3975         return false;
3976 
3977       ResultPtr = AddrMode.BaseGV;
3978     }
3979 
3980     // If the real base value actually came from an inttoptr, then the matcher
3981     // will look through it and provide only the integer value. In that case,
3982     // use it here.
3983     if (!ResultPtr && AddrMode.BaseReg) {
3984       ResultPtr =
3985         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
3986       AddrMode.BaseReg = nullptr;
3987     } else if (!ResultPtr && AddrMode.Scale == 1) {
3988       ResultPtr =
3989         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3990       AddrMode.Scale = 0;
3991     }
3992 
3993     if (!ResultPtr &&
3994         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3995       SunkAddr = Constant::getNullValue(Addr->getType());
3996     } else if (!ResultPtr) {
3997       return false;
3998     } else {
3999       Type *I8PtrTy =
4000           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4001       Type *I8Ty = Builder.getInt8Ty();
4002 
4003       // Start with the base register. Do this first so that subsequent address
4004       // matching finds it last, which will prevent it from trying to match it
4005       // as the scaled value in case it happens to be a mul. That would be
4006       // problematic if we've sunk a different mul for the scale, because then
4007       // we'd end up sinking both muls.
4008       if (AddrMode.BaseReg) {
4009         Value *V = AddrMode.BaseReg;
4010         if (V->getType() != IntPtrTy)
4011           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4012 
4013         ResultIndex = V;
4014       }
4015 
4016       // Add the scale value.
4017       if (AddrMode.Scale) {
4018         Value *V = AddrMode.ScaledReg;
4019         if (V->getType() == IntPtrTy) {
4020           // done.
4021         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4022                    cast<IntegerType>(V->getType())->getBitWidth()) {
4023           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4024         } else {
4025           // It is only safe to sign extend the BaseReg if we know that the math
4026           // required to create it did not overflow before we extend it. Since
4027           // the original IR value was tossed in favor of a constant back when
4028           // the AddrMode was created we need to bail out gracefully if widths
4029           // do not match instead of extending it.
4030           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4031           if (I && (ResultIndex != AddrMode.BaseReg))
4032             I->eraseFromParent();
4033           return false;
4034         }
4035 
4036         if (AddrMode.Scale != 1)
4037           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4038                                 "sunkaddr");
4039         if (ResultIndex)
4040           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4041         else
4042           ResultIndex = V;
4043       }
4044 
4045       // Add in the Base Offset if present.
4046       if (AddrMode.BaseOffs) {
4047         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4048         if (ResultIndex) {
4049           // We need to add this separately from the scale above to help with
4050           // SDAG consecutive load/store merging.
4051           if (ResultPtr->getType() != I8PtrTy)
4052             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4053           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4054         }
4055 
4056         ResultIndex = V;
4057       }
4058 
4059       if (!ResultIndex) {
4060         SunkAddr = ResultPtr;
4061       } else {
4062         if (ResultPtr->getType() != I8PtrTy)
4063           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4064         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4065       }
4066 
4067       if (SunkAddr->getType() != Addr->getType())
4068         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4069     }
4070   } else {
4071     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4072                  << *MemoryInst << "\n");
4073     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4074     Value *Result = nullptr;
4075 
4076     // Start with the base register. Do this first so that subsequent address
4077     // matching finds it last, which will prevent it from trying to match it
4078     // as the scaled value in case it happens to be a mul. That would be
4079     // problematic if we've sunk a different mul for the scale, because then
4080     // we'd end up sinking both muls.
4081     if (AddrMode.BaseReg) {
4082       Value *V = AddrMode.BaseReg;
4083       if (V->getType()->isPointerTy())
4084         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4085       if (V->getType() != IntPtrTy)
4086         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4087       Result = V;
4088     }
4089 
4090     // Add the scale value.
4091     if (AddrMode.Scale) {
4092       Value *V = AddrMode.ScaledReg;
4093       if (V->getType() == IntPtrTy) {
4094         // done.
4095       } else if (V->getType()->isPointerTy()) {
4096         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4097       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4098                  cast<IntegerType>(V->getType())->getBitWidth()) {
4099         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4100       } else {
4101         // It is only safe to sign extend the BaseReg if we know that the math
4102         // required to create it did not overflow before we extend it. Since
4103         // the original IR value was tossed in favor of a constant back when
4104         // the AddrMode was created we need to bail out gracefully if widths
4105         // do not match instead of extending it.
4106         Instruction *I = dyn_cast_or_null<Instruction>(Result);
4107         if (I && (Result != AddrMode.BaseReg))
4108           I->eraseFromParent();
4109         return false;
4110       }
4111       if (AddrMode.Scale != 1)
4112         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4113                               "sunkaddr");
4114       if (Result)
4115         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4116       else
4117         Result = V;
4118     }
4119 
4120     // Add in the BaseGV if present.
4121     if (AddrMode.BaseGV) {
4122       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
4123       if (Result)
4124         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4125       else
4126         Result = V;
4127     }
4128 
4129     // Add in the Base Offset if present.
4130     if (AddrMode.BaseOffs) {
4131       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4132       if (Result)
4133         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4134       else
4135         Result = V;
4136     }
4137 
4138     if (!Result)
4139       SunkAddr = Constant::getNullValue(Addr->getType());
4140     else
4141       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
4142   }
4143 
4144   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
4145 
4146   // If we have no uses, recursively delete the value and all dead instructions
4147   // using it.
4148   if (Repl->use_empty()) {
4149     // This can cause recursive deletion, which can invalidate our iterator.
4150     // Use a WeakVH to hold onto it in case this happens.
4151     Value *CurValue = &*CurInstIterator;
4152     WeakVH IterHandle(CurValue);
4153     BasicBlock *BB = CurInstIterator->getParent();
4154 
4155     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
4156 
4157     if (IterHandle != CurValue) {
4158       // If the iterator instruction was recursively deleted, start over at the
4159       // start of the block.
4160       CurInstIterator = BB->begin();
4161       SunkAddrs.clear();
4162     }
4163   }
4164   ++NumMemoryInsts;
4165   return true;
4166 }
4167 
4168 /// If there are any memory operands, use OptimizeMemoryInst to sink their
4169 /// address computing into the block when possible / profitable.
4170 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
4171   bool MadeChange = false;
4172 
4173   const TargetRegisterInfo *TRI =
4174       TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
4175   TargetLowering::AsmOperandInfoVector TargetConstraints =
4176       TLI->ParseConstraints(*DL, TRI, CS);
4177   unsigned ArgNo = 0;
4178   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4179     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4180 
4181     // Compute the constraint code and ConstraintType to use.
4182     TLI->ComputeConstraintToUse(OpInfo, SDValue());
4183 
4184     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4185         OpInfo.isIndirect) {
4186       Value *OpVal = CS->getArgOperand(ArgNo++);
4187       MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
4188     } else if (OpInfo.Type == InlineAsm::isInput)
4189       ArgNo++;
4190   }
4191 
4192   return MadeChange;
4193 }
4194 
4195 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4196 /// sign extensions.
4197 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4198   assert(!Inst->use_empty() && "Input must have at least one use");
4199   const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4200   bool IsSExt = isa<SExtInst>(FirstUser);
4201   Type *ExtTy = FirstUser->getType();
4202   for (const User *U : Inst->users()) {
4203     const Instruction *UI = cast<Instruction>(U);
4204     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4205       return false;
4206     Type *CurTy = UI->getType();
4207     // Same input and output types: Same instruction after CSE.
4208     if (CurTy == ExtTy)
4209       continue;
4210 
4211     // If IsSExt is true, we are in this situation:
4212     // a = Inst
4213     // b = sext ty1 a to ty2
4214     // c = sext ty1 a to ty3
4215     // Assuming ty2 is shorter than ty3, this could be turned into:
4216     // a = Inst
4217     // b = sext ty1 a to ty2
4218     // c = sext ty2 b to ty3
4219     // However, the last sext is not free.
4220     if (IsSExt)
4221       return false;
4222 
4223     // This is a ZExt, maybe this is free to extend from one type to another.
4224     // In that case, we would not account for a different use.
4225     Type *NarrowTy;
4226     Type *LargeTy;
4227     if (ExtTy->getScalarType()->getIntegerBitWidth() >
4228         CurTy->getScalarType()->getIntegerBitWidth()) {
4229       NarrowTy = CurTy;
4230       LargeTy = ExtTy;
4231     } else {
4232       NarrowTy = ExtTy;
4233       LargeTy = CurTy;
4234     }
4235 
4236     if (!TLI.isZExtFree(NarrowTy, LargeTy))
4237       return false;
4238   }
4239   // All uses are the same or can be derived from one another for free.
4240   return true;
4241 }
4242 
4243 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
4244 /// load instruction.
4245 /// If an ext(load) can be formed, it is returned via \p LI for the load
4246 /// and \p Inst for the extension.
4247 /// Otherwise LI == nullptr and Inst == nullptr.
4248 /// When some promotion happened, \p TPT contains the proper state to
4249 /// revert them.
4250 ///
4251 /// \return true when promoting was necessary to expose the ext(load)
4252 /// opportunity, false otherwise.
4253 ///
4254 /// Example:
4255 /// \code
4256 /// %ld = load i32* %addr
4257 /// %add = add nuw i32 %ld, 4
4258 /// %zext = zext i32 %add to i64
4259 /// \endcode
4260 /// =>
4261 /// \code
4262 /// %ld = load i32* %addr
4263 /// %zext = zext i32 %ld to i64
4264 /// %add = add nuw i64 %zext, 4
4265 /// \endcode
4266 /// Thanks to the promotion, we can match zext(load i32*) to i64.
4267 bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
4268                                     LoadInst *&LI, Instruction *&Inst,
4269                                     const SmallVectorImpl<Instruction *> &Exts,
4270                                     unsigned CreatedInstsCost = 0) {
4271   // Iterate over all the extensions to see if one form an ext(load).
4272   for (auto I : Exts) {
4273     // Check if we directly have ext(load).
4274     if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4275       Inst = I;
4276       // No promotion happened here.
4277       return false;
4278     }
4279     // Check whether or not we want to do any promotion.
4280     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4281       continue;
4282     // Get the action to perform the promotion.
4283     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
4284         I, InsertedInsts, *TLI, PromotedInsts);
4285     // Check if we can promote.
4286     if (!TPH)
4287       continue;
4288     // Save the current state.
4289     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4290         TPT.getRestorationPoint();
4291     SmallVector<Instruction *, 4> NewExts;
4292     unsigned NewCreatedInstsCost = 0;
4293     unsigned ExtCost = !TLI->isExtFree(I);
4294     // Promote.
4295     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4296                              &NewExts, nullptr, *TLI);
4297     assert(PromotedVal &&
4298            "TypePromotionHelper should have filtered out those cases");
4299 
4300     // We would be able to merge only one extension in a load.
4301     // Therefore, if we have more than 1 new extension we heuristically
4302     // cut this search path, because it means we degrade the code quality.
4303     // With exactly 2, the transformation is neutral, because we will merge
4304     // one extension but leave one. However, we optimistically keep going,
4305     // because the new extension may be removed too.
4306     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4307     // FIXME: It would be possible to propagate a negative value instead of
4308     // conservatively ceiling it to 0.
4309     TotalCreatedInstsCost =
4310         std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
4311     if (!StressExtLdPromotion &&
4312         (TotalCreatedInstsCost > 1 ||
4313          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
4314       // The promotion is not profitable, rollback to the previous state.
4315       TPT.rollback(LastKnownGood);
4316       continue;
4317     }
4318     // The promotion is profitable.
4319     // Check if it exposes an ext(load).
4320     (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
4321     if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4322                // If we have created a new extension, i.e., now we have two
4323                // extensions. We must make sure one of them is merged with
4324                // the load, otherwise we may degrade the code quality.
4325                (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4326       // Promotion happened.
4327       return true;
4328     // If this does not help to expose an ext(load) then, rollback.
4329     TPT.rollback(LastKnownGood);
4330   }
4331   // None of the extension can form an ext(load).
4332   LI = nullptr;
4333   Inst = nullptr;
4334   return false;
4335 }
4336 
4337 /// Move a zext or sext fed by a load into the same basic block as the load,
4338 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
4339 /// extend into the load.
4340 /// \p I[in/out] the extension may be modified during the process if some
4341 /// promotions apply.
4342 ///
4343 bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
4344   // ExtLoad formation infrastructure requires TLI to be effective.
4345   if (!TLI)
4346     return false;
4347 
4348   // Try to promote a chain of computation if it allows to form
4349   // an extended load.
4350   TypePromotionTransaction TPT;
4351   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4352     TPT.getRestorationPoint();
4353   SmallVector<Instruction *, 1> Exts;
4354   Exts.push_back(I);
4355   // Look for a load being extended.
4356   LoadInst *LI = nullptr;
4357   Instruction *OldExt = I;
4358   bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
4359   if (!LI || !I) {
4360     assert(!HasPromoted && !LI && "If we did not match any load instruction "
4361                                   "the code must remain the same");
4362     I = OldExt;
4363     return false;
4364   }
4365 
4366   // If they're already in the same block, there's nothing to do.
4367   // Make the cheap checks first if we did not promote.
4368   // If we promoted, we need to check if it is indeed profitable.
4369   if (!HasPromoted && LI->getParent() == I->getParent())
4370     return false;
4371 
4372   EVT VT = TLI->getValueType(*DL, I->getType());
4373   EVT LoadVT = TLI->getValueType(*DL, LI->getType());
4374 
4375   // If the load has other users and the truncate is not free, this probably
4376   // isn't worthwhile.
4377   if (!LI->hasOneUse() &&
4378       (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
4379       !TLI->isTruncateFree(I->getType(), LI->getType())) {
4380     I = OldExt;
4381     TPT.rollback(LastKnownGood);
4382     return false;
4383   }
4384 
4385   // Check whether the target supports casts folded into loads.
4386   unsigned LType;
4387   if (isa<ZExtInst>(I))
4388     LType = ISD::ZEXTLOAD;
4389   else {
4390     assert(isa<SExtInst>(I) && "Unexpected ext type!");
4391     LType = ISD::SEXTLOAD;
4392   }
4393   if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
4394     I = OldExt;
4395     TPT.rollback(LastKnownGood);
4396     return false;
4397   }
4398 
4399   // Move the extend into the same block as the load, so that SelectionDAG
4400   // can fold it.
4401   TPT.commit();
4402   I->removeFromParent();
4403   I->insertAfter(LI);
4404   // CGP does not check if the zext would be speculatively executed when moved
4405   // to the same basic block as the load. Preserving its original location would
4406   // pessimize the debugging experience, as well as negatively impact the
4407   // quality of sample pgo. We don't want to use "line 0" as that has a
4408   // size cost in the line-table section and logically the zext can be seen as
4409   // part of the load. Therefore we conservatively reuse the same debug location
4410   // for the load and the zext.
4411   I->setDebugLoc(LI->getDebugLoc());
4412   ++NumExtsMoved;
4413   return true;
4414 }
4415 
4416 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
4417   BasicBlock *DefBB = I->getParent();
4418 
4419   // If the result of a {s|z}ext and its source are both live out, rewrite all
4420   // other uses of the source with result of extension.
4421   Value *Src = I->getOperand(0);
4422   if (Src->hasOneUse())
4423     return false;
4424 
4425   // Only do this xform if truncating is free.
4426   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
4427     return false;
4428 
4429   // Only safe to perform the optimization if the source is also defined in
4430   // this block.
4431   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
4432     return false;
4433 
4434   bool DefIsLiveOut = false;
4435   for (User *U : I->users()) {
4436     Instruction *UI = cast<Instruction>(U);
4437 
4438     // Figure out which BB this ext is used in.
4439     BasicBlock *UserBB = UI->getParent();
4440     if (UserBB == DefBB) continue;
4441     DefIsLiveOut = true;
4442     break;
4443   }
4444   if (!DefIsLiveOut)
4445     return false;
4446 
4447   // Make sure none of the uses are PHI nodes.
4448   for (User *U : Src->users()) {
4449     Instruction *UI = cast<Instruction>(U);
4450     BasicBlock *UserBB = UI->getParent();
4451     if (UserBB == DefBB) continue;
4452     // Be conservative. We don't want this xform to end up introducing
4453     // reloads just before load / store instructions.
4454     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
4455       return false;
4456   }
4457 
4458   // InsertedTruncs - Only insert one trunc in each block once.
4459   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4460 
4461   bool MadeChange = false;
4462   for (Use &U : Src->uses()) {
4463     Instruction *User = cast<Instruction>(U.getUser());
4464 
4465     // Figure out which BB this ext is used in.
4466     BasicBlock *UserBB = User->getParent();
4467     if (UserBB == DefBB) continue;
4468 
4469     // Both src and def are live in this block. Rewrite the use.
4470     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4471 
4472     if (!InsertedTrunc) {
4473       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
4474       assert(InsertPt != UserBB->end());
4475       InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
4476       InsertedInsts.insert(InsertedTrunc);
4477     }
4478 
4479     // Replace a use of the {s|z}ext source with a use of the result.
4480     U = InsertedTrunc;
4481     ++NumExtUses;
4482     MadeChange = true;
4483   }
4484 
4485   return MadeChange;
4486 }
4487 
4488 // Find loads whose uses only use some of the loaded value's bits.  Add an "and"
4489 // just after the load if the target can fold this into one extload instruction,
4490 // with the hope of eliminating some of the other later "and" instructions using
4491 // the loaded value.  "and"s that are made trivially redundant by the insertion
4492 // of the new "and" are removed by this function, while others (e.g. those whose
4493 // path from the load goes through a phi) are left for isel to potentially
4494 // remove.
4495 //
4496 // For example:
4497 //
4498 // b0:
4499 //   x = load i32
4500 //   ...
4501 // b1:
4502 //   y = and x, 0xff
4503 //   z = use y
4504 //
4505 // becomes:
4506 //
4507 // b0:
4508 //   x = load i32
4509 //   x' = and x, 0xff
4510 //   ...
4511 // b1:
4512 //   z = use x'
4513 //
4514 // whereas:
4515 //
4516 // b0:
4517 //   x1 = load i32
4518 //   ...
4519 // b1:
4520 //   x2 = load i32
4521 //   ...
4522 // b2:
4523 //   x = phi x1, x2
4524 //   y = and x, 0xff
4525 //
4526 // becomes (after a call to optimizeLoadExt for each load):
4527 //
4528 // b0:
4529 //   x1 = load i32
4530 //   x1' = and x1, 0xff
4531 //   ...
4532 // b1:
4533 //   x2 = load i32
4534 //   x2' = and x2, 0xff
4535 //   ...
4536 // b2:
4537 //   x = phi x1', x2'
4538 //   y = and x, 0xff
4539 //
4540 
4541 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4542 
4543   if (!Load->isSimple() ||
4544       !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4545     return false;
4546 
4547   // Skip loads we've already transformed or have no reason to transform.
4548   if (Load->hasOneUse()) {
4549     User *LoadUser = *Load->user_begin();
4550     if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4551         !dyn_cast<PHINode>(LoadUser))
4552       return false;
4553   }
4554 
4555   // Look at all uses of Load, looking through phis, to determine how many bits
4556   // of the loaded value are needed.
4557   SmallVector<Instruction *, 8> WorkList;
4558   SmallPtrSet<Instruction *, 16> Visited;
4559   SmallVector<Instruction *, 8> AndsToMaybeRemove;
4560   for (auto *U : Load->users())
4561     WorkList.push_back(cast<Instruction>(U));
4562 
4563   EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4564   unsigned BitWidth = LoadResultVT.getSizeInBits();
4565   APInt DemandBits(BitWidth, 0);
4566   APInt WidestAndBits(BitWidth, 0);
4567 
4568   while (!WorkList.empty()) {
4569     Instruction *I = WorkList.back();
4570     WorkList.pop_back();
4571 
4572     // Break use-def graph loops.
4573     if (!Visited.insert(I).second)
4574       continue;
4575 
4576     // For a PHI node, push all of its users.
4577     if (auto *Phi = dyn_cast<PHINode>(I)) {
4578       for (auto *U : Phi->users())
4579         WorkList.push_back(cast<Instruction>(U));
4580       continue;
4581     }
4582 
4583     switch (I->getOpcode()) {
4584     case llvm::Instruction::And: {
4585       auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4586       if (!AndC)
4587         return false;
4588       APInt AndBits = AndC->getValue();
4589       DemandBits |= AndBits;
4590       // Keep track of the widest and mask we see.
4591       if (AndBits.ugt(WidestAndBits))
4592         WidestAndBits = AndBits;
4593       if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4594         AndsToMaybeRemove.push_back(I);
4595       break;
4596     }
4597 
4598     case llvm::Instruction::Shl: {
4599       auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4600       if (!ShlC)
4601         return false;
4602       uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4603       auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4604       DemandBits |= ShlDemandBits;
4605       break;
4606     }
4607 
4608     case llvm::Instruction::Trunc: {
4609       EVT TruncVT = TLI->getValueType(*DL, I->getType());
4610       unsigned TruncBitWidth = TruncVT.getSizeInBits();
4611       auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4612       DemandBits |= TruncBits;
4613       break;
4614     }
4615 
4616     default:
4617       return false;
4618     }
4619   }
4620 
4621   uint32_t ActiveBits = DemandBits.getActiveBits();
4622   // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4623   // target even if isLoadExtLegal says an i1 EXTLOAD is valid.  For example,
4624   // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4625   // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4626   // followed by an AND.
4627   // TODO: Look into removing this restriction by fixing backends to either
4628   // return false for isLoadExtLegal for i1 or have them select this pattern to
4629   // a single instruction.
4630   //
4631   // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4632   // mask, since these are the only ands that will be removed by isel.
4633   if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4634       WidestAndBits != DemandBits)
4635     return false;
4636 
4637   LLVMContext &Ctx = Load->getType()->getContext();
4638   Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4639   EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4640 
4641   // Reject cases that won't be matched as extloads.
4642   if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4643       !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4644     return false;
4645 
4646   IRBuilder<> Builder(Load->getNextNode());
4647   auto *NewAnd = dyn_cast<Instruction>(
4648       Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4649 
4650   // Replace all uses of load with new and (except for the use of load in the
4651   // new and itself).
4652   Load->replaceAllUsesWith(NewAnd);
4653   NewAnd->setOperand(0, Load);
4654 
4655   // Remove any and instructions that are now redundant.
4656   for (auto *And : AndsToMaybeRemove)
4657     // Check that the and mask is the same as the one we decided to put on the
4658     // new and.
4659     if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4660       And->replaceAllUsesWith(NewAnd);
4661       if (&*CurInstIterator == And)
4662         CurInstIterator = std::next(And->getIterator());
4663       And->eraseFromParent();
4664       ++NumAndUses;
4665     }
4666 
4667   ++NumAndsAdded;
4668   return true;
4669 }
4670 
4671 /// Check if V (an operand of a select instruction) is an expensive instruction
4672 /// that is only used once.
4673 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4674   auto *I = dyn_cast<Instruction>(V);
4675   // If it's safe to speculatively execute, then it should not have side
4676   // effects; therefore, it's safe to sink and possibly *not* execute.
4677   return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4678          TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
4679 }
4680 
4681 /// Returns true if a SelectInst should be turned into an explicit branch.
4682 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
4683                                                 const TargetLowering *TLI,
4684                                                 SelectInst *SI) {
4685   // If even a predictable select is cheap, then a branch can't be cheaper.
4686   if (!TLI->isPredictableSelectExpensive())
4687     return false;
4688 
4689   // FIXME: This should use the same heuristics as IfConversion to determine
4690   // whether a select is better represented as a branch.
4691 
4692   // If metadata tells us that the select condition is obviously predictable,
4693   // then we want to replace the select with a branch.
4694   uint64_t TrueWeight, FalseWeight;
4695   if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4696     uint64_t Max = std::max(TrueWeight, FalseWeight);
4697     uint64_t Sum = TrueWeight + FalseWeight;
4698     if (Sum != 0) {
4699       auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4700       if (Probability > TLI->getPredictableBranchThreshold())
4701         return true;
4702     }
4703   }
4704 
4705   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4706 
4707   // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4708   // comparison condition. If the compare has more than one use, there's
4709   // probably another cmov or setcc around, so it's not worth emitting a branch.
4710   if (!Cmp || !Cmp->hasOneUse())
4711     return false;
4712 
4713   // If either operand of the select is expensive and only needed on one side
4714   // of the select, we should form a branch.
4715   if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4716       sinkSelectOperand(TTI, SI->getFalseValue()))
4717     return true;
4718 
4719   return false;
4720 }
4721 
4722 /// If \p isTrue is true, return the true value of \p SI, otherwise return
4723 /// false value of \p SI. If the true/false value of \p SI is defined by any
4724 /// select instructions in \p Selects, look through the defining select
4725 /// instruction until the true/false value is not defined in \p Selects.
4726 static Value *getTrueOrFalseValue(
4727     SelectInst *SI, bool isTrue,
4728     const SmallPtrSet<const Instruction *, 2> &Selects) {
4729   Value *V;
4730 
4731   for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4732        DefSI = dyn_cast<SelectInst>(V)) {
4733     assert(DefSI->getCondition() == SI->getCondition() &&
4734            "The condition of DefSI does not match with SI");
4735     V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4736   }
4737   return V;
4738 }
4739 
4740 /// If we have a SelectInst that will likely profit from branch prediction,
4741 /// turn it into a branch.
4742 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
4743   // Find all consecutive select instructions that share the same condition.
4744   SmallVector<SelectInst *, 2> ASI;
4745   ASI.push_back(SI);
4746   for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4747        It != SI->getParent()->end(); ++It) {
4748     SelectInst *I = dyn_cast<SelectInst>(&*It);
4749     if (I && SI->getCondition() == I->getCondition()) {
4750       ASI.push_back(I);
4751     } else {
4752       break;
4753     }
4754   }
4755 
4756   SelectInst *LastSI = ASI.back();
4757   // Increment the current iterator to skip all the rest of select instructions
4758   // because they will be either "not lowered" or "all lowered" to branch.
4759   CurInstIterator = std::next(LastSI->getIterator());
4760 
4761   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4762 
4763   // Can we convert the 'select' to CF ?
4764   if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4765       SI->getMetadata(LLVMContext::MD_unpredictable))
4766     return false;
4767 
4768   TargetLowering::SelectSupportKind SelectKind;
4769   if (VectorCond)
4770     SelectKind = TargetLowering::VectorMaskSelect;
4771   else if (SI->getType()->isVectorTy())
4772     SelectKind = TargetLowering::ScalarCondVectorVal;
4773   else
4774     SelectKind = TargetLowering::ScalarValSelect;
4775 
4776   if (TLI->isSelectSupported(SelectKind) &&
4777       !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4778     return false;
4779 
4780   ModifiedDT = true;
4781 
4782   // Transform a sequence like this:
4783   //    start:
4784   //       %cmp = cmp uge i32 %a, %b
4785   //       %sel = select i1 %cmp, i32 %c, i32 %d
4786   //
4787   // Into:
4788   //    start:
4789   //       %cmp = cmp uge i32 %a, %b
4790   //       br i1 %cmp, label %select.true, label %select.false
4791   //    select.true:
4792   //       br label %select.end
4793   //    select.false:
4794   //       br label %select.end
4795   //    select.end:
4796   //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4797   //
4798   // In addition, we may sink instructions that produce %c or %d from
4799   // the entry block into the destination(s) of the new branch.
4800   // If the true or false blocks do not contain a sunken instruction, that
4801   // block and its branch may be optimized away. In that case, one side of the
4802   // first branch will point directly to select.end, and the corresponding PHI
4803   // predecessor block will be the start block.
4804 
4805   // First, we split the block containing the select into 2 blocks.
4806   BasicBlock *StartBlock = SI->getParent();
4807   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
4808   BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
4809 
4810   // Delete the unconditional branch that was just created by the split.
4811   StartBlock->getTerminator()->eraseFromParent();
4812 
4813   // These are the new basic blocks for the conditional branch.
4814   // At least one will become an actual new basic block.
4815   BasicBlock *TrueBlock = nullptr;
4816   BasicBlock *FalseBlock = nullptr;
4817   BranchInst *TrueBranch = nullptr;
4818   BranchInst *FalseBranch = nullptr;
4819 
4820   // Sink expensive instructions into the conditional blocks to avoid executing
4821   // them speculatively.
4822   for (SelectInst *SI : ASI) {
4823     if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4824       if (TrueBlock == nullptr) {
4825         TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4826                                        EndBlock->getParent(), EndBlock);
4827         TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4828       }
4829       auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4830       TrueInst->moveBefore(TrueBranch);
4831     }
4832     if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4833       if (FalseBlock == nullptr) {
4834         FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4835                                         EndBlock->getParent(), EndBlock);
4836         FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4837       }
4838       auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4839       FalseInst->moveBefore(FalseBranch);
4840     }
4841   }
4842 
4843   // If there was nothing to sink, then arbitrarily choose the 'false' side
4844   // for a new input value to the PHI.
4845   if (TrueBlock == FalseBlock) {
4846     assert(TrueBlock == nullptr &&
4847            "Unexpected basic block transform while optimizing select");
4848 
4849     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4850                                     EndBlock->getParent(), EndBlock);
4851     BranchInst::Create(EndBlock, FalseBlock);
4852   }
4853 
4854   // Insert the real conditional branch based on the original condition.
4855   // If we did not create a new block for one of the 'true' or 'false' paths
4856   // of the condition, it means that side of the branch goes to the end block
4857   // directly and the path originates from the start block from the point of
4858   // view of the new PHI.
4859   BasicBlock *TT, *FT;
4860   if (TrueBlock == nullptr) {
4861     TT = EndBlock;
4862     FT = FalseBlock;
4863     TrueBlock = StartBlock;
4864   } else if (FalseBlock == nullptr) {
4865     TT = TrueBlock;
4866     FT = EndBlock;
4867     FalseBlock = StartBlock;
4868   } else {
4869     TT = TrueBlock;
4870     FT = FalseBlock;
4871   }
4872   IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
4873 
4874   SmallPtrSet<const Instruction *, 2> INS;
4875   INS.insert(ASI.begin(), ASI.end());
4876   // Use reverse iterator because later select may use the value of the
4877   // earlier select, and we need to propagate value through earlier select
4878   // to get the PHI operand.
4879   for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4880     SelectInst *SI = *It;
4881     // The select itself is replaced with a PHI Node.
4882     PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4883     PN->takeName(SI);
4884     PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4885     PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
4886 
4887     SI->replaceAllUsesWith(PN);
4888     SI->eraseFromParent();
4889     INS.erase(SI);
4890     ++NumSelectsExpanded;
4891   }
4892 
4893   // Instruct OptimizeBlock to skip to the next block.
4894   CurInstIterator = StartBlock->end();
4895   return true;
4896 }
4897 
4898 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
4899   SmallVector<int, 16> Mask(SVI->getShuffleMask());
4900   int SplatElem = -1;
4901   for (unsigned i = 0; i < Mask.size(); ++i) {
4902     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4903       return false;
4904     SplatElem = Mask[i];
4905   }
4906 
4907   return true;
4908 }
4909 
4910 /// Some targets have expensive vector shifts if the lanes aren't all the same
4911 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4912 /// it's often worth sinking a shufflevector splat down to its use so that
4913 /// codegen can spot all lanes are identical.
4914 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
4915   BasicBlock *DefBB = SVI->getParent();
4916 
4917   // Only do this xform if variable vector shifts are particularly expensive.
4918   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4919     return false;
4920 
4921   // We only expect better codegen by sinking a shuffle if we can recognise a
4922   // constant splat.
4923   if (!isBroadcastShuffle(SVI))
4924     return false;
4925 
4926   // InsertedShuffles - Only insert a shuffle in each block once.
4927   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4928 
4929   bool MadeChange = false;
4930   for (User *U : SVI->users()) {
4931     Instruction *UI = cast<Instruction>(U);
4932 
4933     // Figure out which BB this ext is used in.
4934     BasicBlock *UserBB = UI->getParent();
4935     if (UserBB == DefBB) continue;
4936 
4937     // For now only apply this when the splat is used by a shift instruction.
4938     if (!UI->isShift()) continue;
4939 
4940     // Everything checks out, sink the shuffle if the user's block doesn't
4941     // already have a copy.
4942     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4943 
4944     if (!InsertedShuffle) {
4945       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
4946       assert(InsertPt != UserBB->end());
4947       InsertedShuffle =
4948           new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4949                                 SVI->getOperand(2), "", &*InsertPt);
4950     }
4951 
4952     UI->replaceUsesOfWith(SVI, InsertedShuffle);
4953     MadeChange = true;
4954   }
4955 
4956   // If we removed all uses, nuke the shuffle.
4957   if (SVI->use_empty()) {
4958     SVI->eraseFromParent();
4959     MadeChange = true;
4960   }
4961 
4962   return MadeChange;
4963 }
4964 
4965 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4966   if (!TLI || !DL)
4967     return false;
4968 
4969   Value *Cond = SI->getCondition();
4970   Type *OldType = Cond->getType();
4971   LLVMContext &Context = Cond->getContext();
4972   MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4973   unsigned RegWidth = RegType.getSizeInBits();
4974 
4975   if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4976     return false;
4977 
4978   // If the register width is greater than the type width, expand the condition
4979   // of the switch instruction and each case constant to the width of the
4980   // register. By widening the type of the switch condition, subsequent
4981   // comparisons (for case comparisons) will not need to be extended to the
4982   // preferred register width, so we will potentially eliminate N-1 extends,
4983   // where N is the number of cases in the switch.
4984   auto *NewType = Type::getIntNTy(Context, RegWidth);
4985 
4986   // Zero-extend the switch condition and case constants unless the switch
4987   // condition is a function argument that is already being sign-extended.
4988   // In that case, we can avoid an unnecessary mask/extension by sign-extending
4989   // everything instead.
4990   Instruction::CastOps ExtType = Instruction::ZExt;
4991   if (auto *Arg = dyn_cast<Argument>(Cond))
4992     if (Arg->hasSExtAttr())
4993       ExtType = Instruction::SExt;
4994 
4995   auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4996   ExtInst->insertBefore(SI);
4997   SI->setCondition(ExtInst);
4998   for (SwitchInst::CaseIt Case : SI->cases()) {
4999     APInt NarrowConst = Case.getCaseValue()->getValue();
5000     APInt WideConst = (ExtType == Instruction::ZExt) ?
5001                       NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5002     Case.setValue(ConstantInt::get(Context, WideConst));
5003   }
5004 
5005   return true;
5006 }
5007 
5008 namespace {
5009 /// \brief Helper class to promote a scalar operation to a vector one.
5010 /// This class is used to move downward extractelement transition.
5011 /// E.g.,
5012 /// a = vector_op <2 x i32>
5013 /// b = extractelement <2 x i32> a, i32 0
5014 /// c = scalar_op b
5015 /// store c
5016 ///
5017 /// =>
5018 /// a = vector_op <2 x i32>
5019 /// c = vector_op a (equivalent to scalar_op on the related lane)
5020 /// * d = extractelement <2 x i32> c, i32 0
5021 /// * store d
5022 /// Assuming both extractelement and store can be combine, we get rid of the
5023 /// transition.
5024 class VectorPromoteHelper {
5025   /// DataLayout associated with the current module.
5026   const DataLayout &DL;
5027 
5028   /// Used to perform some checks on the legality of vector operations.
5029   const TargetLowering &TLI;
5030 
5031   /// Used to estimated the cost of the promoted chain.
5032   const TargetTransformInfo &TTI;
5033 
5034   /// The transition being moved downwards.
5035   Instruction *Transition;
5036   /// The sequence of instructions to be promoted.
5037   SmallVector<Instruction *, 4> InstsToBePromoted;
5038   /// Cost of combining a store and an extract.
5039   unsigned StoreExtractCombineCost;
5040   /// Instruction that will be combined with the transition.
5041   Instruction *CombineInst;
5042 
5043   /// \brief The instruction that represents the current end of the transition.
5044   /// Since we are faking the promotion until we reach the end of the chain
5045   /// of computation, we need a way to get the current end of the transition.
5046   Instruction *getEndOfTransition() const {
5047     if (InstsToBePromoted.empty())
5048       return Transition;
5049     return InstsToBePromoted.back();
5050   }
5051 
5052   /// \brief Return the index of the original value in the transition.
5053   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5054   /// c, is at index 0.
5055   unsigned getTransitionOriginalValueIdx() const {
5056     assert(isa<ExtractElementInst>(Transition) &&
5057            "Other kind of transitions are not supported yet");
5058     return 0;
5059   }
5060 
5061   /// \brief Return the index of the index in the transition.
5062   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5063   /// is at index 1.
5064   unsigned getTransitionIdx() const {
5065     assert(isa<ExtractElementInst>(Transition) &&
5066            "Other kind of transitions are not supported yet");
5067     return 1;
5068   }
5069 
5070   /// \brief Get the type of the transition.
5071   /// This is the type of the original value.
5072   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5073   /// transition is <2 x i32>.
5074   Type *getTransitionType() const {
5075     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5076   }
5077 
5078   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5079   /// I.e., we have the following sequence:
5080   /// Def = Transition <ty1> a to <ty2>
5081   /// b = ToBePromoted <ty2> Def, ...
5082   /// =>
5083   /// b = ToBePromoted <ty1> a, ...
5084   /// Def = Transition <ty1> ToBePromoted to <ty2>
5085   void promoteImpl(Instruction *ToBePromoted);
5086 
5087   /// \brief Check whether or not it is profitable to promote all the
5088   /// instructions enqueued to be promoted.
5089   bool isProfitableToPromote() {
5090     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5091     unsigned Index = isa<ConstantInt>(ValIdx)
5092                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
5093                          : -1;
5094     Type *PromotedType = getTransitionType();
5095 
5096     StoreInst *ST = cast<StoreInst>(CombineInst);
5097     unsigned AS = ST->getPointerAddressSpace();
5098     unsigned Align = ST->getAlignment();
5099     // Check if this store is supported.
5100     if (!TLI.allowsMisalignedMemoryAccesses(
5101             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5102             Align)) {
5103       // If this is not supported, there is no way we can combine
5104       // the extract with the store.
5105       return false;
5106     }
5107 
5108     // The scalar chain of computation has to pay for the transition
5109     // scalar to vector.
5110     // The vector chain has to account for the combining cost.
5111     uint64_t ScalarCost =
5112         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5113     uint64_t VectorCost = StoreExtractCombineCost;
5114     for (const auto &Inst : InstsToBePromoted) {
5115       // Compute the cost.
5116       // By construction, all instructions being promoted are arithmetic ones.
5117       // Moreover, one argument is a constant that can be viewed as a splat
5118       // constant.
5119       Value *Arg0 = Inst->getOperand(0);
5120       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5121                             isa<ConstantFP>(Arg0);
5122       TargetTransformInfo::OperandValueKind Arg0OVK =
5123           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5124                          : TargetTransformInfo::OK_AnyValue;
5125       TargetTransformInfo::OperandValueKind Arg1OVK =
5126           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5127                           : TargetTransformInfo::OK_AnyValue;
5128       ScalarCost += TTI.getArithmeticInstrCost(
5129           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5130       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5131                                                Arg0OVK, Arg1OVK);
5132     }
5133     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5134                  << ScalarCost << "\nVector: " << VectorCost << '\n');
5135     return ScalarCost > VectorCost;
5136   }
5137 
5138   /// \brief Generate a constant vector with \p Val with the same
5139   /// number of elements as the transition.
5140   /// \p UseSplat defines whether or not \p Val should be replicated
5141   /// across the whole vector.
5142   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5143   /// otherwise we generate a vector with as many undef as possible:
5144   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5145   /// used at the index of the extract.
5146   Value *getConstantVector(Constant *Val, bool UseSplat) const {
5147     unsigned ExtractIdx = UINT_MAX;
5148     if (!UseSplat) {
5149       // If we cannot determine where the constant must be, we have to
5150       // use a splat constant.
5151       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5152       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5153         ExtractIdx = CstVal->getSExtValue();
5154       else
5155         UseSplat = true;
5156     }
5157 
5158     unsigned End = getTransitionType()->getVectorNumElements();
5159     if (UseSplat)
5160       return ConstantVector::getSplat(End, Val);
5161 
5162     SmallVector<Constant *, 4> ConstVec;
5163     UndefValue *UndefVal = UndefValue::get(Val->getType());
5164     for (unsigned Idx = 0; Idx != End; ++Idx) {
5165       if (Idx == ExtractIdx)
5166         ConstVec.push_back(Val);
5167       else
5168         ConstVec.push_back(UndefVal);
5169     }
5170     return ConstantVector::get(ConstVec);
5171   }
5172 
5173   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5174   /// in \p Use can trigger undefined behavior.
5175   static bool canCauseUndefinedBehavior(const Instruction *Use,
5176                                         unsigned OperandIdx) {
5177     // This is not safe to introduce undef when the operand is on
5178     // the right hand side of a division-like instruction.
5179     if (OperandIdx != 1)
5180       return false;
5181     switch (Use->getOpcode()) {
5182     default:
5183       return false;
5184     case Instruction::SDiv:
5185     case Instruction::UDiv:
5186     case Instruction::SRem:
5187     case Instruction::URem:
5188       return true;
5189     case Instruction::FDiv:
5190     case Instruction::FRem:
5191       return !Use->hasNoNaNs();
5192     }
5193     llvm_unreachable(nullptr);
5194   }
5195 
5196 public:
5197   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5198                       const TargetTransformInfo &TTI, Instruction *Transition,
5199                       unsigned CombineCost)
5200       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
5201         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5202     assert(Transition && "Do not know how to promote null");
5203   }
5204 
5205   /// \brief Check if we can promote \p ToBePromoted to \p Type.
5206   bool canPromote(const Instruction *ToBePromoted) const {
5207     // We could support CastInst too.
5208     return isa<BinaryOperator>(ToBePromoted);
5209   }
5210 
5211   /// \brief Check if it is profitable to promote \p ToBePromoted
5212   /// by moving downward the transition through.
5213   bool shouldPromote(const Instruction *ToBePromoted) const {
5214     // Promote only if all the operands can be statically expanded.
5215     // Indeed, we do not want to introduce any new kind of transitions.
5216     for (const Use &U : ToBePromoted->operands()) {
5217       const Value *Val = U.get();
5218       if (Val == getEndOfTransition()) {
5219         // If the use is a division and the transition is on the rhs,
5220         // we cannot promote the operation, otherwise we may create a
5221         // division by zero.
5222         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5223           return false;
5224         continue;
5225       }
5226       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5227           !isa<ConstantFP>(Val))
5228         return false;
5229     }
5230     // Check that the resulting operation is legal.
5231     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5232     if (!ISDOpcode)
5233       return false;
5234     return StressStoreExtract ||
5235            TLI.isOperationLegalOrCustom(
5236                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
5237   }
5238 
5239   /// \brief Check whether or not \p Use can be combined
5240   /// with the transition.
5241   /// I.e., is it possible to do Use(Transition) => AnotherUse?
5242   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5243 
5244   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5245   void enqueueForPromotion(Instruction *ToBePromoted) {
5246     InstsToBePromoted.push_back(ToBePromoted);
5247   }
5248 
5249   /// \brief Set the instruction that will be combined with the transition.
5250   void recordCombineInstruction(Instruction *ToBeCombined) {
5251     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5252     CombineInst = ToBeCombined;
5253   }
5254 
5255   /// \brief Promote all the instructions enqueued for promotion if it is
5256   /// is profitable.
5257   /// \return True if the promotion happened, false otherwise.
5258   bool promote() {
5259     // Check if there is something to promote.
5260     // Right now, if we do not have anything to combine with,
5261     // we assume the promotion is not profitable.
5262     if (InstsToBePromoted.empty() || !CombineInst)
5263       return false;
5264 
5265     // Check cost.
5266     if (!StressStoreExtract && !isProfitableToPromote())
5267       return false;
5268 
5269     // Promote.
5270     for (auto &ToBePromoted : InstsToBePromoted)
5271       promoteImpl(ToBePromoted);
5272     InstsToBePromoted.clear();
5273     return true;
5274   }
5275 };
5276 } // End of anonymous namespace.
5277 
5278 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5279   // At this point, we know that all the operands of ToBePromoted but Def
5280   // can be statically promoted.
5281   // For Def, we need to use its parameter in ToBePromoted:
5282   // b = ToBePromoted ty1 a
5283   // Def = Transition ty1 b to ty2
5284   // Move the transition down.
5285   // 1. Replace all uses of the promoted operation by the transition.
5286   // = ... b => = ... Def.
5287   assert(ToBePromoted->getType() == Transition->getType() &&
5288          "The type of the result of the transition does not match "
5289          "the final type");
5290   ToBePromoted->replaceAllUsesWith(Transition);
5291   // 2. Update the type of the uses.
5292   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5293   Type *TransitionTy = getTransitionType();
5294   ToBePromoted->mutateType(TransitionTy);
5295   // 3. Update all the operands of the promoted operation with promoted
5296   // operands.
5297   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5298   for (Use &U : ToBePromoted->operands()) {
5299     Value *Val = U.get();
5300     Value *NewVal = nullptr;
5301     if (Val == Transition)
5302       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5303     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5304              isa<ConstantFP>(Val)) {
5305       // Use a splat constant if it is not safe to use undef.
5306       NewVal = getConstantVector(
5307           cast<Constant>(Val),
5308           isa<UndefValue>(Val) ||
5309               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5310     } else
5311       llvm_unreachable("Did you modified shouldPromote and forgot to update "
5312                        "this?");
5313     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5314   }
5315   Transition->removeFromParent();
5316   Transition->insertAfter(ToBePromoted);
5317   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5318 }
5319 
5320 /// Some targets can do store(extractelement) with one instruction.
5321 /// Try to push the extractelement towards the stores when the target
5322 /// has this feature and this is profitable.
5323 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
5324   unsigned CombineCost = UINT_MAX;
5325   if (DisableStoreExtract || !TLI ||
5326       (!StressStoreExtract &&
5327        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5328                                        Inst->getOperand(1), CombineCost)))
5329     return false;
5330 
5331   // At this point we know that Inst is a vector to scalar transition.
5332   // Try to move it down the def-use chain, until:
5333   // - We can combine the transition with its single use
5334   //   => we got rid of the transition.
5335   // - We escape the current basic block
5336   //   => we would need to check that we are moving it at a cheaper place and
5337   //      we do not do that for now.
5338   BasicBlock *Parent = Inst->getParent();
5339   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
5340   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
5341   // If the transition has more than one use, assume this is not going to be
5342   // beneficial.
5343   while (Inst->hasOneUse()) {
5344     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5345     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5346 
5347     if (ToBePromoted->getParent() != Parent) {
5348       DEBUG(dbgs() << "Instruction to promote is in a different block ("
5349                    << ToBePromoted->getParent()->getName()
5350                    << ") than the transition (" << Parent->getName() << ").\n");
5351       return false;
5352     }
5353 
5354     if (VPH.canCombine(ToBePromoted)) {
5355       DEBUG(dbgs() << "Assume " << *Inst << '\n'
5356                    << "will be combined with: " << *ToBePromoted << '\n');
5357       VPH.recordCombineInstruction(ToBePromoted);
5358       bool Changed = VPH.promote();
5359       NumStoreExtractExposed += Changed;
5360       return Changed;
5361     }
5362 
5363     DEBUG(dbgs() << "Try promoting.\n");
5364     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5365       return false;
5366 
5367     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5368 
5369     VPH.enqueueForPromotion(ToBePromoted);
5370     Inst = ToBePromoted;
5371   }
5372   return false;
5373 }
5374 
5375 /// For the instruction sequence of store below, F and I values
5376 /// are bundled together as an i64 value before being stored into memory.
5377 /// Sometimes it is more efficent to generate separate stores for F and I,
5378 /// which can remove the bitwise instructions or sink them to colder places.
5379 ///
5380 ///   (store (or (zext (bitcast F to i32) to i64),
5381 ///              (shl (zext I to i64), 32)), addr)  -->
5382 ///   (store F, addr) and (store I, addr+4)
5383 ///
5384 /// Similarly, splitting for other merged store can also be beneficial, like:
5385 /// For pair of {i32, i32}, i64 store --> two i32 stores.
5386 /// For pair of {i32, i16}, i64 store --> two i32 stores.
5387 /// For pair of {i16, i16}, i32 store --> two i16 stores.
5388 /// For pair of {i16, i8},  i32 store --> two i16 stores.
5389 /// For pair of {i8, i8},   i16 store --> two i8 stores.
5390 ///
5391 /// We allow each target to determine specifically which kind of splitting is
5392 /// supported.
5393 ///
5394 /// The store patterns are commonly seen from the simple code snippet below
5395 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5396 ///   void goo(const std::pair<int, float> &);
5397 ///   hoo() {
5398 ///     ...
5399 ///     goo(std::make_pair(tmp, ftmp));
5400 ///     ...
5401 ///   }
5402 ///
5403 /// Although we already have similar splitting in DAG Combine, we duplicate
5404 /// it in CodeGenPrepare to catch the case in which pattern is across
5405 /// multiple BBs. The logic in DAG Combine is kept to catch case generated
5406 /// during code expansion.
5407 static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5408                                 const TargetLowering &TLI) {
5409   // Handle simple but common cases only.
5410   Type *StoreType = SI.getValueOperand()->getType();
5411   if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5412       DL.getTypeSizeInBits(StoreType) == 0)
5413     return false;
5414 
5415   unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5416   Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5417   if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5418       DL.getTypeSizeInBits(SplitStoreType))
5419     return false;
5420 
5421   // Match the following patterns:
5422   // (store (or (zext LValue to i64),
5423   //            (shl (zext HValue to i64), 32)), HalfValBitSize)
5424   //  or
5425   // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5426   //            (zext LValue to i64),
5427   // Expect both operands of OR and the first operand of SHL have only
5428   // one use.
5429   Value *LValue, *HValue;
5430   if (!match(SI.getValueOperand(),
5431              m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5432                     m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5433                                    m_SpecificInt(HalfValBitSize))))))
5434     return false;
5435 
5436   // Check LValue and HValue are int with size less or equal than 32.
5437   if (!LValue->getType()->isIntegerTy() ||
5438       DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5439       !HValue->getType()->isIntegerTy() ||
5440       DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5441     return false;
5442 
5443   // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5444   // as the input of target query.
5445   auto *LBC = dyn_cast<BitCastInst>(LValue);
5446   auto *HBC = dyn_cast<BitCastInst>(HValue);
5447   EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5448                   : EVT::getEVT(LValue->getType());
5449   EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5450                    : EVT::getEVT(HValue->getType());
5451   if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5452     return false;
5453 
5454   // Start to split store.
5455   IRBuilder<> Builder(SI.getContext());
5456   Builder.SetInsertPoint(&SI);
5457 
5458   // If LValue/HValue is a bitcast in another BB, create a new one in current
5459   // BB so it may be merged with the splitted stores by dag combiner.
5460   if (LBC && LBC->getParent() != SI.getParent())
5461     LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5462   if (HBC && HBC->getParent() != SI.getParent())
5463     HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
5464 
5465   auto CreateSplitStore = [&](Value *V, bool Upper) {
5466     V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
5467     Value *Addr = Builder.CreateBitCast(
5468         SI.getOperand(1),
5469         SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
5470     if (Upper)
5471       Addr = Builder.CreateGEP(
5472           SplitStoreType, Addr,
5473           ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
5474     Builder.CreateAlignedStore(
5475         V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
5476   };
5477 
5478   CreateSplitStore(LValue, false);
5479   CreateSplitStore(HValue, true);
5480 
5481   // Delete the old store.
5482   SI.eraseFromParent();
5483   return true;
5484 }
5485 
5486 bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
5487   // Bail out if we inserted the instruction to prevent optimizations from
5488   // stepping on each other's toes.
5489   if (InsertedInsts.count(I))
5490     return false;
5491 
5492   if (PHINode *P = dyn_cast<PHINode>(I)) {
5493     // It is possible for very late stage optimizations (such as SimplifyCFG)
5494     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
5495     // trivial PHI, go ahead and zap it here.
5496     if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
5497       P->replaceAllUsesWith(V);
5498       P->eraseFromParent();
5499       ++NumPHIsElim;
5500       return true;
5501     }
5502     return false;
5503   }
5504 
5505   if (CastInst *CI = dyn_cast<CastInst>(I)) {
5506     // If the source of the cast is a constant, then this should have
5507     // already been constant folded.  The only reason NOT to constant fold
5508     // it is if something (e.g. LSR) was careful to place the constant
5509     // evaluation in a block other than then one that uses it (e.g. to hoist
5510     // the address of globals out of a loop).  If this is the case, we don't
5511     // want to forward-subst the cast.
5512     if (isa<Constant>(CI->getOperand(0)))
5513       return false;
5514 
5515     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
5516       return true;
5517 
5518     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
5519       /// Sink a zext or sext into its user blocks if the target type doesn't
5520       /// fit in one register
5521       if (TLI &&
5522           TLI->getTypeAction(CI->getContext(),
5523                              TLI->getValueType(*DL, CI->getType())) ==
5524               TargetLowering::TypeExpandInteger) {
5525         return SinkCast(CI);
5526       } else {
5527         bool MadeChange = moveExtToFormExtLoad(I);
5528         return MadeChange | optimizeExtUses(I);
5529       }
5530     }
5531     return false;
5532   }
5533 
5534   if (CmpInst *CI = dyn_cast<CmpInst>(I))
5535     if (!TLI || !TLI->hasMultipleConditionRegisters())
5536       return OptimizeCmpExpression(CI, TLI);
5537 
5538   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5539     LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
5540     if (TLI) {
5541       bool Modified = optimizeLoadExt(LI);
5542       unsigned AS = LI->getPointerAddressSpace();
5543       Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5544       return Modified;
5545     }
5546     return false;
5547   }
5548 
5549   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
5550     if (TLI && splitMergedValStore(*SI, *DL, *TLI))
5551       return true;
5552     SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
5553     if (TLI) {
5554       unsigned AS = SI->getPointerAddressSpace();
5555       return optimizeMemoryInst(I, SI->getOperand(1),
5556                                 SI->getOperand(0)->getType(), AS);
5557     }
5558     return false;
5559   }
5560 
5561   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5562 
5563   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5564                 BinOp->getOpcode() == Instruction::LShr)) {
5565     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5566     if (TLI && CI && TLI->hasExtractBitsInsn())
5567       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
5568 
5569     return false;
5570   }
5571 
5572   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
5573     if (GEPI->hasAllZeroIndices()) {
5574       /// The GEP operand must be a pointer, so must its result -> BitCast
5575       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5576                                         GEPI->getName(), GEPI);
5577       GEPI->replaceAllUsesWith(NC);
5578       GEPI->eraseFromParent();
5579       ++NumGEPsElim;
5580       optimizeInst(NC, ModifiedDT);
5581       return true;
5582     }
5583     return false;
5584   }
5585 
5586   if (CallInst *CI = dyn_cast<CallInst>(I))
5587     return optimizeCallInst(CI, ModifiedDT);
5588 
5589   if (SelectInst *SI = dyn_cast<SelectInst>(I))
5590     return optimizeSelectInst(SI);
5591 
5592   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
5593     return optimizeShuffleVectorInst(SVI);
5594 
5595   if (auto *Switch = dyn_cast<SwitchInst>(I))
5596     return optimizeSwitchInst(Switch);
5597 
5598   if (isa<ExtractElementInst>(I))
5599     return optimizeExtractElementInst(I);
5600 
5601   return false;
5602 }
5603 
5604 /// Given an OR instruction, check to see if this is a bitreverse
5605 /// idiom. If so, insert the new intrinsic and return true.
5606 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5607                            const TargetLowering &TLI) {
5608   if (!I.getType()->isIntegerTy() ||
5609       !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5610                                     TLI.getValueType(DL, I.getType(), true)))
5611     return false;
5612 
5613   SmallVector<Instruction*, 4> Insts;
5614   if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
5615     return false;
5616   Instruction *LastInst = Insts.back();
5617   I.replaceAllUsesWith(LastInst);
5618   RecursivelyDeleteTriviallyDeadInstructions(&I);
5619   return true;
5620 }
5621 
5622 // In this pass we look for GEP and cast instructions that are used
5623 // across basic blocks and rewrite them to improve basic-block-at-a-time
5624 // selection.
5625 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
5626   SunkAddrs.clear();
5627   bool MadeChange = false;
5628 
5629   CurInstIterator = BB.begin();
5630   while (CurInstIterator != BB.end()) {
5631     MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
5632     if (ModifiedDT)
5633       return true;
5634   }
5635 
5636   bool MadeBitReverse = true;
5637   while (TLI && MadeBitReverse) {
5638     MadeBitReverse = false;
5639     for (auto &I : reverse(BB)) {
5640       if (makeBitReverse(I, *DL, *TLI)) {
5641         MadeBitReverse = MadeChange = true;
5642         ModifiedDT = true;
5643         break;
5644       }
5645     }
5646   }
5647   MadeChange |= dupRetToEnableTailCallOpts(&BB);
5648 
5649   return MadeChange;
5650 }
5651 
5652 // llvm.dbg.value is far away from the value then iSel may not be able
5653 // handle it properly. iSel will drop llvm.dbg.value if it can not
5654 // find a node corresponding to the value.
5655 bool CodeGenPrepare::placeDbgValues(Function &F) {
5656   bool MadeChange = false;
5657   for (BasicBlock &BB : F) {
5658     Instruction *PrevNonDbgInst = nullptr;
5659     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
5660       Instruction *Insn = &*BI++;
5661       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
5662       // Leave dbg.values that refer to an alloca alone. These
5663       // instrinsics describe the address of a variable (= the alloca)
5664       // being taken.  They should not be moved next to the alloca
5665       // (and to the beginning of the scope), but rather stay close to
5666       // where said address is used.
5667       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
5668         PrevNonDbgInst = Insn;
5669         continue;
5670       }
5671 
5672       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5673       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
5674         // If VI is a phi in a block with an EHPad terminator, we can't insert
5675         // after it.
5676         if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5677           continue;
5678         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5679         DVI->removeFromParent();
5680         if (isa<PHINode>(VI))
5681           DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5682         else
5683           DVI->insertAfter(VI);
5684         MadeChange = true;
5685         ++NumDbgValueMoved;
5686       }
5687     }
5688   }
5689   return MadeChange;
5690 }
5691 
5692 // If there is a sequence that branches based on comparing a single bit
5693 // against zero that can be combined into a single instruction, and the
5694 // target supports folding these into a single instruction, sink the
5695 // mask and compare into the branch uses. Do this before OptimizeBlock ->
5696 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5697 // searched for.
5698 bool CodeGenPrepare::sinkAndCmp(Function &F) {
5699   if (!EnableAndCmpSinking)
5700     return false;
5701   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5702     return false;
5703   bool MadeChange = false;
5704   for (BasicBlock &BB : F) {
5705     // Does this BB end with the following?
5706     //   %andVal = and %val, #single-bit-set
5707     //   %icmpVal = icmp %andResult, 0
5708     //   br i1 %cmpVal label %dest1, label %dest2"
5709     BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
5710     if (!Brcc || !Brcc->isConditional())
5711       continue;
5712     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
5713     if (!Cmp || Cmp->getParent() != &BB)
5714       continue;
5715     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5716     if (!Zero || !Zero->isZero())
5717       continue;
5718     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
5719     if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
5720       continue;
5721     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5722     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5723       continue;
5724     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
5725 
5726     // Push the "and; icmp" for any users that are conditional branches.
5727     // Since there can only be one branch use per BB, we don't need to keep
5728     // track of which BBs we insert into.
5729     for (Use &TheUse : Cmp->uses()) {
5730       // Find brcc use.
5731       BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
5732       if (!BrccUser || !BrccUser->isConditional())
5733         continue;
5734       BasicBlock *UserBB = BrccUser->getParent();
5735       if (UserBB == &BB) continue;
5736       DEBUG(dbgs() << "found Brcc use\n");
5737 
5738       // Sink the "and; icmp" to use.
5739       MadeChange = true;
5740       BinaryOperator *NewAnd =
5741         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5742                                   BrccUser);
5743       CmpInst *NewCmp =
5744         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5745                         "", BrccUser);
5746       TheUse = NewCmp;
5747       ++NumAndCmpsMoved;
5748       DEBUG(BrccUser->getParent()->dump());
5749     }
5750   }
5751   return MadeChange;
5752 }
5753 
5754 /// \brief Scale down both weights to fit into uint32_t.
5755 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5756   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5757   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5758   NewTrue = NewTrue / Scale;
5759   NewFalse = NewFalse / Scale;
5760 }
5761 
5762 /// \brief Some targets prefer to split a conditional branch like:
5763 /// \code
5764 ///   %0 = icmp ne i32 %a, 0
5765 ///   %1 = icmp ne i32 %b, 0
5766 ///   %or.cond = or i1 %0, %1
5767 ///   br i1 %or.cond, label %TrueBB, label %FalseBB
5768 /// \endcode
5769 /// into multiple branch instructions like:
5770 /// \code
5771 ///   bb1:
5772 ///     %0 = icmp ne i32 %a, 0
5773 ///     br i1 %0, label %TrueBB, label %bb2
5774 ///   bb2:
5775 ///     %1 = icmp ne i32 %b, 0
5776 ///     br i1 %1, label %TrueBB, label %FalseBB
5777 /// \endcode
5778 /// This usually allows instruction selection to do even further optimizations
5779 /// and combine the compare with the branch instruction. Currently this is
5780 /// applied for targets which have "cheap" jump instructions.
5781 ///
5782 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5783 ///
5784 bool CodeGenPrepare::splitBranchCondition(Function &F) {
5785   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
5786     return false;
5787 
5788   bool MadeChange = false;
5789   for (auto &BB : F) {
5790     // Does this BB end with the following?
5791     //   %cond1 = icmp|fcmp|binary instruction ...
5792     //   %cond2 = icmp|fcmp|binary instruction ...
5793     //   %cond.or = or|and i1 %cond1, cond2
5794     //   br i1 %cond.or label %dest1, label %dest2"
5795     BinaryOperator *LogicOp;
5796     BasicBlock *TBB, *FBB;
5797     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5798       continue;
5799 
5800     auto *Br1 = cast<BranchInst>(BB.getTerminator());
5801     if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5802       continue;
5803 
5804     unsigned Opc;
5805     Value *Cond1, *Cond2;
5806     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5807                              m_OneUse(m_Value(Cond2)))))
5808       Opc = Instruction::And;
5809     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5810                                  m_OneUse(m_Value(Cond2)))))
5811       Opc = Instruction::Or;
5812     else
5813       continue;
5814 
5815     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5816         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
5817       continue;
5818 
5819     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5820 
5821     // Create a new BB.
5822     auto TmpBB =
5823         BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5824                            BB.getParent(), BB.getNextNode());
5825 
5826     // Update original basic block by using the first condition directly by the
5827     // branch instruction and removing the no longer needed and/or instruction.
5828     Br1->setCondition(Cond1);
5829     LogicOp->eraseFromParent();
5830 
5831     // Depending on the conditon we have to either replace the true or the false
5832     // successor of the original branch instruction.
5833     if (Opc == Instruction::And)
5834       Br1->setSuccessor(0, TmpBB);
5835     else
5836       Br1->setSuccessor(1, TmpBB);
5837 
5838     // Fill in the new basic block.
5839     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
5840     if (auto *I = dyn_cast<Instruction>(Cond2)) {
5841       I->removeFromParent();
5842       I->insertBefore(Br2);
5843     }
5844 
5845     // Update PHI nodes in both successors. The original BB needs to be
5846     // replaced in one succesor's PHI nodes, because the branch comes now from
5847     // the newly generated BB (NewBB). In the other successor we need to add one
5848     // incoming edge to the PHI nodes, because both branch instructions target
5849     // now the same successor. Depending on the original branch condition
5850     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5851     // we perform the correct update for the PHI nodes.
5852     // This doesn't change the successor order of the just created branch
5853     // instruction (or any other instruction).
5854     if (Opc == Instruction::Or)
5855       std::swap(TBB, FBB);
5856 
5857     // Replace the old BB with the new BB.
5858     for (auto &I : *TBB) {
5859       PHINode *PN = dyn_cast<PHINode>(&I);
5860       if (!PN)
5861         break;
5862       int i;
5863       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5864         PN->setIncomingBlock(i, TmpBB);
5865     }
5866 
5867     // Add another incoming edge form the new BB.
5868     for (auto &I : *FBB) {
5869       PHINode *PN = dyn_cast<PHINode>(&I);
5870       if (!PN)
5871         break;
5872       auto *Val = PN->getIncomingValueForBlock(&BB);
5873       PN->addIncoming(Val, TmpBB);
5874     }
5875 
5876     // Update the branch weights (from SelectionDAGBuilder::
5877     // FindMergedConditions).
5878     if (Opc == Instruction::Or) {
5879       // Codegen X | Y as:
5880       // BB1:
5881       //   jmp_if_X TBB
5882       //   jmp TmpBB
5883       // TmpBB:
5884       //   jmp_if_Y TBB
5885       //   jmp FBB
5886       //
5887 
5888       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5889       // The requirement is that
5890       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5891       //     = TrueProb for orignal BB.
5892       // Assuming the orignal weights are A and B, one choice is to set BB1's
5893       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5894       // assumes that
5895       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5896       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5897       // TmpBB, but the math is more complicated.
5898       uint64_t TrueWeight, FalseWeight;
5899       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
5900         uint64_t NewTrueWeight = TrueWeight;
5901         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5902         scaleWeights(NewTrueWeight, NewFalseWeight);
5903         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5904                          .createBranchWeights(TrueWeight, FalseWeight));
5905 
5906         NewTrueWeight = TrueWeight;
5907         NewFalseWeight = 2 * FalseWeight;
5908         scaleWeights(NewTrueWeight, NewFalseWeight);
5909         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5910                          .createBranchWeights(TrueWeight, FalseWeight));
5911       }
5912     } else {
5913       // Codegen X & Y as:
5914       // BB1:
5915       //   jmp_if_X TmpBB
5916       //   jmp FBB
5917       // TmpBB:
5918       //   jmp_if_Y TBB
5919       //   jmp FBB
5920       //
5921       //  This requires creation of TmpBB after CurBB.
5922 
5923       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5924       // The requirement is that
5925       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5926       //     = FalseProb for orignal BB.
5927       // Assuming the orignal weights are A and B, one choice is to set BB1's
5928       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5929       // assumes that
5930       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5931       uint64_t TrueWeight, FalseWeight;
5932       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
5933         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5934         uint64_t NewFalseWeight = FalseWeight;
5935         scaleWeights(NewTrueWeight, NewFalseWeight);
5936         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5937                          .createBranchWeights(TrueWeight, FalseWeight));
5938 
5939         NewTrueWeight = 2 * TrueWeight;
5940         NewFalseWeight = FalseWeight;
5941         scaleWeights(NewTrueWeight, NewFalseWeight);
5942         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5943                          .createBranchWeights(TrueWeight, FalseWeight));
5944       }
5945     }
5946 
5947     // Note: No point in getting fancy here, since the DT info is never
5948     // available to CodeGenPrepare.
5949     ModifiedDT = true;
5950 
5951     MadeChange = true;
5952 
5953     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5954           TmpBB->dump());
5955   }
5956   return MadeChange;
5957 }
5958