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