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