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