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/TargetLowering.h"
40 #include "llvm/CodeGen/TargetPassConfig.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/CodeGen/ValueTypes.h"
43 #include "llvm/IR/Argument.h"
44 #include "llvm/IR/Attributes.h"
45 #include "llvm/IR/BasicBlock.h"
46 #include "llvm/IR/CallSite.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Dominators.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GetElementPtrTypeIterator.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/GlobalVariable.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/InlineAsm.h"
58 #include "llvm/IR/InstrTypes.h"
59 #include "llvm/IR/Instruction.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/Intrinsics.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/IR/MDBuilder.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Statepoint.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #include "llvm/IR/ValueMap.h"
75 #include "llvm/Pass.h"
76 #include "llvm/Support/BlockFrequency.h"
77 #include "llvm/Support/BranchProbability.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetMachine.h"
86 #include "llvm/Target/TargetOptions.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 NewAddrMode differs in only one dimension then we can handle it by
2804     // inserting a phi/select later on. Even if NewAddMode is the same
2805     // we still need to collect it due to original value is different.
2806     // And later we will need all original values as anchors during
2807     // finding the common Phi node.
2808     if (DifferentField != ExtAddrMode::MultipleFields) {
2809       AddrModes.emplace_back(NewAddrMode);
2810       return true;
2811     }
2812 
2813     // We couldn't combine NewAddrMode with the rest, so return failure.
2814     AddrModes.clear();
2815     return false;
2816   }
2817 
2818   /// \brief Combine the addressing modes we've collected into a single
2819   /// addressing mode.
2820   /// \return True iff we successfully combined them or we only had one so
2821   /// didn't need to combine them anyway.
2822   bool combineAddrModes() {
2823     // If we have no AddrModes then they can't be combined.
2824     if (AddrModes.size() == 0)
2825       return false;
2826 
2827     // A single AddrMode can trivially be combined.
2828     if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
2829       return true;
2830 
2831     // If the AddrModes we collected are all just equal to the value they are
2832     // derived from then combining them wouldn't do anything useful.
2833     if (AllAddrModesTrivial)
2834       return false;
2835 
2836     if (DisableComplexAddrModes)
2837       return false;
2838 
2839     // For now we support only different base registers.
2840     // TODO: enable others.
2841     if (DifferentField != ExtAddrMode::BaseRegField)
2842       return false;
2843 
2844     // Build a map between <original value, basic block where we saw it> to
2845     // value of base register.
2846     FoldAddrToValueMapping Map;
2847     initializeMap(Map);
2848 
2849     Value *CommonValue = findCommon(Map);
2850     if (CommonValue)
2851       AddrModes[0].BaseReg = CommonValue;
2852     return CommonValue != nullptr;
2853   }
2854 
2855 private:
2856   /// \brief Initialize Map with anchor values. For address seen in some BB
2857   /// we set the value of different field saw in this address.
2858   /// If address is not an instruction than basic block is set to null.
2859   /// At the same time we find a common type for different field we will
2860   /// use to create new Phi/Select nodes. Keep it in CommonType field.
2861   void initializeMap(FoldAddrToValueMapping &Map) {
2862     // Keep track of keys where the value is null. We will need to replace it
2863     // with constant null when we know the common type.
2864     SmallVector<ValueInBB, 2> NullValue;
2865     for (auto &AM : AddrModes) {
2866       BasicBlock *BB = nullptr;
2867       if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2868         BB = I->getParent();
2869 
2870       // For now we support only base register as different field.
2871       // TODO: Enable others.
2872       Value *DV = AM.BaseReg;
2873       if (DV) {
2874         if (CommonType)
2875           assert(CommonType == DV->getType() && "Different types detected!");
2876         else
2877           CommonType = DV->getType();
2878         Map[{ AM.OriginalValue, BB }] = DV;
2879       } else {
2880         NullValue.push_back({ AM.OriginalValue, BB });
2881       }
2882     }
2883     assert(CommonType && "At least one non-null value must be!");
2884     for (auto VIBB : NullValue)
2885       Map[VIBB] = Constant::getNullValue(CommonType);
2886   }
2887 
2888   /// \brief We have mapping between value A and basic block where value A
2889   /// seen to other value B where B was a field in addressing mode represented
2890   /// by A. Also we have an original value C representin an address in some
2891   /// basic block. Traversing from C through phi and selects we ended up with
2892   /// A's in a map. This utility function tries to find a value V which is a
2893   /// field in addressing mode C and traversing through phi nodes and selects
2894   /// we will end up in corresponded values B in a map.
2895   /// The utility will create a new Phi/Selects if needed.
2896   // The simple example looks as follows:
2897   // BB1:
2898   //   p1 = b1 + 40
2899   //   br cond BB2, BB3
2900   // BB2:
2901   //   p2 = b2 + 40
2902   //   br BB3
2903   // BB3:
2904   //   p = phi [p1, BB1], [p2, BB2]
2905   //   v = load p
2906   // Map is
2907   //   <p1, BB1> -> b1
2908   //   <p2, BB2> -> b2
2909   // Request is
2910   //   <p, BB3> -> ?
2911   // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2912   Value *findCommon(FoldAddrToValueMapping &Map) {
2913     // Tracks of new created Phi nodes.
2914     SmallPtrSet<PHINode *, 32> NewPhiNodes;
2915     // Tracks of new created Select nodes.
2916     SmallPtrSet<SelectInst *, 32> NewSelectNodes;
2917     // Tracks the simplification of new created phi nodes. The reason we use
2918     // this mapping is because we will add new created Phi nodes in AddrToBase.
2919     // Simplification of Phi nodes is recursive, so some Phi node may
2920     // be simplified after we added it to AddrToBase.
2921     // Using this mapping we can find the current value in AddrToBase.
2922     SimplificationTracker ST(SQ, NewPhiNodes, NewSelectNodes);
2923 
2924     // First step, DFS to create PHI nodes for all intermediate blocks.
2925     // Also fill traverse order for the second step.
2926     SmallVector<ValueInBB, 32> TraverseOrder;
2927     InsertPlaceholders(Map, TraverseOrder, NewPhiNodes, NewSelectNodes);
2928 
2929     // Second Step, fill new nodes by merged values and simplify if possible.
2930     FillPlaceholders(Map, TraverseOrder, ST);
2931 
2932     if (!AddrSinkNewSelects && NewSelectNodes.size() > 0) {
2933       DestroyNodes(NewPhiNodes);
2934       DestroyNodes(NewSelectNodes);
2935       return nullptr;
2936     }
2937 
2938     // Now we'd like to match New Phi nodes to existed ones.
2939     unsigned PhiNotMatchedCount = 0;
2940     if (!MatchPhiSet(NewPhiNodes, ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2941       DestroyNodes(NewPhiNodes);
2942       DestroyNodes(NewSelectNodes);
2943       return nullptr;
2944     }
2945 
2946     auto *Result = ST.Get(Map.find(Original)->second);
2947     if (Result) {
2948       NumMemoryInstsPhiCreated += NewPhiNodes.size() + PhiNotMatchedCount;
2949       NumMemoryInstsSelectCreated += NewSelectNodes.size();
2950     }
2951     return Result;
2952   }
2953 
2954   /// \brief Destroy nodes from a set.
2955   template <typename T> void DestroyNodes(SmallPtrSetImpl<T *> &Instructions) {
2956     // For safe erasing, replace the Phi with dummy value first.
2957     auto Dummy = UndefValue::get(CommonType);
2958     for (auto I : Instructions) {
2959       I->replaceAllUsesWith(Dummy);
2960       I->eraseFromParent();
2961     }
2962   }
2963 
2964   /// \brief Try to match PHI node to Candidate.
2965   /// Matcher tracks the matched Phi nodes.
2966   bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
2967                     DenseSet<PHIPair> &Matcher,
2968                     SmallPtrSetImpl<PHINode *> &PhiNodesToMatch) {
2969     SmallVector<PHIPair, 8> WorkList;
2970     Matcher.insert({ PHI, Candidate });
2971     WorkList.push_back({ PHI, Candidate });
2972     SmallSet<PHIPair, 8> Visited;
2973     while (!WorkList.empty()) {
2974       auto Item = WorkList.pop_back_val();
2975       if (!Visited.insert(Item).second)
2976         continue;
2977       // We iterate over all incoming values to Phi to compare them.
2978       // If values are different and both of them Phi and the first one is a
2979       // Phi we added (subject to match) and both of them is in the same basic
2980       // block then we can match our pair if values match. So we state that
2981       // these values match and add it to work list to verify that.
2982       for (auto B : Item.first->blocks()) {
2983         Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2984         Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2985         if (FirstValue == SecondValue)
2986           continue;
2987 
2988         PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2989         PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2990 
2991         // One of them is not Phi or
2992         // The first one is not Phi node from the set we'd like to match or
2993         // Phi nodes from different basic blocks then
2994         // we will not be able to match.
2995         if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2996             FirstPhi->getParent() != SecondPhi->getParent())
2997           return false;
2998 
2999         // If we already matched them then continue.
3000         if (Matcher.count({ FirstPhi, SecondPhi }))
3001           continue;
3002         // So the values are different and does not match. So we need them to
3003         // match.
3004         Matcher.insert({ FirstPhi, SecondPhi });
3005         // But me must check it.
3006         WorkList.push_back({ FirstPhi, SecondPhi });
3007       }
3008     }
3009     return true;
3010   }
3011 
3012   /// \brief For the given set of PHI nodes try to find their equivalents.
3013   /// Returns false if this matching fails and creation of new Phi is disabled.
3014   bool MatchPhiSet(SmallPtrSetImpl<PHINode *> &PhiNodesToMatch,
3015                    SimplificationTracker &ST, bool AllowNewPhiNodes,
3016                    unsigned &PhiNotMatchedCount) {
3017     DenseSet<PHIPair> Matched;
3018     SmallPtrSet<PHINode *, 8> WillNotMatch;
3019     while (PhiNodesToMatch.size()) {
3020       PHINode *PHI = *PhiNodesToMatch.begin();
3021 
3022       // Add us, if no Phi nodes in the basic block we do not match.
3023       WillNotMatch.clear();
3024       WillNotMatch.insert(PHI);
3025 
3026       // Traverse all Phis until we found equivalent or fail to do that.
3027       bool IsMatched = false;
3028       for (auto &P : PHI->getParent()->phis()) {
3029         if (&P == PHI)
3030           continue;
3031         if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3032           break;
3033         // If it does not match, collect all Phi nodes from matcher.
3034         // if we end up with no match, them all these Phi nodes will not match
3035         // later.
3036         for (auto M : Matched)
3037           WillNotMatch.insert(M.first);
3038         Matched.clear();
3039       }
3040       if (IsMatched) {
3041         // Replace all matched values and erase them.
3042         for (auto MV : Matched) {
3043           MV.first->replaceAllUsesWith(MV.second);
3044           PhiNodesToMatch.erase(MV.first);
3045           ST.Put(MV.first, MV.second);
3046           MV.first->eraseFromParent();
3047         }
3048         Matched.clear();
3049         continue;
3050       }
3051       // If we are not allowed to create new nodes then bail out.
3052       if (!AllowNewPhiNodes)
3053         return false;
3054       // Just remove all seen values in matcher. They will not match anything.
3055       PhiNotMatchedCount += WillNotMatch.size();
3056       for (auto *P : WillNotMatch)
3057         PhiNodesToMatch.erase(P);
3058     }
3059     return true;
3060   }
3061   /// \brief Fill the placeholder with values from predecessors and simplify it.
3062   void FillPlaceholders(FoldAddrToValueMapping &Map,
3063                         SmallVectorImpl<ValueInBB> &TraverseOrder,
3064                         SimplificationTracker &ST) {
3065     while (!TraverseOrder.empty()) {
3066       auto Current = TraverseOrder.pop_back_val();
3067       assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3068       Value *CurrentValue = Current.first;
3069       BasicBlock *CurrentBlock = Current.second;
3070       Value *V = Map[Current];
3071 
3072       if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3073         // CurrentValue also must be Select.
3074         auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3075         auto *TrueValue = CurrentSelect->getTrueValue();
3076         ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3077                                               ? CurrentBlock
3078                                               : nullptr };
3079         assert(Map.find(TrueItem) != Map.end() && "No True Value!");
3080         Select->setTrueValue(Map[TrueItem]);
3081         auto *FalseValue = CurrentSelect->getFalseValue();
3082         ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3083                                                 ? CurrentBlock
3084                                                 : nullptr };
3085         assert(Map.find(FalseItem) != Map.end() && "No False Value!");
3086         Select->setFalseValue(Map[FalseItem]);
3087       } else {
3088         // Must be a Phi node then.
3089         PHINode *PHI = cast<PHINode>(V);
3090         // Fill the Phi node with values from predecessors.
3091         bool IsDefinedInThisBB =
3092             cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3093         auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3094         for (auto B : predecessors(CurrentBlock)) {
3095           Value *PV = IsDefinedInThisBB
3096                           ? CurrentPhi->getIncomingValueForBlock(B)
3097                           : CurrentValue;
3098           ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3099           assert(Map.find(item) != Map.end() && "No predecessor Value!");
3100           PHI->addIncoming(ST.Get(Map[item]), B);
3101         }
3102       }
3103       // Simplify if possible.
3104       Map[Current] = ST.Simplify(V);
3105     }
3106   }
3107 
3108   /// Starting from value recursively iterates over predecessors up to known
3109   /// ending values represented in a map. For each traversed block inserts
3110   /// a placeholder Phi or Select.
3111   /// Reports all new created Phi/Select nodes by adding them to set.
3112   /// Also reports and order in what basic blocks have been traversed.
3113   void InsertPlaceholders(FoldAddrToValueMapping &Map,
3114                           SmallVectorImpl<ValueInBB> &TraverseOrder,
3115                           SmallPtrSetImpl<PHINode *> &NewPhiNodes,
3116                           SmallPtrSetImpl<SelectInst *> &NewSelectNodes) {
3117     SmallVector<ValueInBB, 32> Worklist;
3118     assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3119            "Address must be a Phi or Select node");
3120     auto *Dummy = UndefValue::get(CommonType);
3121     Worklist.push_back(Original);
3122     while (!Worklist.empty()) {
3123       auto Current = Worklist.pop_back_val();
3124       // If value is not an instruction it is something global, constant,
3125       // parameter and we can say that this value is observable in any block.
3126       // Set block to null to denote it.
3127       // Also please take into account that it is how we build anchors.
3128       if (!isa<Instruction>(Current.first))
3129         Current.second = nullptr;
3130       // if it is already visited or it is an ending value then skip it.
3131       if (Map.find(Current) != Map.end())
3132         continue;
3133       TraverseOrder.push_back(Current);
3134 
3135       Value *CurrentValue = Current.first;
3136       BasicBlock *CurrentBlock = Current.second;
3137       // CurrentValue must be a Phi node or select. All others must be covered
3138       // by anchors.
3139       Instruction *CurrentI = cast<Instruction>(CurrentValue);
3140       bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3141 
3142       unsigned PredCount =
3143           std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3144       // if Current Value is not defined in this basic block we are interested
3145       // in values in predecessors.
3146       if (!IsDefinedInThisBB) {
3147         assert(PredCount && "Unreachable block?!");
3148         PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3149                                        &CurrentBlock->front());
3150         Map[Current] = PHI;
3151         NewPhiNodes.insert(PHI);
3152         // Add all predecessors in work list.
3153         for (auto B : predecessors(CurrentBlock))
3154           Worklist.push_back({ CurrentValue, B });
3155         continue;
3156       }
3157       // Value is defined in this basic block.
3158       if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3159         // Is it OK to get metadata from OrigSelect?!
3160         // Create a Select placeholder with dummy value.
3161         SelectInst *Select =
3162             SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3163                                OrigSelect->getName(), OrigSelect, OrigSelect);
3164         Map[Current] = Select;
3165         NewSelectNodes.insert(Select);
3166         // We are interested in True and False value in this basic block.
3167         Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3168         Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3169       } else {
3170         // It must be a Phi node then.
3171         auto *CurrentPhi = cast<PHINode>(CurrentI);
3172         // Create new Phi node for merge of bases.
3173         assert(PredCount && "Unreachable block?!");
3174         PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3175                                        &CurrentBlock->front());
3176         Map[Current] = PHI;
3177         NewPhiNodes.insert(PHI);
3178 
3179         // Add all predecessors in work list.
3180         for (auto B : predecessors(CurrentBlock))
3181           Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3182       }
3183     }
3184   }
3185 };
3186 } // end anonymous namespace
3187 
3188 /// Try adding ScaleReg*Scale to the current addressing mode.
3189 /// Return true and update AddrMode if this addr mode is legal for the target,
3190 /// false if not.
3191 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3192                                              unsigned Depth) {
3193   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3194   // mode.  Just process that directly.
3195   if (Scale == 1)
3196     return matchAddr(ScaleReg, Depth);
3197 
3198   // If the scale is 0, it takes nothing to add this.
3199   if (Scale == 0)
3200     return true;
3201 
3202   // If we already have a scale of this value, we can add to it, otherwise, we
3203   // need an available scale field.
3204   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3205     return false;
3206 
3207   ExtAddrMode TestAddrMode = AddrMode;
3208 
3209   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
3210   // [A+B + A*7] -> [B+A*8].
3211   TestAddrMode.Scale += Scale;
3212   TestAddrMode.ScaledReg = ScaleReg;
3213 
3214   // If the new address isn't legal, bail out.
3215   if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3216     return false;
3217 
3218   // It was legal, so commit it.
3219   AddrMode = TestAddrMode;
3220 
3221   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
3222   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
3223   // X*Scale + C*Scale to addr mode.
3224   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3225   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
3226       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3227     TestAddrMode.ScaledReg = AddLHS;
3228     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
3229 
3230     // If this addressing mode is legal, commit it and remember that we folded
3231     // this instruction.
3232     if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3233       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3234       AddrMode = TestAddrMode;
3235       return true;
3236     }
3237   }
3238 
3239   // Otherwise, not (x+c)*scale, just return what we have.
3240   return true;
3241 }
3242 
3243 /// This is a little filter, which returns true if an addressing computation
3244 /// involving I might be folded into a load/store accessing it.
3245 /// This doesn't need to be perfect, but needs to accept at least
3246 /// the set of instructions that MatchOperationAddr can.
3247 static bool MightBeFoldableInst(Instruction *I) {
3248   switch (I->getOpcode()) {
3249   case Instruction::BitCast:
3250   case Instruction::AddrSpaceCast:
3251     // Don't touch identity bitcasts.
3252     if (I->getType() == I->getOperand(0)->getType())
3253       return false;
3254     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3255   case Instruction::PtrToInt:
3256     // PtrToInt is always a noop, as we know that the int type is pointer sized.
3257     return true;
3258   case Instruction::IntToPtr:
3259     // We know the input is intptr_t, so this is foldable.
3260     return true;
3261   case Instruction::Add:
3262     return true;
3263   case Instruction::Mul:
3264   case Instruction::Shl:
3265     // Can only handle X*C and X << C.
3266     return isa<ConstantInt>(I->getOperand(1));
3267   case Instruction::GetElementPtr:
3268     return true;
3269   default:
3270     return false;
3271   }
3272 }
3273 
3274 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3275 /// \note \p Val is assumed to be the product of some type promotion.
3276 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3277 /// to be legal, as the non-promoted value would have had the same state.
3278 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3279                                        const DataLayout &DL, Value *Val) {
3280   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3281   if (!PromotedInst)
3282     return false;
3283   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3284   // If the ISDOpcode is undefined, it was undefined before the promotion.
3285   if (!ISDOpcode)
3286     return true;
3287   // Otherwise, check if the promoted instruction is legal or not.
3288   return TLI.isOperationLegalOrCustom(
3289       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
3290 }
3291 
3292 namespace {
3293 
3294 /// \brief Hepler class to perform type promotion.
3295 class TypePromotionHelper {
3296   /// \brief Utility function to check whether or not a sign or zero extension
3297   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3298   /// either using the operands of \p Inst or promoting \p Inst.
3299   /// The type of the extension is defined by \p IsSExt.
3300   /// In other words, check if:
3301   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
3302   /// #1 Promotion applies:
3303   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
3304   /// #2 Operand reuses:
3305   /// ext opnd1 to ConsideredExtType.
3306   /// \p PromotedInsts maps the instructions to their type before promotion.
3307   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3308                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
3309 
3310   /// \brief Utility function to determine if \p OpIdx should be promoted when
3311   /// promoting \p Inst.
3312   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
3313     return !(isa<SelectInst>(Inst) && OpIdx == 0);
3314   }
3315 
3316   /// \brief Utility function to promote the operand of \p Ext when this
3317   /// operand is a promotable trunc or sext or zext.
3318   /// \p PromotedInsts maps the instructions to their type before promotion.
3319   /// \p CreatedInstsCost[out] contains the cost of all instructions
3320   /// created to promote the operand of Ext.
3321   /// Newly added extensions are inserted in \p Exts.
3322   /// Newly added truncates are inserted in \p Truncs.
3323   /// Should never be called directly.
3324   /// \return The promoted value which is used instead of Ext.
3325   static Value *promoteOperandForTruncAndAnyExt(
3326       Instruction *Ext, TypePromotionTransaction &TPT,
3327       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3328       SmallVectorImpl<Instruction *> *Exts,
3329       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
3330 
3331   /// \brief Utility function to promote the operand of \p Ext when this
3332   /// operand is promotable and is not a supported trunc or sext.
3333   /// \p PromotedInsts maps the instructions to their type before promotion.
3334   /// \p CreatedInstsCost[out] contains the cost of all the instructions
3335   /// created to promote the operand of Ext.
3336   /// Newly added extensions are inserted in \p Exts.
3337   /// Newly added truncates are inserted in \p Truncs.
3338   /// Should never be called directly.
3339   /// \return The promoted value which is used instead of Ext.
3340   static Value *promoteOperandForOther(Instruction *Ext,
3341                                        TypePromotionTransaction &TPT,
3342                                        InstrToOrigTy &PromotedInsts,
3343                                        unsigned &CreatedInstsCost,
3344                                        SmallVectorImpl<Instruction *> *Exts,
3345                                        SmallVectorImpl<Instruction *> *Truncs,
3346                                        const TargetLowering &TLI, bool IsSExt);
3347 
3348   /// \see promoteOperandForOther.
3349   static Value *signExtendOperandForOther(
3350       Instruction *Ext, TypePromotionTransaction &TPT,
3351       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3352       SmallVectorImpl<Instruction *> *Exts,
3353       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3354     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3355                                   Exts, Truncs, TLI, true);
3356   }
3357 
3358   /// \see promoteOperandForOther.
3359   static Value *zeroExtendOperandForOther(
3360       Instruction *Ext, TypePromotionTransaction &TPT,
3361       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3362       SmallVectorImpl<Instruction *> *Exts,
3363       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3364     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3365                                   Exts, Truncs, TLI, false);
3366   }
3367 
3368 public:
3369   /// Type for the utility function that promotes the operand of Ext.
3370   using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3371                             InstrToOrigTy &PromotedInsts,
3372                             unsigned &CreatedInstsCost,
3373                             SmallVectorImpl<Instruction *> *Exts,
3374                             SmallVectorImpl<Instruction *> *Truncs,
3375                             const TargetLowering &TLI);
3376 
3377   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3378   /// action to promote the operand of \p Ext instead of using Ext.
3379   /// \return NULL if no promotable action is possible with the current
3380   /// sign extension.
3381   /// \p InsertedInsts keeps track of all the instructions inserted by the
3382   /// other CodeGenPrepare optimizations. This information is important
3383   /// because we do not want to promote these instructions as CodeGenPrepare
3384   /// will reinsert them later. Thus creating an infinite loop: create/remove.
3385   /// \p PromotedInsts maps the instructions to their type before promotion.
3386   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
3387                           const TargetLowering &TLI,
3388                           const InstrToOrigTy &PromotedInsts);
3389 };
3390 
3391 } // end anonymous namespace
3392 
3393 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
3394                                         Type *ConsideredExtType,
3395                                         const InstrToOrigTy &PromotedInsts,
3396                                         bool IsSExt) {
3397   // The promotion helper does not know how to deal with vector types yet.
3398   // To be able to fix that, we would need to fix the places where we
3399   // statically extend, e.g., constants and such.
3400   if (Inst->getType()->isVectorTy())
3401     return false;
3402 
3403   // We can always get through zext.
3404   if (isa<ZExtInst>(Inst))
3405     return true;
3406 
3407   // sext(sext) is ok too.
3408   if (IsSExt && isa<SExtInst>(Inst))
3409     return true;
3410 
3411   // We can get through binary operator, if it is legal. In other words, the
3412   // binary operator must have a nuw or nsw flag.
3413   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3414   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3415       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3416        (IsSExt && BinOp->hasNoSignedWrap())))
3417     return true;
3418 
3419   // Check if we can do the following simplification.
3420   // ext(trunc(opnd)) --> ext(opnd)
3421   if (!isa<TruncInst>(Inst))
3422     return false;
3423 
3424   Value *OpndVal = Inst->getOperand(0);
3425   // Check if we can use this operand in the extension.
3426   // If the type is larger than the result type of the extension, we cannot.
3427   if (!OpndVal->getType()->isIntegerTy() ||
3428       OpndVal->getType()->getIntegerBitWidth() >
3429           ConsideredExtType->getIntegerBitWidth())
3430     return false;
3431 
3432   // If the operand of the truncate is not an instruction, we will not have
3433   // any information on the dropped bits.
3434   // (Actually we could for constant but it is not worth the extra logic).
3435   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3436   if (!Opnd)
3437     return false;
3438 
3439   // Check if the source of the type is narrow enough.
3440   // I.e., check that trunc just drops extended bits of the same kind of
3441   // the extension.
3442   // #1 get the type of the operand and check the kind of the extended bits.
3443   const Type *OpndType;
3444   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3445   if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3446     OpndType = It->second.getPointer();
3447   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3448     OpndType = Opnd->getOperand(0)->getType();
3449   else
3450     return false;
3451 
3452   // #2 check that the truncate just drops extended bits.
3453   return Inst->getType()->getIntegerBitWidth() >=
3454          OpndType->getIntegerBitWidth();
3455 }
3456 
3457 TypePromotionHelper::Action TypePromotionHelper::getAction(
3458     Instruction *Ext, const SetOfInstrs &InsertedInsts,
3459     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3460   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3461          "Unexpected instruction type");
3462   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3463   Type *ExtTy = Ext->getType();
3464   bool IsSExt = isa<SExtInst>(Ext);
3465   // If the operand of the extension is not an instruction, we cannot
3466   // get through.
3467   // If it, check we can get through.
3468   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3469     return nullptr;
3470 
3471   // Do not promote if the operand has been added by codegenprepare.
3472   // Otherwise, it means we are undoing an optimization that is likely to be
3473   // redone, thus causing potential infinite loop.
3474   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3475     return nullptr;
3476 
3477   // SExt or Trunc instructions.
3478   // Return the related handler.
3479   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3480       isa<ZExtInst>(ExtOpnd))
3481     return promoteOperandForTruncAndAnyExt;
3482 
3483   // Regular instruction.
3484   // Abort early if we will have to insert non-free instructions.
3485   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
3486     return nullptr;
3487   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3488 }
3489 
3490 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3491     Instruction *SExt, TypePromotionTransaction &TPT,
3492     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3493     SmallVectorImpl<Instruction *> *Exts,
3494     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3495   // By construction, the operand of SExt is an instruction. Otherwise we cannot
3496   // get through it and this method should not be called.
3497   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
3498   Value *ExtVal = SExt;
3499   bool HasMergedNonFreeExt = false;
3500   if (isa<ZExtInst>(SExtOpnd)) {
3501     // Replace s|zext(zext(opnd))
3502     // => zext(opnd).
3503     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
3504     Value *ZExt =
3505         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3506     TPT.replaceAllUsesWith(SExt, ZExt);
3507     TPT.eraseInstruction(SExt);
3508     ExtVal = ZExt;
3509   } else {
3510     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3511     // => z|sext(opnd).
3512     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3513   }
3514   CreatedInstsCost = 0;
3515 
3516   // Remove dead code.
3517   if (SExtOpnd->use_empty())
3518     TPT.eraseInstruction(SExtOpnd);
3519 
3520   // Check if the extension is still needed.
3521   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
3522   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3523     if (ExtInst) {
3524       if (Exts)
3525         Exts->push_back(ExtInst);
3526       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3527     }
3528     return ExtVal;
3529   }
3530 
3531   // At this point we have: ext ty opnd to ty.
3532   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3533   Value *NextVal = ExtInst->getOperand(0);
3534   TPT.eraseInstruction(ExtInst, NextVal);
3535   return NextVal;
3536 }
3537 
3538 Value *TypePromotionHelper::promoteOperandForOther(
3539     Instruction *Ext, TypePromotionTransaction &TPT,
3540     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3541     SmallVectorImpl<Instruction *> *Exts,
3542     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3543     bool IsSExt) {
3544   // By construction, the operand of Ext is an instruction. Otherwise we cannot
3545   // get through it and this method should not be called.
3546   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3547   CreatedInstsCost = 0;
3548   if (!ExtOpnd->hasOneUse()) {
3549     // ExtOpnd will be promoted.
3550     // All its uses, but Ext, will need to use a truncated value of the
3551     // promoted version.
3552     // Create the truncate now.
3553     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
3554     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3555       // Insert it just after the definition.
3556       ITrunc->moveAfter(ExtOpnd);
3557       if (Truncs)
3558         Truncs->push_back(ITrunc);
3559     }
3560 
3561     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
3562     // Restore the operand of Ext (which has been replaced by the previous call
3563     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
3564     TPT.setOperand(Ext, 0, ExtOpnd);
3565   }
3566 
3567   // Get through the Instruction:
3568   // 1. Update its type.
3569   // 2. Replace the uses of Ext by Inst.
3570   // 3. Extend each operand that needs to be extended.
3571 
3572   // Remember the original type of the instruction before promotion.
3573   // This is useful to know that the high bits are sign extended bits.
3574   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3575       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
3576   // Step #1.
3577   TPT.mutateType(ExtOpnd, Ext->getType());
3578   // Step #2.
3579   TPT.replaceAllUsesWith(Ext, ExtOpnd);
3580   // Step #3.
3581   Instruction *ExtForOpnd = Ext;
3582 
3583   DEBUG(dbgs() << "Propagate Ext to operands\n");
3584   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
3585        ++OpIdx) {
3586     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3587     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3588         !shouldExtOperand(ExtOpnd, OpIdx)) {
3589       DEBUG(dbgs() << "No need to propagate\n");
3590       continue;
3591     }
3592     // Check if we can statically extend the operand.
3593     Value *Opnd = ExtOpnd->getOperand(OpIdx);
3594     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
3595       DEBUG(dbgs() << "Statically extend\n");
3596       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3597       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3598                             : Cst->getValue().zext(BitWidth);
3599       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
3600       continue;
3601     }
3602     // UndefValue are typed, so we have to statically sign extend them.
3603     if (isa<UndefValue>(Opnd)) {
3604       DEBUG(dbgs() << "Statically extend\n");
3605       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
3606       continue;
3607     }
3608 
3609     // Otherwise we have to explicity sign extend the operand.
3610     // Check if Ext was reused to extend an operand.
3611     if (!ExtForOpnd) {
3612       // If yes, create a new one.
3613       DEBUG(dbgs() << "More operands to ext\n");
3614       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3615         : TPT.createZExt(Ext, Opnd, Ext->getType());
3616       if (!isa<Instruction>(ValForExtOpnd)) {
3617         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3618         continue;
3619       }
3620       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
3621     }
3622     if (Exts)
3623       Exts->push_back(ExtForOpnd);
3624     TPT.setOperand(ExtForOpnd, 0, Opnd);
3625 
3626     // Move the sign extension before the insertion point.
3627     TPT.moveBefore(ExtForOpnd, ExtOpnd);
3628     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3629     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
3630     // If more sext are required, new instructions will have to be created.
3631     ExtForOpnd = nullptr;
3632   }
3633   if (ExtForOpnd == Ext) {
3634     DEBUG(dbgs() << "Extension is useless now\n");
3635     TPT.eraseInstruction(Ext);
3636   }
3637   return ExtOpnd;
3638 }
3639 
3640 /// Check whether or not promoting an instruction to a wider type is profitable.
3641 /// \p NewCost gives the cost of extension instructions created by the
3642 /// promotion.
3643 /// \p OldCost gives the cost of extension instructions before the promotion
3644 /// plus the number of instructions that have been
3645 /// matched in the addressing mode the promotion.
3646 /// \p PromotedOperand is the value that has been promoted.
3647 /// \return True if the promotion is profitable, false otherwise.
3648 bool AddressingModeMatcher::isPromotionProfitable(
3649     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3650   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3651   // The cost of the new extensions is greater than the cost of the
3652   // old extension plus what we folded.
3653   // This is not profitable.
3654   if (NewCost > OldCost)
3655     return false;
3656   if (NewCost < OldCost)
3657     return true;
3658   // The promotion is neutral but it may help folding the sign extension in
3659   // loads for instance.
3660   // Check that we did not create an illegal instruction.
3661   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
3662 }
3663 
3664 /// Given an instruction or constant expr, see if we can fold the operation
3665 /// into the addressing mode. If so, update the addressing mode and return
3666 /// true, otherwise return false without modifying AddrMode.
3667 /// If \p MovedAway is not NULL, it contains the information of whether or
3668 /// not AddrInst has to be folded into the addressing mode on success.
3669 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3670 /// because it has been moved away.
3671 /// Thus AddrInst must not be added in the matched instructions.
3672 /// This state can happen when AddrInst is a sext, since it may be moved away.
3673 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
3674 /// not be referenced anymore.
3675 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
3676                                                unsigned Depth,
3677                                                bool *MovedAway) {
3678   // Avoid exponential behavior on extremely deep expression trees.
3679   if (Depth >= 5) return false;
3680 
3681   // By default, all matched instructions stay in place.
3682   if (MovedAway)
3683     *MovedAway = false;
3684 
3685   switch (Opcode) {
3686   case Instruction::PtrToInt:
3687     // PtrToInt is always a noop, as we know that the int type is pointer sized.
3688     return matchAddr(AddrInst->getOperand(0), Depth);
3689   case Instruction::IntToPtr: {
3690     auto AS = AddrInst->getType()->getPointerAddressSpace();
3691     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
3692     // This inttoptr is a no-op if the integer type is pointer sized.
3693     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
3694       return matchAddr(AddrInst->getOperand(0), Depth);
3695     return false;
3696   }
3697   case Instruction::BitCast:
3698     // BitCast is always a noop, and we can handle it as long as it is
3699     // int->int or pointer->pointer (we don't want int<->fp or something).
3700     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3701          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3702         // Don't touch identity bitcasts.  These were probably put here by LSR,
3703         // and we don't want to mess around with them.  Assume it knows what it
3704         // is doing.
3705         AddrInst->getOperand(0)->getType() != AddrInst->getType())
3706       return matchAddr(AddrInst->getOperand(0), Depth);
3707     return false;
3708   case Instruction::AddrSpaceCast: {
3709     unsigned SrcAS
3710       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3711     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3712     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3713       return matchAddr(AddrInst->getOperand(0), Depth);
3714     return false;
3715   }
3716   case Instruction::Add: {
3717     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
3718     ExtAddrMode BackupAddrMode = AddrMode;
3719     unsigned OldSize = AddrModeInsts.size();
3720     // Start a transaction at this point.
3721     // The LHS may match but not the RHS.
3722     // Therefore, we need a higher level restoration point to undo partially
3723     // matched operation.
3724     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3725         TPT.getRestorationPoint();
3726 
3727     if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3728         matchAddr(AddrInst->getOperand(0), Depth+1))
3729       return true;
3730 
3731     // Restore the old addr mode info.
3732     AddrMode = BackupAddrMode;
3733     AddrModeInsts.resize(OldSize);
3734     TPT.rollback(LastKnownGood);
3735 
3736     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
3737     if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3738         matchAddr(AddrInst->getOperand(1), Depth+1))
3739       return true;
3740 
3741     // Otherwise we definitely can't merge the ADD in.
3742     AddrMode = BackupAddrMode;
3743     AddrModeInsts.resize(OldSize);
3744     TPT.rollback(LastKnownGood);
3745     break;
3746   }
3747   //case Instruction::Or:
3748   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3749   //break;
3750   case Instruction::Mul:
3751   case Instruction::Shl: {
3752     // Can only handle X*C and X << C.
3753     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
3754     if (!RHS || RHS->getBitWidth() > 64)
3755       return false;
3756     int64_t Scale = RHS->getSExtValue();
3757     if (Opcode == Instruction::Shl)
3758       Scale = 1LL << Scale;
3759 
3760     return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
3761   }
3762   case Instruction::GetElementPtr: {
3763     // Scan the GEP.  We check it if it contains constant offsets and at most
3764     // one variable offset.
3765     int VariableOperand = -1;
3766     unsigned VariableScale = 0;
3767 
3768     int64_t ConstantOffset = 0;
3769     gep_type_iterator GTI = gep_type_begin(AddrInst);
3770     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3771       if (StructType *STy = GTI.getStructTypeOrNull()) {
3772         const StructLayout *SL = DL.getStructLayout(STy);
3773         unsigned Idx =
3774           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3775         ConstantOffset += SL->getElementOffset(Idx);
3776       } else {
3777         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
3778         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3779           ConstantOffset += CI->getSExtValue()*TypeSize;
3780         } else if (TypeSize) {  // Scales of zero don't do anything.
3781           // We only allow one variable index at the moment.
3782           if (VariableOperand != -1)
3783             return false;
3784 
3785           // Remember the variable index.
3786           VariableOperand = i;
3787           VariableScale = TypeSize;
3788         }
3789       }
3790     }
3791 
3792     // A common case is for the GEP to only do a constant offset.  In this case,
3793     // just add it to the disp field and check validity.
3794     if (VariableOperand == -1) {
3795       AddrMode.BaseOffs += ConstantOffset;
3796       if (ConstantOffset == 0 ||
3797           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
3798         // Check to see if we can fold the base pointer in too.
3799         if (matchAddr(AddrInst->getOperand(0), Depth+1))
3800           return true;
3801       }
3802       AddrMode.BaseOffs -= ConstantOffset;
3803       return false;
3804     }
3805 
3806     // Save the valid addressing mode in case we can't match.
3807     ExtAddrMode BackupAddrMode = AddrMode;
3808     unsigned OldSize = AddrModeInsts.size();
3809 
3810     // See if the scale and offset amount is valid for this target.
3811     AddrMode.BaseOffs += ConstantOffset;
3812 
3813     // Match the base operand of the GEP.
3814     if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
3815       // If it couldn't be matched, just stuff the value in a register.
3816       if (AddrMode.HasBaseReg) {
3817         AddrMode = BackupAddrMode;
3818         AddrModeInsts.resize(OldSize);
3819         return false;
3820       }
3821       AddrMode.HasBaseReg = true;
3822       AddrMode.BaseReg = AddrInst->getOperand(0);
3823     }
3824 
3825     // Match the remaining variable portion of the GEP.
3826     if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
3827                           Depth)) {
3828       // If it couldn't be matched, try stuffing the base into a register
3829       // instead of matching it, and retrying the match of the scale.
3830       AddrMode = BackupAddrMode;
3831       AddrModeInsts.resize(OldSize);
3832       if (AddrMode.HasBaseReg)
3833         return false;
3834       AddrMode.HasBaseReg = true;
3835       AddrMode.BaseReg = AddrInst->getOperand(0);
3836       AddrMode.BaseOffs += ConstantOffset;
3837       if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
3838                             VariableScale, Depth)) {
3839         // If even that didn't work, bail.
3840         AddrMode = BackupAddrMode;
3841         AddrModeInsts.resize(OldSize);
3842         return false;
3843       }
3844     }
3845 
3846     return true;
3847   }
3848   case Instruction::SExt:
3849   case Instruction::ZExt: {
3850     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3851     if (!Ext)
3852       return false;
3853 
3854     // Try to move this ext out of the way of the addressing mode.
3855     // Ask for a method for doing so.
3856     TypePromotionHelper::Action TPH =
3857         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
3858     if (!TPH)
3859       return false;
3860 
3861     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3862         TPT.getRestorationPoint();
3863     unsigned CreatedInstsCost = 0;
3864     unsigned ExtCost = !TLI.isExtFree(Ext);
3865     Value *PromotedOperand =
3866         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
3867     // SExt has been moved away.
3868     // Thus either it will be rematched later in the recursive calls or it is
3869     // gone. Anyway, we must not fold it into the addressing mode at this point.
3870     // E.g.,
3871     // op = add opnd, 1
3872     // idx = ext op
3873     // addr = gep base, idx
3874     // is now:
3875     // promotedOpnd = ext opnd            <- no match here
3876     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
3877     // addr = gep base, op                <- match
3878     if (MovedAway)
3879       *MovedAway = true;
3880 
3881     assert(PromotedOperand &&
3882            "TypePromotionHelper should have filtered out those cases");
3883 
3884     ExtAddrMode BackupAddrMode = AddrMode;
3885     unsigned OldSize = AddrModeInsts.size();
3886 
3887     if (!matchAddr(PromotedOperand, Depth) ||
3888         // The total of the new cost is equal to the cost of the created
3889         // instructions.
3890         // The total of the old cost is equal to the cost of the extension plus
3891         // what we have saved in the addressing mode.
3892         !isPromotionProfitable(CreatedInstsCost,
3893                                ExtCost + (AddrModeInsts.size() - OldSize),
3894                                PromotedOperand)) {
3895       AddrMode = BackupAddrMode;
3896       AddrModeInsts.resize(OldSize);
3897       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3898       TPT.rollback(LastKnownGood);
3899       return false;
3900     }
3901     return true;
3902   }
3903   }
3904   return false;
3905 }
3906 
3907 /// If we can, try to add the value of 'Addr' into the current addressing mode.
3908 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3909 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
3910 /// for the target.
3911 ///
3912 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
3913   // Start a transaction at this point that we will rollback if the matching
3914   // fails.
3915   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3916       TPT.getRestorationPoint();
3917   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3918     // Fold in immediates if legal for the target.
3919     AddrMode.BaseOffs += CI->getSExtValue();
3920     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3921       return true;
3922     AddrMode.BaseOffs -= CI->getSExtValue();
3923   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3924     // If this is a global variable, try to fold it into the addressing mode.
3925     if (!AddrMode.BaseGV) {
3926       AddrMode.BaseGV = GV;
3927       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3928         return true;
3929       AddrMode.BaseGV = nullptr;
3930     }
3931   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3932     ExtAddrMode BackupAddrMode = AddrMode;
3933     unsigned OldSize = AddrModeInsts.size();
3934 
3935     // Check to see if it is possible to fold this operation.
3936     bool MovedAway = false;
3937     if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
3938       // This instruction may have been moved away. If so, there is nothing
3939       // to check here.
3940       if (MovedAway)
3941         return true;
3942       // Okay, it's possible to fold this.  Check to see if it is actually
3943       // *profitable* to do so.  We use a simple cost model to avoid increasing
3944       // register pressure too much.
3945       if (I->hasOneUse() ||
3946           isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
3947         AddrModeInsts.push_back(I);
3948         return true;
3949       }
3950 
3951       // It isn't profitable to do this, roll back.
3952       //cerr << "NOT FOLDING: " << *I;
3953       AddrMode = BackupAddrMode;
3954       AddrModeInsts.resize(OldSize);
3955       TPT.rollback(LastKnownGood);
3956     }
3957   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
3958     if (matchOperationAddr(CE, CE->getOpcode(), Depth))
3959       return true;
3960     TPT.rollback(LastKnownGood);
3961   } else if (isa<ConstantPointerNull>(Addr)) {
3962     // Null pointer gets folded without affecting the addressing mode.
3963     return true;
3964   }
3965 
3966   // Worse case, the target should support [reg] addressing modes. :)
3967   if (!AddrMode.HasBaseReg) {
3968     AddrMode.HasBaseReg = true;
3969     AddrMode.BaseReg = Addr;
3970     // Still check for legality in case the target supports [imm] but not [i+r].
3971     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3972       return true;
3973     AddrMode.HasBaseReg = false;
3974     AddrMode.BaseReg = nullptr;
3975   }
3976 
3977   // If the base register is already taken, see if we can do [r+r].
3978   if (AddrMode.Scale == 0) {
3979     AddrMode.Scale = 1;
3980     AddrMode.ScaledReg = Addr;
3981     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3982       return true;
3983     AddrMode.Scale = 0;
3984     AddrMode.ScaledReg = nullptr;
3985   }
3986   // Couldn't match.
3987   TPT.rollback(LastKnownGood);
3988   return false;
3989 }
3990 
3991 /// Check to see if all uses of OpVal by the specified inline asm call are due
3992 /// to memory operands. If so, return true, otherwise return false.
3993 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
3994                                     const TargetLowering &TLI,
3995                                     const TargetRegisterInfo &TRI) {
3996   const Function *F = CI->getFunction();
3997   TargetLowering::AsmOperandInfoVector TargetConstraints =
3998       TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
3999                             ImmutableCallSite(CI));
4000 
4001   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4002     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4003 
4004     // Compute the constraint code and ConstraintType to use.
4005     TLI.ComputeConstraintToUse(OpInfo, SDValue());
4006 
4007     // If this asm operand is our Value*, and if it isn't an indirect memory
4008     // operand, we can't fold it!
4009     if (OpInfo.CallOperandVal == OpVal &&
4010         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4011          !OpInfo.isIndirect))
4012       return false;
4013   }
4014 
4015   return true;
4016 }
4017 
4018 // Max number of memory uses to look at before aborting the search to conserve
4019 // compile time.
4020 static constexpr int MaxMemoryUsesToScan = 20;
4021 
4022 /// Recursively walk all the uses of I until we find a memory use.
4023 /// If we find an obviously non-foldable instruction, return true.
4024 /// Add the ultimately found memory instructions to MemoryUses.
4025 static bool FindAllMemoryUses(
4026     Instruction *I,
4027     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
4028     SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4029     const TargetRegisterInfo &TRI, int SeenInsts = 0) {
4030   // If we already considered this instruction, we're done.
4031   if (!ConsideredInsts.insert(I).second)
4032     return false;
4033 
4034   // If this is an obviously unfoldable instruction, bail out.
4035   if (!MightBeFoldableInst(I))
4036     return true;
4037 
4038   const bool OptSize = I->getFunction()->optForSize();
4039 
4040   // Loop over all the uses, recursively processing them.
4041   for (Use &U : I->uses()) {
4042     // Conservatively return true if we're seeing a large number or a deep chain
4043     // of users. This avoids excessive compilation times in pathological cases.
4044     if (SeenInsts++ >= MaxMemoryUsesToScan)
4045       return true;
4046 
4047     Instruction *UserI = cast<Instruction>(U.getUser());
4048     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4049       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4050       continue;
4051     }
4052 
4053     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4054       unsigned opNo = U.getOperandNo();
4055       if (opNo != StoreInst::getPointerOperandIndex())
4056         return true; // Storing addr, not into addr.
4057       MemoryUses.push_back(std::make_pair(SI, opNo));
4058       continue;
4059     }
4060 
4061     if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4062       unsigned opNo = U.getOperandNo();
4063       if (opNo != AtomicRMWInst::getPointerOperandIndex())
4064         return true; // Storing addr, not into addr.
4065       MemoryUses.push_back(std::make_pair(RMW, opNo));
4066       continue;
4067     }
4068 
4069     if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4070       unsigned opNo = U.getOperandNo();
4071       if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4072         return true; // Storing addr, not into addr.
4073       MemoryUses.push_back(std::make_pair(CmpX, opNo));
4074       continue;
4075     }
4076 
4077     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
4078       // If this is a cold call, we can sink the addressing calculation into
4079       // the cold path.  See optimizeCallInst
4080       if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4081         continue;
4082 
4083       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4084       if (!IA) return true;
4085 
4086       // If this is a memory operand, we're cool, otherwise bail out.
4087       if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
4088         return true;
4089       continue;
4090     }
4091 
4092     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4093                           SeenInsts))
4094       return true;
4095   }
4096 
4097   return false;
4098 }
4099 
4100 /// Return true if Val is already known to be live at the use site that we're
4101 /// folding it into. If so, there is no cost to include it in the addressing
4102 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4103 /// instruction already.
4104 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4105                                                    Value *KnownLive2) {
4106   // If Val is either of the known-live values, we know it is live!
4107   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4108     return true;
4109 
4110   // All values other than instructions and arguments (e.g. constants) are live.
4111   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4112 
4113   // If Val is a constant sized alloca in the entry block, it is live, this is
4114   // true because it is just a reference to the stack/frame pointer, which is
4115   // live for the whole function.
4116   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4117     if (AI->isStaticAlloca())
4118       return true;
4119 
4120   // Check to see if this value is already used in the memory instruction's
4121   // block.  If so, it's already live into the block at the very least, so we
4122   // can reasonably fold it.
4123   return Val->isUsedInBasicBlock(MemoryInst->getParent());
4124 }
4125 
4126 /// It is possible for the addressing mode of the machine to fold the specified
4127 /// instruction into a load or store that ultimately uses it.
4128 /// However, the specified instruction has multiple uses.
4129 /// Given this, it may actually increase register pressure to fold it
4130 /// into the load. For example, consider this code:
4131 ///
4132 ///     X = ...
4133 ///     Y = X+1
4134 ///     use(Y)   -> nonload/store
4135 ///     Z = Y+1
4136 ///     load Z
4137 ///
4138 /// In this case, Y has multiple uses, and can be folded into the load of Z
4139 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
4140 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
4141 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
4142 /// number of computations either.
4143 ///
4144 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
4145 /// X was live across 'load Z' for other reasons, we actually *would* want to
4146 /// fold the addressing mode in the Z case.  This would make Y die earlier.
4147 bool AddressingModeMatcher::
4148 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4149                                      ExtAddrMode &AMAfter) {
4150   if (IgnoreProfitability) return true;
4151 
4152   // AMBefore is the addressing mode before this instruction was folded into it,
4153   // and AMAfter is the addressing mode after the instruction was folded.  Get
4154   // the set of registers referenced by AMAfter and subtract out those
4155   // referenced by AMBefore: this is the set of values which folding in this
4156   // address extends the lifetime of.
4157   //
4158   // Note that there are only two potential values being referenced here,
4159   // BaseReg and ScaleReg (global addresses are always available, as are any
4160   // folded immediates).
4161   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4162 
4163   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4164   // lifetime wasn't extended by adding this instruction.
4165   if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4166     BaseReg = nullptr;
4167   if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4168     ScaledReg = nullptr;
4169 
4170   // If folding this instruction (and it's subexprs) didn't extend any live
4171   // ranges, we're ok with it.
4172   if (!BaseReg && !ScaledReg)
4173     return true;
4174 
4175   // If all uses of this instruction can have the address mode sunk into them,
4176   // we can remove the addressing mode and effectively trade one live register
4177   // for another (at worst.)  In this context, folding an addressing mode into
4178   // the use is just a particularly nice way of sinking it.
4179   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4180   SmallPtrSet<Instruction*, 16> ConsideredInsts;
4181   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
4182     return false;  // Has a non-memory, non-foldable use!
4183 
4184   // Now that we know that all uses of this instruction are part of a chain of
4185   // computation involving only operations that could theoretically be folded
4186   // into a memory use, loop over each of these memory operation uses and see
4187   // if they could  *actually* fold the instruction.  The assumption is that
4188   // addressing modes are cheap and that duplicating the computation involved
4189   // many times is worthwhile, even on a fastpath. For sinking candidates
4190   // (i.e. cold call sites), this serves as a way to prevent excessive code
4191   // growth since most architectures have some reasonable small and fast way to
4192   // compute an effective address.  (i.e LEA on x86)
4193   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4194   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4195     Instruction *User = MemoryUses[i].first;
4196     unsigned OpNo = MemoryUses[i].second;
4197 
4198     // Get the access type of this use.  If the use isn't a pointer, we don't
4199     // know what it accesses.
4200     Value *Address = User->getOperand(OpNo);
4201     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4202     if (!AddrTy)
4203       return false;
4204     Type *AddressAccessTy = AddrTy->getElementType();
4205     unsigned AS = AddrTy->getAddressSpace();
4206 
4207     // Do a match against the root of this address, ignoring profitability. This
4208     // will tell us if the addressing mode for the memory operation will
4209     // *actually* cover the shared instruction.
4210     ExtAddrMode Result;
4211     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4212         TPT.getRestorationPoint();
4213     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4214                                   AddressAccessTy, AS,
4215                                   MemoryInst, Result, InsertedInsts,
4216                                   PromotedInsts, TPT);
4217     Matcher.IgnoreProfitability = true;
4218     bool Success = Matcher.matchAddr(Address, 0);
4219     (void)Success; assert(Success && "Couldn't select *anything*?");
4220 
4221     // The match was to check the profitability, the changes made are not
4222     // part of the original matcher. Therefore, they should be dropped
4223     // otherwise the original matcher will not present the right state.
4224     TPT.rollback(LastKnownGood);
4225 
4226     // If the match didn't cover I, then it won't be shared by it.
4227     if (!is_contained(MatchedAddrModeInsts, I))
4228       return false;
4229 
4230     MatchedAddrModeInsts.clear();
4231   }
4232 
4233   return true;
4234 }
4235 
4236 /// Return true if the specified values are defined in a
4237 /// different basic block than BB.
4238 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4239   if (Instruction *I = dyn_cast<Instruction>(V))
4240     return I->getParent() != BB;
4241   return false;
4242 }
4243 
4244 /// Sink addressing mode computation immediate before MemoryInst if doing so
4245 /// can be done without increasing register pressure.  The need for the
4246 /// register pressure constraint means this can end up being an all or nothing
4247 /// decision for all uses of the same addressing computation.
4248 ///
4249 /// Load and Store Instructions often have addressing modes that can do
4250 /// significant amounts of computation. As such, instruction selection will try
4251 /// to get the load or store to do as much computation as possible for the
4252 /// program. The problem is that isel can only see within a single block. As
4253 /// such, we sink as much legal addressing mode work into the block as possible.
4254 ///
4255 /// This method is used to optimize both load/store and inline asms with memory
4256 /// operands.  It's also used to sink addressing computations feeding into cold
4257 /// call sites into their (cold) basic block.
4258 ///
4259 /// The motivation for handling sinking into cold blocks is that doing so can
4260 /// both enable other address mode sinking (by satisfying the register pressure
4261 /// constraint above), and reduce register pressure globally (by removing the
4262 /// addressing mode computation from the fast path entirely.).
4263 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
4264                                         Type *AccessTy, unsigned AddrSpace) {
4265   Value *Repl = Addr;
4266 
4267   // Try to collapse single-value PHI nodes.  This is necessary to undo
4268   // unprofitable PRE transformations.
4269   SmallVector<Value*, 8> worklist;
4270   SmallPtrSet<Value*, 16> Visited;
4271   worklist.push_back(Addr);
4272 
4273   // Use a worklist to iteratively look through PHI and select nodes, and
4274   // ensure that the addressing mode obtained from the non-PHI/select roots of
4275   // the graph are compatible.
4276   bool PhiOrSelectSeen = false;
4277   SmallVector<Instruction*, 16> AddrModeInsts;
4278   const SimplifyQuery SQ(*DL, TLInfo);
4279   AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
4280   TypePromotionTransaction TPT(RemovedInsts);
4281   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4282       TPT.getRestorationPoint();
4283   while (!worklist.empty()) {
4284     Value *V = worklist.back();
4285     worklist.pop_back();
4286 
4287     // We allow traversing cyclic Phi nodes.
4288     // In case of success after this loop we ensure that traversing through
4289     // Phi nodes ends up with all cases to compute address of the form
4290     //    BaseGV + Base + Scale * Index + Offset
4291     // where Scale and Offset are constans and BaseGV, Base and Index
4292     // are exactly the same Values in all cases.
4293     // It means that BaseGV, Scale and Offset dominate our memory instruction
4294     // and have the same value as they had in address computation represented
4295     // as Phi. So we can safely sink address computation to memory instruction.
4296     if (!Visited.insert(V).second)
4297       continue;
4298 
4299     // For a PHI node, push all of its incoming values.
4300     if (PHINode *P = dyn_cast<PHINode>(V)) {
4301       for (Value *IncValue : P->incoming_values())
4302         worklist.push_back(IncValue);
4303       PhiOrSelectSeen = true;
4304       continue;
4305     }
4306     // Similar for select.
4307     if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4308       worklist.push_back(SI->getFalseValue());
4309       worklist.push_back(SI->getTrueValue());
4310       PhiOrSelectSeen = true;
4311       continue;
4312     }
4313 
4314     // For non-PHIs, determine the addressing mode being computed.  Note that
4315     // the result may differ depending on what other uses our candidate
4316     // addressing instructions might have.
4317     AddrModeInsts.clear();
4318     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4319         V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4320         InsertedInsts, PromotedInsts, TPT);
4321     NewAddrMode.OriginalValue = V;
4322 
4323     if (!AddrModes.addNewAddrMode(NewAddrMode))
4324       break;
4325   }
4326 
4327   // Try to combine the AddrModes we've collected. If we couldn't collect any,
4328   // or we have multiple but either couldn't combine them or combining them
4329   // wouldn't do anything useful, bail out now.
4330   if (!AddrModes.combineAddrModes()) {
4331     TPT.rollback(LastKnownGood);
4332     return false;
4333   }
4334   TPT.commit();
4335 
4336   // Get the combined AddrMode (or the only AddrMode, if we only had one).
4337   ExtAddrMode AddrMode = AddrModes.getAddrMode();
4338 
4339   // If all the instructions matched are already in this BB, don't do anything.
4340   // If we saw a Phi node then it is not local definitely, and if we saw a select
4341   // then we want to push the address calculation past it even if it's already
4342   // in this BB.
4343   if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
4344         return IsNonLocalValue(V, MemoryInst->getParent());
4345                   })) {
4346     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
4347     return false;
4348   }
4349 
4350   // Insert this computation right after this user.  Since our caller is
4351   // scanning from the top of the BB to the bottom, reuse of the expr are
4352   // guaranteed to happen later.
4353   IRBuilder<> Builder(MemoryInst);
4354 
4355   // Now that we determined the addressing expression we want to use and know
4356   // that we have to sink it into this block.  Check to see if we have already
4357   // done this for some other load/store instr in this block.  If so, reuse the
4358   // computation.
4359   Value *&SunkAddr = SunkAddrs[Addr];
4360   if (SunkAddr) {
4361     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
4362                  << *MemoryInst << "\n");
4363     if (SunkAddr->getType() != Addr->getType())
4364       SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4365   } else if (AddrSinkUsingGEPs ||
4366              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
4367               SubtargetInfo->useAA())) {
4368     // By default, we use the GEP-based method when AA is used later. This
4369     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4370     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4371                  << *MemoryInst << "\n");
4372     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4373     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
4374 
4375     // First, find the pointer.
4376     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4377       ResultPtr = AddrMode.BaseReg;
4378       AddrMode.BaseReg = nullptr;
4379     }
4380 
4381     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4382       // We can't add more than one pointer together, nor can we scale a
4383       // pointer (both of which seem meaningless).
4384       if (ResultPtr || AddrMode.Scale != 1)
4385         return false;
4386 
4387       ResultPtr = AddrMode.ScaledReg;
4388       AddrMode.Scale = 0;
4389     }
4390 
4391     // It is only safe to sign extend the BaseReg if we know that the math
4392     // required to create it did not overflow before we extend it. Since
4393     // the original IR value was tossed in favor of a constant back when
4394     // the AddrMode was created we need to bail out gracefully if widths
4395     // do not match instead of extending it.
4396     //
4397     // (See below for code to add the scale.)
4398     if (AddrMode.Scale) {
4399       Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4400       if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4401           cast<IntegerType>(ScaledRegTy)->getBitWidth())
4402         return false;
4403     }
4404 
4405     if (AddrMode.BaseGV) {
4406       if (ResultPtr)
4407         return false;
4408 
4409       ResultPtr = AddrMode.BaseGV;
4410     }
4411 
4412     // If the real base value actually came from an inttoptr, then the matcher
4413     // will look through it and provide only the integer value. In that case,
4414     // use it here.
4415     if (!DL->isNonIntegralPointerType(Addr->getType())) {
4416       if (!ResultPtr && AddrMode.BaseReg) {
4417         ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4418                                            "sunkaddr");
4419         AddrMode.BaseReg = nullptr;
4420       } else if (!ResultPtr && AddrMode.Scale == 1) {
4421         ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4422                                            "sunkaddr");
4423         AddrMode.Scale = 0;
4424       }
4425     }
4426 
4427     if (!ResultPtr &&
4428         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4429       SunkAddr = Constant::getNullValue(Addr->getType());
4430     } else if (!ResultPtr) {
4431       return false;
4432     } else {
4433       Type *I8PtrTy =
4434           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4435       Type *I8Ty = Builder.getInt8Ty();
4436 
4437       // Start with the base register. Do this first so that subsequent address
4438       // matching finds it last, which will prevent it from trying to match it
4439       // as the scaled value in case it happens to be a mul. That would be
4440       // problematic if we've sunk a different mul for the scale, because then
4441       // we'd end up sinking both muls.
4442       if (AddrMode.BaseReg) {
4443         Value *V = AddrMode.BaseReg;
4444         if (V->getType() != IntPtrTy)
4445           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4446 
4447         ResultIndex = V;
4448       }
4449 
4450       // Add the scale value.
4451       if (AddrMode.Scale) {
4452         Value *V = AddrMode.ScaledReg;
4453         if (V->getType() == IntPtrTy) {
4454           // done.
4455         } else {
4456           assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4457                  cast<IntegerType>(V->getType())->getBitWidth() &&
4458                  "We can't transform if ScaledReg is too narrow");
4459           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4460         }
4461 
4462         if (AddrMode.Scale != 1)
4463           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4464                                 "sunkaddr");
4465         if (ResultIndex)
4466           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4467         else
4468           ResultIndex = V;
4469       }
4470 
4471       // Add in the Base Offset if present.
4472       if (AddrMode.BaseOffs) {
4473         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4474         if (ResultIndex) {
4475           // We need to add this separately from the scale above to help with
4476           // SDAG consecutive load/store merging.
4477           if (ResultPtr->getType() != I8PtrTy)
4478             ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4479           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4480         }
4481 
4482         ResultIndex = V;
4483       }
4484 
4485       if (!ResultIndex) {
4486         SunkAddr = ResultPtr;
4487       } else {
4488         if (ResultPtr->getType() != I8PtrTy)
4489           ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4490         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4491       }
4492 
4493       if (SunkAddr->getType() != Addr->getType())
4494         SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4495     }
4496   } else {
4497     // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4498     // non-integral pointers, so in that case bail out now.
4499     Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4500     Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4501     PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4502     PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4503     if (DL->isNonIntegralPointerType(Addr->getType()) ||
4504         (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4505         (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4506         (AddrMode.BaseGV &&
4507          DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4508       return false;
4509 
4510     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4511                  << *MemoryInst << "\n");
4512     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4513     Value *Result = nullptr;
4514 
4515     // Start with the base register. Do this first so that subsequent address
4516     // matching finds it last, which will prevent it from trying to match it
4517     // as the scaled value in case it happens to be a mul. That would be
4518     // problematic if we've sunk a different mul for the scale, because then
4519     // we'd end up sinking both muls.
4520     if (AddrMode.BaseReg) {
4521       Value *V = AddrMode.BaseReg;
4522       if (V->getType()->isPointerTy())
4523         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4524       if (V->getType() != IntPtrTy)
4525         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4526       Result = V;
4527     }
4528 
4529     // Add the scale value.
4530     if (AddrMode.Scale) {
4531       Value *V = AddrMode.ScaledReg;
4532       if (V->getType() == IntPtrTy) {
4533         // done.
4534       } else if (V->getType()->isPointerTy()) {
4535         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4536       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4537                  cast<IntegerType>(V->getType())->getBitWidth()) {
4538         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4539       } else {
4540         // It is only safe to sign extend the BaseReg if we know that the math
4541         // required to create it did not overflow before we extend it. Since
4542         // the original IR value was tossed in favor of a constant back when
4543         // the AddrMode was created we need to bail out gracefully if widths
4544         // do not match instead of extending it.
4545         Instruction *I = dyn_cast_or_null<Instruction>(Result);
4546         if (I && (Result != AddrMode.BaseReg))
4547           I->eraseFromParent();
4548         return false;
4549       }
4550       if (AddrMode.Scale != 1)
4551         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4552                               "sunkaddr");
4553       if (Result)
4554         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4555       else
4556         Result = V;
4557     }
4558 
4559     // Add in the BaseGV if present.
4560     if (AddrMode.BaseGV) {
4561       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
4562       if (Result)
4563         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4564       else
4565         Result = V;
4566     }
4567 
4568     // Add in the Base Offset if present.
4569     if (AddrMode.BaseOffs) {
4570       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4571       if (Result)
4572         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4573       else
4574         Result = V;
4575     }
4576 
4577     if (!Result)
4578       SunkAddr = Constant::getNullValue(Addr->getType());
4579     else
4580       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
4581   }
4582 
4583   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
4584 
4585   // If we have no uses, recursively delete the value and all dead instructions
4586   // using it.
4587   if (Repl->use_empty()) {
4588     // This can cause recursive deletion, which can invalidate our iterator.
4589     // Use a WeakTrackingVH to hold onto it in case this happens.
4590     Value *CurValue = &*CurInstIterator;
4591     WeakTrackingVH IterHandle(CurValue);
4592     BasicBlock *BB = CurInstIterator->getParent();
4593 
4594     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
4595 
4596     if (IterHandle != CurValue) {
4597       // If the iterator instruction was recursively deleted, start over at the
4598       // start of the block.
4599       CurInstIterator = BB->begin();
4600       SunkAddrs.clear();
4601     }
4602   }
4603   ++NumMemoryInsts;
4604   return true;
4605 }
4606 
4607 /// If there are any memory operands, use OptimizeMemoryInst to sink their
4608 /// address computing into the block when possible / profitable.
4609 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
4610   bool MadeChange = false;
4611 
4612   const TargetRegisterInfo *TRI =
4613       TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
4614   TargetLowering::AsmOperandInfoVector TargetConstraints =
4615       TLI->ParseConstraints(*DL, TRI, CS);
4616   unsigned ArgNo = 0;
4617   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4618     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4619 
4620     // Compute the constraint code and ConstraintType to use.
4621     TLI->ComputeConstraintToUse(OpInfo, SDValue());
4622 
4623     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4624         OpInfo.isIndirect) {
4625       Value *OpVal = CS->getArgOperand(ArgNo++);
4626       MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
4627     } else if (OpInfo.Type == InlineAsm::isInput)
4628       ArgNo++;
4629   }
4630 
4631   return MadeChange;
4632 }
4633 
4634 /// \brief Check if all the uses of \p Val are equivalent (or free) zero or
4635 /// sign extensions.
4636 static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4637   assert(!Val->use_empty() && "Input must have at least one use");
4638   const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
4639   bool IsSExt = isa<SExtInst>(FirstUser);
4640   Type *ExtTy = FirstUser->getType();
4641   for (const User *U : Val->users()) {
4642     const Instruction *UI = cast<Instruction>(U);
4643     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4644       return false;
4645     Type *CurTy = UI->getType();
4646     // Same input and output types: Same instruction after CSE.
4647     if (CurTy == ExtTy)
4648       continue;
4649 
4650     // If IsSExt is true, we are in this situation:
4651     // a = Val
4652     // b = sext ty1 a to ty2
4653     // c = sext ty1 a to ty3
4654     // Assuming ty2 is shorter than ty3, this could be turned into:
4655     // a = Val
4656     // b = sext ty1 a to ty2
4657     // c = sext ty2 b to ty3
4658     // However, the last sext is not free.
4659     if (IsSExt)
4660       return false;
4661 
4662     // This is a ZExt, maybe this is free to extend from one type to another.
4663     // In that case, we would not account for a different use.
4664     Type *NarrowTy;
4665     Type *LargeTy;
4666     if (ExtTy->getScalarType()->getIntegerBitWidth() >
4667         CurTy->getScalarType()->getIntegerBitWidth()) {
4668       NarrowTy = CurTy;
4669       LargeTy = ExtTy;
4670     } else {
4671       NarrowTy = ExtTy;
4672       LargeTy = CurTy;
4673     }
4674 
4675     if (!TLI.isZExtFree(NarrowTy, LargeTy))
4676       return false;
4677   }
4678   // All uses are the same or can be derived from one another for free.
4679   return true;
4680 }
4681 
4682 /// \brief Try to speculatively promote extensions in \p Exts and continue
4683 /// promoting through newly promoted operands recursively as far as doing so is
4684 /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4685 /// When some promotion happened, \p TPT contains the proper state to revert
4686 /// them.
4687 ///
4688 /// \return true if some promotion happened, false otherwise.
4689 bool CodeGenPrepare::tryToPromoteExts(
4690     TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4691     SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4692     unsigned CreatedInstsCost) {
4693   bool Promoted = false;
4694 
4695   // Iterate over all the extensions to try to promote them.
4696   for (auto I : Exts) {
4697     // Early check if we directly have ext(load).
4698     if (isa<LoadInst>(I->getOperand(0))) {
4699       ProfitablyMovedExts.push_back(I);
4700       continue;
4701     }
4702 
4703     // Check whether or not we want to do any promotion.  The reason we have
4704     // this check inside the for loop is to catch the case where an extension
4705     // is directly fed by a load because in such case the extension can be moved
4706     // up without any promotion on its operands.
4707     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4708       return false;
4709 
4710     // Get the action to perform the promotion.
4711     TypePromotionHelper::Action TPH =
4712         TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
4713     // Check if we can promote.
4714     if (!TPH) {
4715       // Save the current extension as we cannot move up through its operand.
4716       ProfitablyMovedExts.push_back(I);
4717       continue;
4718     }
4719 
4720     // Save the current state.
4721     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4722         TPT.getRestorationPoint();
4723     SmallVector<Instruction *, 4> NewExts;
4724     unsigned NewCreatedInstsCost = 0;
4725     unsigned ExtCost = !TLI->isExtFree(I);
4726     // Promote.
4727     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4728                              &NewExts, nullptr, *TLI);
4729     assert(PromotedVal &&
4730            "TypePromotionHelper should have filtered out those cases");
4731 
4732     // We would be able to merge only one extension in a load.
4733     // Therefore, if we have more than 1 new extension we heuristically
4734     // cut this search path, because it means we degrade the code quality.
4735     // With exactly 2, the transformation is neutral, because we will merge
4736     // one extension but leave one. However, we optimistically keep going,
4737     // because the new extension may be removed too.
4738     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4739     // FIXME: It would be possible to propagate a negative value instead of
4740     // conservatively ceiling it to 0.
4741     TotalCreatedInstsCost =
4742         std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
4743     if (!StressExtLdPromotion &&
4744         (TotalCreatedInstsCost > 1 ||
4745          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
4746       // This promotion is not profitable, rollback to the previous state, and
4747       // save the current extension in ProfitablyMovedExts as the latest
4748       // speculative promotion turned out to be unprofitable.
4749       TPT.rollback(LastKnownGood);
4750       ProfitablyMovedExts.push_back(I);
4751       continue;
4752     }
4753     // Continue promoting NewExts as far as doing so is profitable.
4754     SmallVector<Instruction *, 2> NewlyMovedExts;
4755     (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4756     bool NewPromoted = false;
4757     for (auto ExtInst : NewlyMovedExts) {
4758       Instruction *MovedExt = cast<Instruction>(ExtInst);
4759       Value *ExtOperand = MovedExt->getOperand(0);
4760       // If we have reached to a load, we need this extra profitability check
4761       // as it could potentially be merged into an ext(load).
4762       if (isa<LoadInst>(ExtOperand) &&
4763           !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4764             (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4765         continue;
4766 
4767       ProfitablyMovedExts.push_back(MovedExt);
4768       NewPromoted = true;
4769     }
4770 
4771     // If none of speculative promotions for NewExts is profitable, rollback
4772     // and save the current extension (I) as the last profitable extension.
4773     if (!NewPromoted) {
4774       TPT.rollback(LastKnownGood);
4775       ProfitablyMovedExts.push_back(I);
4776       continue;
4777     }
4778     // The promotion is profitable.
4779     Promoted = true;
4780   }
4781   return Promoted;
4782 }
4783 
4784 /// Merging redundant sexts when one is dominating the other.
4785 bool CodeGenPrepare::mergeSExts(Function &F) {
4786   DominatorTree DT(F);
4787   bool Changed = false;
4788   for (auto &Entry : ValToSExtendedUses) {
4789     SExts &Insts = Entry.second;
4790     SExts CurPts;
4791     for (Instruction *Inst : Insts) {
4792       if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4793           Inst->getOperand(0) != Entry.first)
4794         continue;
4795       bool inserted = false;
4796       for (auto &Pt : CurPts) {
4797         if (DT.dominates(Inst, Pt)) {
4798           Pt->replaceAllUsesWith(Inst);
4799           RemovedInsts.insert(Pt);
4800           Pt->removeFromParent();
4801           Pt = Inst;
4802           inserted = true;
4803           Changed = true;
4804           break;
4805         }
4806         if (!DT.dominates(Pt, Inst))
4807           // Give up if we need to merge in a common dominator as the
4808           // expermients show it is not profitable.
4809           continue;
4810         Inst->replaceAllUsesWith(Pt);
4811         RemovedInsts.insert(Inst);
4812         Inst->removeFromParent();
4813         inserted = true;
4814         Changed = true;
4815         break;
4816       }
4817       if (!inserted)
4818         CurPts.push_back(Inst);
4819     }
4820   }
4821   return Changed;
4822 }
4823 
4824 /// Return true, if an ext(load) can be formed from an extension in
4825 /// \p MovedExts.
4826 bool CodeGenPrepare::canFormExtLd(
4827     const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4828     Instruction *&Inst, bool HasPromoted) {
4829   for (auto *MovedExtInst : MovedExts) {
4830     if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4831       LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4832       Inst = MovedExtInst;
4833       break;
4834     }
4835   }
4836   if (!LI)
4837     return false;
4838 
4839   // If they're already in the same block, there's nothing to do.
4840   // Make the cheap checks first if we did not promote.
4841   // If we promoted, we need to check if it is indeed profitable.
4842   if (!HasPromoted && LI->getParent() == Inst->getParent())
4843     return false;
4844 
4845   return TLI->isExtLoad(LI, Inst, *DL);
4846 }
4847 
4848 /// Move a zext or sext fed by a load into the same basic block as the load,
4849 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
4850 /// extend into the load.
4851 ///
4852 /// E.g.,
4853 /// \code
4854 /// %ld = load i32* %addr
4855 /// %add = add nuw i32 %ld, 4
4856 /// %zext = zext i32 %add to i64
4857 // \endcode
4858 /// =>
4859 /// \code
4860 /// %ld = load i32* %addr
4861 /// %zext = zext i32 %ld to i64
4862 /// %add = add nuw i64 %zext, 4
4863 /// \encode
4864 /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4865 /// allow us to match zext(load i32*) to i64.
4866 ///
4867 /// Also, try to promote the computations used to obtain a sign extended
4868 /// value used into memory accesses.
4869 /// E.g.,
4870 /// \code
4871 /// a = add nsw i32 b, 3
4872 /// d = sext i32 a to i64
4873 /// e = getelementptr ..., i64 d
4874 /// \endcode
4875 /// =>
4876 /// \code
4877 /// f = sext i32 b to i64
4878 /// a = add nsw i64 f, 3
4879 /// e = getelementptr ..., i64 a
4880 /// \endcode
4881 ///
4882 /// \p Inst[in/out] the extension may be modified during the process if some
4883 /// promotions apply.
4884 bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4885   // ExtLoad formation and address type promotion infrastructure requires TLI to
4886   // be effective.
4887   if (!TLI)
4888     return false;
4889 
4890   bool AllowPromotionWithoutCommonHeader = false;
4891   /// See if it is an interesting sext operations for the address type
4892   /// promotion before trying to promote it, e.g., the ones with the right
4893   /// type and used in memory accesses.
4894   bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4895       *Inst, AllowPromotionWithoutCommonHeader);
4896   TypePromotionTransaction TPT(RemovedInsts);
4897   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4898       TPT.getRestorationPoint();
4899   SmallVector<Instruction *, 1> Exts;
4900   SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4901   Exts.push_back(Inst);
4902 
4903   bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
4904 
4905   // Look for a load being extended.
4906   LoadInst *LI = nullptr;
4907   Instruction *ExtFedByLoad;
4908 
4909   // Try to promote a chain of computation if it allows to form an extended
4910   // load.
4911   if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4912     assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4913     TPT.commit();
4914     // Move the extend into the same block as the load
4915     ExtFedByLoad->moveAfter(LI);
4916     // CGP does not check if the zext would be speculatively executed when moved
4917     // to the same basic block as the load. Preserving its original location
4918     // would pessimize the debugging experience, as well as negatively impact
4919     // the quality of sample pgo. We don't want to use "line 0" as that has a
4920     // size cost in the line-table section and logically the zext can be seen as
4921     // part of the load. Therefore we conservatively reuse the same debug
4922     // location for the load and the zext.
4923     ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
4924     ++NumExtsMoved;
4925     Inst = ExtFedByLoad;
4926     return true;
4927   }
4928 
4929   // Continue promoting SExts if known as considerable depending on targets.
4930   if (ATPConsiderable &&
4931       performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4932                                   HasPromoted, TPT, SpeculativelyMovedExts))
4933     return true;
4934 
4935   TPT.rollback(LastKnownGood);
4936   return false;
4937 }
4938 
4939 // Perform address type promotion if doing so is profitable.
4940 // If AllowPromotionWithoutCommonHeader == false, we should find other sext
4941 // instructions that sign extended the same initial value. However, if
4942 // AllowPromotionWithoutCommonHeader == true, we expect promoting the
4943 // extension is just profitable.
4944 bool CodeGenPrepare::performAddressTypePromotion(
4945     Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
4946     bool HasPromoted, TypePromotionTransaction &TPT,
4947     SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
4948   bool Promoted = false;
4949   SmallPtrSet<Instruction *, 1> UnhandledExts;
4950   bool AllSeenFirst = true;
4951   for (auto I : SpeculativelyMovedExts) {
4952     Value *HeadOfChain = I->getOperand(0);
4953     DenseMap<Value *, Instruction *>::iterator AlreadySeen =
4954         SeenChainsForSExt.find(HeadOfChain);
4955     // If there is an unhandled SExt which has the same header, try to promote
4956     // it as well.
4957     if (AlreadySeen != SeenChainsForSExt.end()) {
4958       if (AlreadySeen->second != nullptr)
4959         UnhandledExts.insert(AlreadySeen->second);
4960       AllSeenFirst = false;
4961     }
4962   }
4963 
4964   if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4965                         SpeculativelyMovedExts.size() == 1)) {
4966     TPT.commit();
4967     if (HasPromoted)
4968       Promoted = true;
4969     for (auto I : SpeculativelyMovedExts) {
4970       Value *HeadOfChain = I->getOperand(0);
4971       SeenChainsForSExt[HeadOfChain] = nullptr;
4972       ValToSExtendedUses[HeadOfChain].push_back(I);
4973     }
4974     // Update Inst as promotion happen.
4975     Inst = SpeculativelyMovedExts.pop_back_val();
4976   } else {
4977     // This is the first chain visited from the header, keep the current chain
4978     // as unhandled. Defer to promote this until we encounter another SExt
4979     // chain derived from the same header.
4980     for (auto I : SpeculativelyMovedExts) {
4981       Value *HeadOfChain = I->getOperand(0);
4982       SeenChainsForSExt[HeadOfChain] = Inst;
4983     }
4984     return false;
4985   }
4986 
4987   if (!AllSeenFirst && !UnhandledExts.empty())
4988     for (auto VisitedSExt : UnhandledExts) {
4989       if (RemovedInsts.count(VisitedSExt))
4990         continue;
4991       TypePromotionTransaction TPT(RemovedInsts);
4992       SmallVector<Instruction *, 1> Exts;
4993       SmallVector<Instruction *, 2> Chains;
4994       Exts.push_back(VisitedSExt);
4995       bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4996       TPT.commit();
4997       if (HasPromoted)
4998         Promoted = true;
4999       for (auto I : Chains) {
5000         Value *HeadOfChain = I->getOperand(0);
5001         // Mark this as handled.
5002         SeenChainsForSExt[HeadOfChain] = nullptr;
5003         ValToSExtendedUses[HeadOfChain].push_back(I);
5004       }
5005     }
5006   return Promoted;
5007 }
5008 
5009 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
5010   BasicBlock *DefBB = I->getParent();
5011 
5012   // If the result of a {s|z}ext and its source are both live out, rewrite all
5013   // other uses of the source with result of extension.
5014   Value *Src = I->getOperand(0);
5015   if (Src->hasOneUse())
5016     return false;
5017 
5018   // Only do this xform if truncating is free.
5019   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
5020     return false;
5021 
5022   // Only safe to perform the optimization if the source is also defined in
5023   // this block.
5024   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
5025     return false;
5026 
5027   bool DefIsLiveOut = false;
5028   for (User *U : I->users()) {
5029     Instruction *UI = cast<Instruction>(U);
5030 
5031     // Figure out which BB this ext is used in.
5032     BasicBlock *UserBB = UI->getParent();
5033     if (UserBB == DefBB) continue;
5034     DefIsLiveOut = true;
5035     break;
5036   }
5037   if (!DefIsLiveOut)
5038     return false;
5039 
5040   // Make sure none of the uses are PHI nodes.
5041   for (User *U : Src->users()) {
5042     Instruction *UI = cast<Instruction>(U);
5043     BasicBlock *UserBB = UI->getParent();
5044     if (UserBB == DefBB) continue;
5045     // Be conservative. We don't want this xform to end up introducing
5046     // reloads just before load / store instructions.
5047     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5048       return false;
5049   }
5050 
5051   // InsertedTruncs - Only insert one trunc in each block once.
5052   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5053 
5054   bool MadeChange = false;
5055   for (Use &U : Src->uses()) {
5056     Instruction *User = cast<Instruction>(U.getUser());
5057 
5058     // Figure out which BB this ext is used in.
5059     BasicBlock *UserBB = User->getParent();
5060     if (UserBB == DefBB) continue;
5061 
5062     // Both src and def are live in this block. Rewrite the use.
5063     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5064 
5065     if (!InsertedTrunc) {
5066       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5067       assert(InsertPt != UserBB->end());
5068       InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
5069       InsertedInsts.insert(InsertedTrunc);
5070     }
5071 
5072     // Replace a use of the {s|z}ext source with a use of the result.
5073     U = InsertedTrunc;
5074     ++NumExtUses;
5075     MadeChange = true;
5076   }
5077 
5078   return MadeChange;
5079 }
5080 
5081 // Find loads whose uses only use some of the loaded value's bits.  Add an "and"
5082 // just after the load if the target can fold this into one extload instruction,
5083 // with the hope of eliminating some of the other later "and" instructions using
5084 // the loaded value.  "and"s that are made trivially redundant by the insertion
5085 // of the new "and" are removed by this function, while others (e.g. those whose
5086 // path from the load goes through a phi) are left for isel to potentially
5087 // remove.
5088 //
5089 // For example:
5090 //
5091 // b0:
5092 //   x = load i32
5093 //   ...
5094 // b1:
5095 //   y = and x, 0xff
5096 //   z = use y
5097 //
5098 // becomes:
5099 //
5100 // b0:
5101 //   x = load i32
5102 //   x' = and x, 0xff
5103 //   ...
5104 // b1:
5105 //   z = use x'
5106 //
5107 // whereas:
5108 //
5109 // b0:
5110 //   x1 = load i32
5111 //   ...
5112 // b1:
5113 //   x2 = load i32
5114 //   ...
5115 // b2:
5116 //   x = phi x1, x2
5117 //   y = and x, 0xff
5118 //
5119 // becomes (after a call to optimizeLoadExt for each load):
5120 //
5121 // b0:
5122 //   x1 = load i32
5123 //   x1' = and x1, 0xff
5124 //   ...
5125 // b1:
5126 //   x2 = load i32
5127 //   x2' = and x2, 0xff
5128 //   ...
5129 // b2:
5130 //   x = phi x1', x2'
5131 //   y = and x, 0xff
5132 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5133   if (!Load->isSimple() ||
5134       !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5135     return false;
5136 
5137   // Skip loads we've already transformed.
5138   if (Load->hasOneUse() &&
5139       InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5140     return false;
5141 
5142   // Look at all uses of Load, looking through phis, to determine how many bits
5143   // of the loaded value are needed.
5144   SmallVector<Instruction *, 8> WorkList;
5145   SmallPtrSet<Instruction *, 16> Visited;
5146   SmallVector<Instruction *, 8> AndsToMaybeRemove;
5147   for (auto *U : Load->users())
5148     WorkList.push_back(cast<Instruction>(U));
5149 
5150   EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5151   unsigned BitWidth = LoadResultVT.getSizeInBits();
5152   APInt DemandBits(BitWidth, 0);
5153   APInt WidestAndBits(BitWidth, 0);
5154 
5155   while (!WorkList.empty()) {
5156     Instruction *I = WorkList.back();
5157     WorkList.pop_back();
5158 
5159     // Break use-def graph loops.
5160     if (!Visited.insert(I).second)
5161       continue;
5162 
5163     // For a PHI node, push all of its users.
5164     if (auto *Phi = dyn_cast<PHINode>(I)) {
5165       for (auto *U : Phi->users())
5166         WorkList.push_back(cast<Instruction>(U));
5167       continue;
5168     }
5169 
5170     switch (I->getOpcode()) {
5171     case Instruction::And: {
5172       auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5173       if (!AndC)
5174         return false;
5175       APInt AndBits = AndC->getValue();
5176       DemandBits |= AndBits;
5177       // Keep track of the widest and mask we see.
5178       if (AndBits.ugt(WidestAndBits))
5179         WidestAndBits = AndBits;
5180       if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5181         AndsToMaybeRemove.push_back(I);
5182       break;
5183     }
5184 
5185     case Instruction::Shl: {
5186       auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5187       if (!ShlC)
5188         return false;
5189       uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5190       DemandBits.setLowBits(BitWidth - ShiftAmt);
5191       break;
5192     }
5193 
5194     case Instruction::Trunc: {
5195       EVT TruncVT = TLI->getValueType(*DL, I->getType());
5196       unsigned TruncBitWidth = TruncVT.getSizeInBits();
5197       DemandBits.setLowBits(TruncBitWidth);
5198       break;
5199     }
5200 
5201     default:
5202       return false;
5203     }
5204   }
5205 
5206   uint32_t ActiveBits = DemandBits.getActiveBits();
5207   // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5208   // target even if isLoadExtLegal says an i1 EXTLOAD is valid.  For example,
5209   // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5210   // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5211   // followed by an AND.
5212   // TODO: Look into removing this restriction by fixing backends to either
5213   // return false for isLoadExtLegal for i1 or have them select this pattern to
5214   // a single instruction.
5215   //
5216   // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5217   // mask, since these are the only ands that will be removed by isel.
5218   if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
5219       WidestAndBits != DemandBits)
5220     return false;
5221 
5222   LLVMContext &Ctx = Load->getType()->getContext();
5223   Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5224   EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5225 
5226   // Reject cases that won't be matched as extloads.
5227   if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5228       !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5229     return false;
5230 
5231   IRBuilder<> Builder(Load->getNextNode());
5232   auto *NewAnd = dyn_cast<Instruction>(
5233       Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5234   // Mark this instruction as "inserted by CGP", so that other
5235   // optimizations don't touch it.
5236   InsertedInsts.insert(NewAnd);
5237 
5238   // Replace all uses of load with new and (except for the use of load in the
5239   // new and itself).
5240   Load->replaceAllUsesWith(NewAnd);
5241   NewAnd->setOperand(0, Load);
5242 
5243   // Remove any and instructions that are now redundant.
5244   for (auto *And : AndsToMaybeRemove)
5245     // Check that the and mask is the same as the one we decided to put on the
5246     // new and.
5247     if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5248       And->replaceAllUsesWith(NewAnd);
5249       if (&*CurInstIterator == And)
5250         CurInstIterator = std::next(And->getIterator());
5251       And->eraseFromParent();
5252       ++NumAndUses;
5253     }
5254 
5255   ++NumAndsAdded;
5256   return true;
5257 }
5258 
5259 /// Check if V (an operand of a select instruction) is an expensive instruction
5260 /// that is only used once.
5261 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5262   auto *I = dyn_cast<Instruction>(V);
5263   // If it's safe to speculatively execute, then it should not have side
5264   // effects; therefore, it's safe to sink and possibly *not* execute.
5265   return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5266          TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5267 }
5268 
5269 /// Returns true if a SelectInst should be turned into an explicit branch.
5270 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
5271                                                 const TargetLowering *TLI,
5272                                                 SelectInst *SI) {
5273   // If even a predictable select is cheap, then a branch can't be cheaper.
5274   if (!TLI->isPredictableSelectExpensive())
5275     return false;
5276 
5277   // FIXME: This should use the same heuristics as IfConversion to determine
5278   // whether a select is better represented as a branch.
5279 
5280   // If metadata tells us that the select condition is obviously predictable,
5281   // then we want to replace the select with a branch.
5282   uint64_t TrueWeight, FalseWeight;
5283   if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5284     uint64_t Max = std::max(TrueWeight, FalseWeight);
5285     uint64_t Sum = TrueWeight + FalseWeight;
5286     if (Sum != 0) {
5287       auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5288       if (Probability > TLI->getPredictableBranchThreshold())
5289         return true;
5290     }
5291   }
5292 
5293   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5294 
5295   // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5296   // comparison condition. If the compare has more than one use, there's
5297   // probably another cmov or setcc around, so it's not worth emitting a branch.
5298   if (!Cmp || !Cmp->hasOneUse())
5299     return false;
5300 
5301   // If either operand of the select is expensive and only needed on one side
5302   // of the select, we should form a branch.
5303   if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5304       sinkSelectOperand(TTI, SI->getFalseValue()))
5305     return true;
5306 
5307   return false;
5308 }
5309 
5310 /// If \p isTrue is true, return the true value of \p SI, otherwise return
5311 /// false value of \p SI. If the true/false value of \p SI is defined by any
5312 /// select instructions in \p Selects, look through the defining select
5313 /// instruction until the true/false value is not defined in \p Selects.
5314 static Value *getTrueOrFalseValue(
5315     SelectInst *SI, bool isTrue,
5316     const SmallPtrSet<const Instruction *, 2> &Selects) {
5317   Value *V;
5318 
5319   for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5320        DefSI = dyn_cast<SelectInst>(V)) {
5321     assert(DefSI->getCondition() == SI->getCondition() &&
5322            "The condition of DefSI does not match with SI");
5323     V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5324   }
5325   return V;
5326 }
5327 
5328 /// If we have a SelectInst that will likely profit from branch prediction,
5329 /// turn it into a branch.
5330 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5331   // Find all consecutive select instructions that share the same condition.
5332   SmallVector<SelectInst *, 2> ASI;
5333   ASI.push_back(SI);
5334   for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5335        It != SI->getParent()->end(); ++It) {
5336     SelectInst *I = dyn_cast<SelectInst>(&*It);
5337     if (I && SI->getCondition() == I->getCondition()) {
5338       ASI.push_back(I);
5339     } else {
5340       break;
5341     }
5342   }
5343 
5344   SelectInst *LastSI = ASI.back();
5345   // Increment the current iterator to skip all the rest of select instructions
5346   // because they will be either "not lowered" or "all lowered" to branch.
5347   CurInstIterator = std::next(LastSI->getIterator());
5348 
5349   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5350 
5351   // Can we convert the 'select' to CF ?
5352   if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5353       SI->getMetadata(LLVMContext::MD_unpredictable))
5354     return false;
5355 
5356   TargetLowering::SelectSupportKind SelectKind;
5357   if (VectorCond)
5358     SelectKind = TargetLowering::VectorMaskSelect;
5359   else if (SI->getType()->isVectorTy())
5360     SelectKind = TargetLowering::ScalarCondVectorVal;
5361   else
5362     SelectKind = TargetLowering::ScalarValSelect;
5363 
5364   if (TLI->isSelectSupported(SelectKind) &&
5365       !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5366     return false;
5367 
5368   ModifiedDT = true;
5369 
5370   // Transform a sequence like this:
5371   //    start:
5372   //       %cmp = cmp uge i32 %a, %b
5373   //       %sel = select i1 %cmp, i32 %c, i32 %d
5374   //
5375   // Into:
5376   //    start:
5377   //       %cmp = cmp uge i32 %a, %b
5378   //       br i1 %cmp, label %select.true, label %select.false
5379   //    select.true:
5380   //       br label %select.end
5381   //    select.false:
5382   //       br label %select.end
5383   //    select.end:
5384   //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5385   //
5386   // In addition, we may sink instructions that produce %c or %d from
5387   // the entry block into the destination(s) of the new branch.
5388   // If the true or false blocks do not contain a sunken instruction, that
5389   // block and its branch may be optimized away. In that case, one side of the
5390   // first branch will point directly to select.end, and the corresponding PHI
5391   // predecessor block will be the start block.
5392 
5393   // First, we split the block containing the select into 2 blocks.
5394   BasicBlock *StartBlock = SI->getParent();
5395   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
5396   BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
5397 
5398   // Delete the unconditional branch that was just created by the split.
5399   StartBlock->getTerminator()->eraseFromParent();
5400 
5401   // These are the new basic blocks for the conditional branch.
5402   // At least one will become an actual new basic block.
5403   BasicBlock *TrueBlock = nullptr;
5404   BasicBlock *FalseBlock = nullptr;
5405   BranchInst *TrueBranch = nullptr;
5406   BranchInst *FalseBranch = nullptr;
5407 
5408   // Sink expensive instructions into the conditional blocks to avoid executing
5409   // them speculatively.
5410   for (SelectInst *SI : ASI) {
5411     if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5412       if (TrueBlock == nullptr) {
5413         TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5414                                        EndBlock->getParent(), EndBlock);
5415         TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5416       }
5417       auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5418       TrueInst->moveBefore(TrueBranch);
5419     }
5420     if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5421       if (FalseBlock == nullptr) {
5422         FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5423                                         EndBlock->getParent(), EndBlock);
5424         FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5425       }
5426       auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5427       FalseInst->moveBefore(FalseBranch);
5428     }
5429   }
5430 
5431   // If there was nothing to sink, then arbitrarily choose the 'false' side
5432   // for a new input value to the PHI.
5433   if (TrueBlock == FalseBlock) {
5434     assert(TrueBlock == nullptr &&
5435            "Unexpected basic block transform while optimizing select");
5436 
5437     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5438                                     EndBlock->getParent(), EndBlock);
5439     BranchInst::Create(EndBlock, FalseBlock);
5440   }
5441 
5442   // Insert the real conditional branch based on the original condition.
5443   // If we did not create a new block for one of the 'true' or 'false' paths
5444   // of the condition, it means that side of the branch goes to the end block
5445   // directly and the path originates from the start block from the point of
5446   // view of the new PHI.
5447   BasicBlock *TT, *FT;
5448   if (TrueBlock == nullptr) {
5449     TT = EndBlock;
5450     FT = FalseBlock;
5451     TrueBlock = StartBlock;
5452   } else if (FalseBlock == nullptr) {
5453     TT = TrueBlock;
5454     FT = EndBlock;
5455     FalseBlock = StartBlock;
5456   } else {
5457     TT = TrueBlock;
5458     FT = FalseBlock;
5459   }
5460   IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
5461 
5462   SmallPtrSet<const Instruction *, 2> INS;
5463   INS.insert(ASI.begin(), ASI.end());
5464   // Use reverse iterator because later select may use the value of the
5465   // earlier select, and we need to propagate value through earlier select
5466   // to get the PHI operand.
5467   for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5468     SelectInst *SI = *It;
5469     // The select itself is replaced with a PHI Node.
5470     PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5471     PN->takeName(SI);
5472     PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5473     PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
5474 
5475     SI->replaceAllUsesWith(PN);
5476     SI->eraseFromParent();
5477     INS.erase(SI);
5478     ++NumSelectsExpanded;
5479   }
5480 
5481   // Instruct OptimizeBlock to skip to the next block.
5482   CurInstIterator = StartBlock->end();
5483   return true;
5484 }
5485 
5486 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
5487   SmallVector<int, 16> Mask(SVI->getShuffleMask());
5488   int SplatElem = -1;
5489   for (unsigned i = 0; i < Mask.size(); ++i) {
5490     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5491       return false;
5492     SplatElem = Mask[i];
5493   }
5494 
5495   return true;
5496 }
5497 
5498 /// Some targets have expensive vector shifts if the lanes aren't all the same
5499 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5500 /// it's often worth sinking a shufflevector splat down to its use so that
5501 /// codegen can spot all lanes are identical.
5502 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
5503   BasicBlock *DefBB = SVI->getParent();
5504 
5505   // Only do this xform if variable vector shifts are particularly expensive.
5506   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5507     return false;
5508 
5509   // We only expect better codegen by sinking a shuffle if we can recognise a
5510   // constant splat.
5511   if (!isBroadcastShuffle(SVI))
5512     return false;
5513 
5514   // InsertedShuffles - Only insert a shuffle in each block once.
5515   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5516 
5517   bool MadeChange = false;
5518   for (User *U : SVI->users()) {
5519     Instruction *UI = cast<Instruction>(U);
5520 
5521     // Figure out which BB this ext is used in.
5522     BasicBlock *UserBB = UI->getParent();
5523     if (UserBB == DefBB) continue;
5524 
5525     // For now only apply this when the splat is used by a shift instruction.
5526     if (!UI->isShift()) continue;
5527 
5528     // Everything checks out, sink the shuffle if the user's block doesn't
5529     // already have a copy.
5530     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5531 
5532     if (!InsertedShuffle) {
5533       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5534       assert(InsertPt != UserBB->end());
5535       InsertedShuffle =
5536           new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5537                                 SVI->getOperand(2), "", &*InsertPt);
5538     }
5539 
5540     UI->replaceUsesOfWith(SVI, InsertedShuffle);
5541     MadeChange = true;
5542   }
5543 
5544   // If we removed all uses, nuke the shuffle.
5545   if (SVI->use_empty()) {
5546     SVI->eraseFromParent();
5547     MadeChange = true;
5548   }
5549 
5550   return MadeChange;
5551 }
5552 
5553 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5554   if (!TLI || !DL)
5555     return false;
5556 
5557   Value *Cond = SI->getCondition();
5558   Type *OldType = Cond->getType();
5559   LLVMContext &Context = Cond->getContext();
5560   MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5561   unsigned RegWidth = RegType.getSizeInBits();
5562 
5563   if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5564     return false;
5565 
5566   // If the register width is greater than the type width, expand the condition
5567   // of the switch instruction and each case constant to the width of the
5568   // register. By widening the type of the switch condition, subsequent
5569   // comparisons (for case comparisons) will not need to be extended to the
5570   // preferred register width, so we will potentially eliminate N-1 extends,
5571   // where N is the number of cases in the switch.
5572   auto *NewType = Type::getIntNTy(Context, RegWidth);
5573 
5574   // Zero-extend the switch condition and case constants unless the switch
5575   // condition is a function argument that is already being sign-extended.
5576   // In that case, we can avoid an unnecessary mask/extension by sign-extending
5577   // everything instead.
5578   Instruction::CastOps ExtType = Instruction::ZExt;
5579   if (auto *Arg = dyn_cast<Argument>(Cond))
5580     if (Arg->hasSExtAttr())
5581       ExtType = Instruction::SExt;
5582 
5583   auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5584   ExtInst->insertBefore(SI);
5585   SI->setCondition(ExtInst);
5586   for (auto Case : SI->cases()) {
5587     APInt NarrowConst = Case.getCaseValue()->getValue();
5588     APInt WideConst = (ExtType == Instruction::ZExt) ?
5589                       NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5590     Case.setValue(ConstantInt::get(Context, WideConst));
5591   }
5592 
5593   return true;
5594 }
5595 
5596 
5597 namespace {
5598 
5599 /// \brief Helper class to promote a scalar operation to a vector one.
5600 /// This class is used to move downward extractelement transition.
5601 /// E.g.,
5602 /// a = vector_op <2 x i32>
5603 /// b = extractelement <2 x i32> a, i32 0
5604 /// c = scalar_op b
5605 /// store c
5606 ///
5607 /// =>
5608 /// a = vector_op <2 x i32>
5609 /// c = vector_op a (equivalent to scalar_op on the related lane)
5610 /// * d = extractelement <2 x i32> c, i32 0
5611 /// * store d
5612 /// Assuming both extractelement and store can be combine, we get rid of the
5613 /// transition.
5614 class VectorPromoteHelper {
5615   /// DataLayout associated with the current module.
5616   const DataLayout &DL;
5617 
5618   /// Used to perform some checks on the legality of vector operations.
5619   const TargetLowering &TLI;
5620 
5621   /// Used to estimated the cost of the promoted chain.
5622   const TargetTransformInfo &TTI;
5623 
5624   /// The transition being moved downwards.
5625   Instruction *Transition;
5626 
5627   /// The sequence of instructions to be promoted.
5628   SmallVector<Instruction *, 4> InstsToBePromoted;
5629 
5630   /// Cost of combining a store and an extract.
5631   unsigned StoreExtractCombineCost;
5632 
5633   /// Instruction that will be combined with the transition.
5634   Instruction *CombineInst = nullptr;
5635 
5636   /// \brief The instruction that represents the current end of the transition.
5637   /// Since we are faking the promotion until we reach the end of the chain
5638   /// of computation, we need a way to get the current end of the transition.
5639   Instruction *getEndOfTransition() const {
5640     if (InstsToBePromoted.empty())
5641       return Transition;
5642     return InstsToBePromoted.back();
5643   }
5644 
5645   /// \brief Return the index of the original value in the transition.
5646   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5647   /// c, is at index 0.
5648   unsigned getTransitionOriginalValueIdx() const {
5649     assert(isa<ExtractElementInst>(Transition) &&
5650            "Other kind of transitions are not supported yet");
5651     return 0;
5652   }
5653 
5654   /// \brief Return the index of the index in the transition.
5655   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5656   /// is at index 1.
5657   unsigned getTransitionIdx() const {
5658     assert(isa<ExtractElementInst>(Transition) &&
5659            "Other kind of transitions are not supported yet");
5660     return 1;
5661   }
5662 
5663   /// \brief Get the type of the transition.
5664   /// This is the type of the original value.
5665   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5666   /// transition is <2 x i32>.
5667   Type *getTransitionType() const {
5668     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5669   }
5670 
5671   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5672   /// I.e., we have the following sequence:
5673   /// Def = Transition <ty1> a to <ty2>
5674   /// b = ToBePromoted <ty2> Def, ...
5675   /// =>
5676   /// b = ToBePromoted <ty1> a, ...
5677   /// Def = Transition <ty1> ToBePromoted to <ty2>
5678   void promoteImpl(Instruction *ToBePromoted);
5679 
5680   /// \brief Check whether or not it is profitable to promote all the
5681   /// instructions enqueued to be promoted.
5682   bool isProfitableToPromote() {
5683     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5684     unsigned Index = isa<ConstantInt>(ValIdx)
5685                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
5686                          : -1;
5687     Type *PromotedType = getTransitionType();
5688 
5689     StoreInst *ST = cast<StoreInst>(CombineInst);
5690     unsigned AS = ST->getPointerAddressSpace();
5691     unsigned Align = ST->getAlignment();
5692     // Check if this store is supported.
5693     if (!TLI.allowsMisalignedMemoryAccesses(
5694             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5695             Align)) {
5696       // If this is not supported, there is no way we can combine
5697       // the extract with the store.
5698       return false;
5699     }
5700 
5701     // The scalar chain of computation has to pay for the transition
5702     // scalar to vector.
5703     // The vector chain has to account for the combining cost.
5704     uint64_t ScalarCost =
5705         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5706     uint64_t VectorCost = StoreExtractCombineCost;
5707     for (const auto &Inst : InstsToBePromoted) {
5708       // Compute the cost.
5709       // By construction, all instructions being promoted are arithmetic ones.
5710       // Moreover, one argument is a constant that can be viewed as a splat
5711       // constant.
5712       Value *Arg0 = Inst->getOperand(0);
5713       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5714                             isa<ConstantFP>(Arg0);
5715       TargetTransformInfo::OperandValueKind Arg0OVK =
5716           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5717                          : TargetTransformInfo::OK_AnyValue;
5718       TargetTransformInfo::OperandValueKind Arg1OVK =
5719           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5720                           : TargetTransformInfo::OK_AnyValue;
5721       ScalarCost += TTI.getArithmeticInstrCost(
5722           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5723       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5724                                                Arg0OVK, Arg1OVK);
5725     }
5726     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5727                  << ScalarCost << "\nVector: " << VectorCost << '\n');
5728     return ScalarCost > VectorCost;
5729   }
5730 
5731   /// \brief Generate a constant vector with \p Val with the same
5732   /// number of elements as the transition.
5733   /// \p UseSplat defines whether or not \p Val should be replicated
5734   /// across the whole vector.
5735   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5736   /// otherwise we generate a vector with as many undef as possible:
5737   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5738   /// used at the index of the extract.
5739   Value *getConstantVector(Constant *Val, bool UseSplat) const {
5740     unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
5741     if (!UseSplat) {
5742       // If we cannot determine where the constant must be, we have to
5743       // use a splat constant.
5744       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5745       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5746         ExtractIdx = CstVal->getSExtValue();
5747       else
5748         UseSplat = true;
5749     }
5750 
5751     unsigned End = getTransitionType()->getVectorNumElements();
5752     if (UseSplat)
5753       return ConstantVector::getSplat(End, Val);
5754 
5755     SmallVector<Constant *, 4> ConstVec;
5756     UndefValue *UndefVal = UndefValue::get(Val->getType());
5757     for (unsigned Idx = 0; Idx != End; ++Idx) {
5758       if (Idx == ExtractIdx)
5759         ConstVec.push_back(Val);
5760       else
5761         ConstVec.push_back(UndefVal);
5762     }
5763     return ConstantVector::get(ConstVec);
5764   }
5765 
5766   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5767   /// in \p Use can trigger undefined behavior.
5768   static bool canCauseUndefinedBehavior(const Instruction *Use,
5769                                         unsigned OperandIdx) {
5770     // This is not safe to introduce undef when the operand is on
5771     // the right hand side of a division-like instruction.
5772     if (OperandIdx != 1)
5773       return false;
5774     switch (Use->getOpcode()) {
5775     default:
5776       return false;
5777     case Instruction::SDiv:
5778     case Instruction::UDiv:
5779     case Instruction::SRem:
5780     case Instruction::URem:
5781       return true;
5782     case Instruction::FDiv:
5783     case Instruction::FRem:
5784       return !Use->hasNoNaNs();
5785     }
5786     llvm_unreachable(nullptr);
5787   }
5788 
5789 public:
5790   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5791                       const TargetTransformInfo &TTI, Instruction *Transition,
5792                       unsigned CombineCost)
5793       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
5794         StoreExtractCombineCost(CombineCost) {
5795     assert(Transition && "Do not know how to promote null");
5796   }
5797 
5798   /// \brief Check if we can promote \p ToBePromoted to \p Type.
5799   bool canPromote(const Instruction *ToBePromoted) const {
5800     // We could support CastInst too.
5801     return isa<BinaryOperator>(ToBePromoted);
5802   }
5803 
5804   /// \brief Check if it is profitable to promote \p ToBePromoted
5805   /// by moving downward the transition through.
5806   bool shouldPromote(const Instruction *ToBePromoted) const {
5807     // Promote only if all the operands can be statically expanded.
5808     // Indeed, we do not want to introduce any new kind of transitions.
5809     for (const Use &U : ToBePromoted->operands()) {
5810       const Value *Val = U.get();
5811       if (Val == getEndOfTransition()) {
5812         // If the use is a division and the transition is on the rhs,
5813         // we cannot promote the operation, otherwise we may create a
5814         // division by zero.
5815         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5816           return false;
5817         continue;
5818       }
5819       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5820           !isa<ConstantFP>(Val))
5821         return false;
5822     }
5823     // Check that the resulting operation is legal.
5824     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5825     if (!ISDOpcode)
5826       return false;
5827     return StressStoreExtract ||
5828            TLI.isOperationLegalOrCustom(
5829                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
5830   }
5831 
5832   /// \brief Check whether or not \p Use can be combined
5833   /// with the transition.
5834   /// I.e., is it possible to do Use(Transition) => AnotherUse?
5835   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5836 
5837   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5838   void enqueueForPromotion(Instruction *ToBePromoted) {
5839     InstsToBePromoted.push_back(ToBePromoted);
5840   }
5841 
5842   /// \brief Set the instruction that will be combined with the transition.
5843   void recordCombineInstruction(Instruction *ToBeCombined) {
5844     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5845     CombineInst = ToBeCombined;
5846   }
5847 
5848   /// \brief Promote all the instructions enqueued for promotion if it is
5849   /// is profitable.
5850   /// \return True if the promotion happened, false otherwise.
5851   bool promote() {
5852     // Check if there is something to promote.
5853     // Right now, if we do not have anything to combine with,
5854     // we assume the promotion is not profitable.
5855     if (InstsToBePromoted.empty() || !CombineInst)
5856       return false;
5857 
5858     // Check cost.
5859     if (!StressStoreExtract && !isProfitableToPromote())
5860       return false;
5861 
5862     // Promote.
5863     for (auto &ToBePromoted : InstsToBePromoted)
5864       promoteImpl(ToBePromoted);
5865     InstsToBePromoted.clear();
5866     return true;
5867   }
5868 };
5869 
5870 } // end anonymous namespace
5871 
5872 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5873   // At this point, we know that all the operands of ToBePromoted but Def
5874   // can be statically promoted.
5875   // For Def, we need to use its parameter in ToBePromoted:
5876   // b = ToBePromoted ty1 a
5877   // Def = Transition ty1 b to ty2
5878   // Move the transition down.
5879   // 1. Replace all uses of the promoted operation by the transition.
5880   // = ... b => = ... Def.
5881   assert(ToBePromoted->getType() == Transition->getType() &&
5882          "The type of the result of the transition does not match "
5883          "the final type");
5884   ToBePromoted->replaceAllUsesWith(Transition);
5885   // 2. Update the type of the uses.
5886   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5887   Type *TransitionTy = getTransitionType();
5888   ToBePromoted->mutateType(TransitionTy);
5889   // 3. Update all the operands of the promoted operation with promoted
5890   // operands.
5891   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5892   for (Use &U : ToBePromoted->operands()) {
5893     Value *Val = U.get();
5894     Value *NewVal = nullptr;
5895     if (Val == Transition)
5896       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5897     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5898              isa<ConstantFP>(Val)) {
5899       // Use a splat constant if it is not safe to use undef.
5900       NewVal = getConstantVector(
5901           cast<Constant>(Val),
5902           isa<UndefValue>(Val) ||
5903               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5904     } else
5905       llvm_unreachable("Did you modified shouldPromote and forgot to update "
5906                        "this?");
5907     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5908   }
5909   Transition->moveAfter(ToBePromoted);
5910   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5911 }
5912 
5913 /// Some targets can do store(extractelement) with one instruction.
5914 /// Try to push the extractelement towards the stores when the target
5915 /// has this feature and this is profitable.
5916 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
5917   unsigned CombineCost = std::numeric_limits<unsigned>::max();
5918   if (DisableStoreExtract || !TLI ||
5919       (!StressStoreExtract &&
5920        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5921                                        Inst->getOperand(1), CombineCost)))
5922     return false;
5923 
5924   // At this point we know that Inst is a vector to scalar transition.
5925   // Try to move it down the def-use chain, until:
5926   // - We can combine the transition with its single use
5927   //   => we got rid of the transition.
5928   // - We escape the current basic block
5929   //   => we would need to check that we are moving it at a cheaper place and
5930   //      we do not do that for now.
5931   BasicBlock *Parent = Inst->getParent();
5932   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
5933   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
5934   // If the transition has more than one use, assume this is not going to be
5935   // beneficial.
5936   while (Inst->hasOneUse()) {
5937     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5938     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5939 
5940     if (ToBePromoted->getParent() != Parent) {
5941       DEBUG(dbgs() << "Instruction to promote is in a different block ("
5942                    << ToBePromoted->getParent()->getName()
5943                    << ") than the transition (" << Parent->getName() << ").\n");
5944       return false;
5945     }
5946 
5947     if (VPH.canCombine(ToBePromoted)) {
5948       DEBUG(dbgs() << "Assume " << *Inst << '\n'
5949                    << "will be combined with: " << *ToBePromoted << '\n');
5950       VPH.recordCombineInstruction(ToBePromoted);
5951       bool Changed = VPH.promote();
5952       NumStoreExtractExposed += Changed;
5953       return Changed;
5954     }
5955 
5956     DEBUG(dbgs() << "Try promoting.\n");
5957     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5958       return false;
5959 
5960     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5961 
5962     VPH.enqueueForPromotion(ToBePromoted);
5963     Inst = ToBePromoted;
5964   }
5965   return false;
5966 }
5967 
5968 /// For the instruction sequence of store below, F and I values
5969 /// are bundled together as an i64 value before being stored into memory.
5970 /// Sometimes it is more efficent to generate separate stores for F and I,
5971 /// which can remove the bitwise instructions or sink them to colder places.
5972 ///
5973 ///   (store (or (zext (bitcast F to i32) to i64),
5974 ///              (shl (zext I to i64), 32)), addr)  -->
5975 ///   (store F, addr) and (store I, addr+4)
5976 ///
5977 /// Similarly, splitting for other merged store can also be beneficial, like:
5978 /// For pair of {i32, i32}, i64 store --> two i32 stores.
5979 /// For pair of {i32, i16}, i64 store --> two i32 stores.
5980 /// For pair of {i16, i16}, i32 store --> two i16 stores.
5981 /// For pair of {i16, i8},  i32 store --> two i16 stores.
5982 /// For pair of {i8, i8},   i16 store --> two i8 stores.
5983 ///
5984 /// We allow each target to determine specifically which kind of splitting is
5985 /// supported.
5986 ///
5987 /// The store patterns are commonly seen from the simple code snippet below
5988 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5989 ///   void goo(const std::pair<int, float> &);
5990 ///   hoo() {
5991 ///     ...
5992 ///     goo(std::make_pair(tmp, ftmp));
5993 ///     ...
5994 ///   }
5995 ///
5996 /// Although we already have similar splitting in DAG Combine, we duplicate
5997 /// it in CodeGenPrepare to catch the case in which pattern is across
5998 /// multiple BBs. The logic in DAG Combine is kept to catch case generated
5999 /// during code expansion.
6000 static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6001                                 const TargetLowering &TLI) {
6002   // Handle simple but common cases only.
6003   Type *StoreType = SI.getValueOperand()->getType();
6004   if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6005       DL.getTypeSizeInBits(StoreType) == 0)
6006     return false;
6007 
6008   unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6009   Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6010   if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6011       DL.getTypeSizeInBits(SplitStoreType))
6012     return false;
6013 
6014   // Match the following patterns:
6015   // (store (or (zext LValue to i64),
6016   //            (shl (zext HValue to i64), 32)), HalfValBitSize)
6017   //  or
6018   // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6019   //            (zext LValue to i64),
6020   // Expect both operands of OR and the first operand of SHL have only
6021   // one use.
6022   Value *LValue, *HValue;
6023   if (!match(SI.getValueOperand(),
6024              m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6025                     m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6026                                    m_SpecificInt(HalfValBitSize))))))
6027     return false;
6028 
6029   // Check LValue and HValue are int with size less or equal than 32.
6030   if (!LValue->getType()->isIntegerTy() ||
6031       DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6032       !HValue->getType()->isIntegerTy() ||
6033       DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6034     return false;
6035 
6036   // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6037   // as the input of target query.
6038   auto *LBC = dyn_cast<BitCastInst>(LValue);
6039   auto *HBC = dyn_cast<BitCastInst>(HValue);
6040   EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6041                   : EVT::getEVT(LValue->getType());
6042   EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6043                    : EVT::getEVT(HValue->getType());
6044   if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6045     return false;
6046 
6047   // Start to split store.
6048   IRBuilder<> Builder(SI.getContext());
6049   Builder.SetInsertPoint(&SI);
6050 
6051   // If LValue/HValue is a bitcast in another BB, create a new one in current
6052   // BB so it may be merged with the splitted stores by dag combiner.
6053   if (LBC && LBC->getParent() != SI.getParent())
6054     LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6055   if (HBC && HBC->getParent() != SI.getParent())
6056     HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6057 
6058   auto CreateSplitStore = [&](Value *V, bool Upper) {
6059     V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6060     Value *Addr = Builder.CreateBitCast(
6061         SI.getOperand(1),
6062         SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6063     if (Upper)
6064       Addr = Builder.CreateGEP(
6065           SplitStoreType, Addr,
6066           ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6067     Builder.CreateAlignedStore(
6068         V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6069   };
6070 
6071   CreateSplitStore(LValue, false);
6072   CreateSplitStore(HValue, true);
6073 
6074   // Delete the old store.
6075   SI.eraseFromParent();
6076   return true;
6077 }
6078 
6079 // Return true if the GEP has two operands, the first operand is of a sequential
6080 // type, and the second operand is a constant.
6081 static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6082   gep_type_iterator I = gep_type_begin(*GEP);
6083   return GEP->getNumOperands() == 2 &&
6084       I.isSequential() &&
6085       isa<ConstantInt>(GEP->getOperand(1));
6086 }
6087 
6088 // Try unmerging GEPs to reduce liveness interference (register pressure) across
6089 // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6090 // reducing liveness interference across those edges benefits global register
6091 // allocation. Currently handles only certain cases.
6092 //
6093 // For example, unmerge %GEPI and %UGEPI as below.
6094 //
6095 // ---------- BEFORE ----------
6096 // SrcBlock:
6097 //   ...
6098 //   %GEPIOp = ...
6099 //   ...
6100 //   %GEPI = gep %GEPIOp, Idx
6101 //   ...
6102 //   indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6103 //   (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6104 //   (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6105 //   %UGEPI)
6106 //
6107 // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6108 // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6109 // ...
6110 //
6111 // DstBi:
6112 //   ...
6113 //   %UGEPI = gep %GEPIOp, UIdx
6114 // ...
6115 // ---------------------------
6116 //
6117 // ---------- AFTER ----------
6118 // SrcBlock:
6119 //   ... (same as above)
6120 //    (* %GEPI is still alive on the indirectbr edges)
6121 //    (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6122 //    unmerging)
6123 // ...
6124 //
6125 // DstBi:
6126 //   ...
6127 //   %UGEPI = gep %GEPI, (UIdx-Idx)
6128 //   ...
6129 // ---------------------------
6130 //
6131 // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6132 // no longer alive on them.
6133 //
6134 // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6135 // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6136 // not to disable further simplications and optimizations as a result of GEP
6137 // merging.
6138 //
6139 // Note this unmerging may increase the length of the data flow critical path
6140 // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6141 // between the register pressure and the length of data-flow critical
6142 // path. Restricting this to the uncommon IndirectBr case would minimize the
6143 // impact of potentially longer critical path, if any, and the impact on compile
6144 // time.
6145 static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6146                                              const TargetTransformInfo *TTI) {
6147   BasicBlock *SrcBlock = GEPI->getParent();
6148   // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6149   // (non-IndirectBr) cases exit early here.
6150   if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6151     return false;
6152   // Check that GEPI is a simple gep with a single constant index.
6153   if (!GEPSequentialConstIndexed(GEPI))
6154     return false;
6155   ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6156   // Check that GEPI is a cheap one.
6157   if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6158       > TargetTransformInfo::TCC_Basic)
6159     return false;
6160   Value *GEPIOp = GEPI->getOperand(0);
6161   // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6162   if (!isa<Instruction>(GEPIOp))
6163     return false;
6164   auto *GEPIOpI = cast<Instruction>(GEPIOp);
6165   if (GEPIOpI->getParent() != SrcBlock)
6166     return false;
6167   // Check that GEP is used outside the block, meaning it's alive on the
6168   // IndirectBr edge(s).
6169   if (find_if(GEPI->users(), [&](User *Usr) {
6170         if (auto *I = dyn_cast<Instruction>(Usr)) {
6171           if (I->getParent() != SrcBlock) {
6172             return true;
6173           }
6174         }
6175         return false;
6176       }) == GEPI->users().end())
6177     return false;
6178   // The second elements of the GEP chains to be unmerged.
6179   std::vector<GetElementPtrInst *> UGEPIs;
6180   // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6181   // on IndirectBr edges.
6182   for (User *Usr : GEPIOp->users()) {
6183     if (Usr == GEPI) continue;
6184     // Check if Usr is an Instruction. If not, give up.
6185     if (!isa<Instruction>(Usr))
6186       return false;
6187     auto *UI = cast<Instruction>(Usr);
6188     // Check if Usr in the same block as GEPIOp, which is fine, skip.
6189     if (UI->getParent() == SrcBlock)
6190       continue;
6191     // Check if Usr is a GEP. If not, give up.
6192     if (!isa<GetElementPtrInst>(Usr))
6193       return false;
6194     auto *UGEPI = cast<GetElementPtrInst>(Usr);
6195     // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6196     // the pointer operand to it. If so, record it in the vector. If not, give
6197     // up.
6198     if (!GEPSequentialConstIndexed(UGEPI))
6199       return false;
6200     if (UGEPI->getOperand(0) != GEPIOp)
6201       return false;
6202     if (GEPIIdx->getType() !=
6203         cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6204       return false;
6205     ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6206     if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6207         > TargetTransformInfo::TCC_Basic)
6208       return false;
6209     UGEPIs.push_back(UGEPI);
6210   }
6211   if (UGEPIs.size() == 0)
6212     return false;
6213   // Check the materializing cost of (Uidx-Idx).
6214   for (GetElementPtrInst *UGEPI : UGEPIs) {
6215     ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6216     APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6217     unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6218     if (ImmCost > TargetTransformInfo::TCC_Basic)
6219       return false;
6220   }
6221   // Now unmerge between GEPI and UGEPIs.
6222   for (GetElementPtrInst *UGEPI : UGEPIs) {
6223     UGEPI->setOperand(0, GEPI);
6224     ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6225     Constant *NewUGEPIIdx =
6226         ConstantInt::get(GEPIIdx->getType(),
6227                          UGEPIIdx->getValue() - GEPIIdx->getValue());
6228     UGEPI->setOperand(1, NewUGEPIIdx);
6229     // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6230     // inbounds to avoid UB.
6231     if (!GEPI->isInBounds()) {
6232       UGEPI->setIsInBounds(false);
6233     }
6234   }
6235   // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6236   // alive on IndirectBr edges).
6237   assert(find_if(GEPIOp->users(), [&](User *Usr) {
6238         return cast<Instruction>(Usr)->getParent() != SrcBlock;
6239       }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6240   return true;
6241 }
6242 
6243 bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
6244   // Bail out if we inserted the instruction to prevent optimizations from
6245   // stepping on each other's toes.
6246   if (InsertedInsts.count(I))
6247     return false;
6248 
6249   if (PHINode *P = dyn_cast<PHINode>(I)) {
6250     // It is possible for very late stage optimizations (such as SimplifyCFG)
6251     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
6252     // trivial PHI, go ahead and zap it here.
6253     if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
6254       P->replaceAllUsesWith(V);
6255       P->eraseFromParent();
6256       ++NumPHIsElim;
6257       return true;
6258     }
6259     return false;
6260   }
6261 
6262   if (CastInst *CI = dyn_cast<CastInst>(I)) {
6263     // If the source of the cast is a constant, then this should have
6264     // already been constant folded.  The only reason NOT to constant fold
6265     // it is if something (e.g. LSR) was careful to place the constant
6266     // evaluation in a block other than then one that uses it (e.g. to hoist
6267     // the address of globals out of a loop).  If this is the case, we don't
6268     // want to forward-subst the cast.
6269     if (isa<Constant>(CI->getOperand(0)))
6270       return false;
6271 
6272     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
6273       return true;
6274 
6275     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6276       /// Sink a zext or sext into its user blocks if the target type doesn't
6277       /// fit in one register
6278       if (TLI &&
6279           TLI->getTypeAction(CI->getContext(),
6280                              TLI->getValueType(*DL, CI->getType())) ==
6281               TargetLowering::TypeExpandInteger) {
6282         return SinkCast(CI);
6283       } else {
6284         bool MadeChange = optimizeExt(I);
6285         return MadeChange | optimizeExtUses(I);
6286       }
6287     }
6288     return false;
6289   }
6290 
6291   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6292     if (!TLI || !TLI->hasMultipleConditionRegisters())
6293       return OptimizeCmpExpression(CI, TLI);
6294 
6295   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6296     LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
6297     if (TLI) {
6298       bool Modified = optimizeLoadExt(LI);
6299       unsigned AS = LI->getPointerAddressSpace();
6300       Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6301       return Modified;
6302     }
6303     return false;
6304   }
6305 
6306   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6307     if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6308       return true;
6309     SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
6310     if (TLI) {
6311       unsigned AS = SI->getPointerAddressSpace();
6312       return optimizeMemoryInst(I, SI->getOperand(1),
6313                                 SI->getOperand(0)->getType(), AS);
6314     }
6315     return false;
6316   }
6317 
6318   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6319       unsigned AS = RMW->getPointerAddressSpace();
6320       return optimizeMemoryInst(I, RMW->getPointerOperand(),
6321                                 RMW->getType(), AS);
6322   }
6323 
6324   if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6325       unsigned AS = CmpX->getPointerAddressSpace();
6326       return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6327                                 CmpX->getCompareOperand()->getType(), AS);
6328   }
6329 
6330   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6331 
6332   if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6333       EnableAndCmpSinking && TLI)
6334     return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6335 
6336   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6337                 BinOp->getOpcode() == Instruction::LShr)) {
6338     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6339     if (TLI && CI && TLI->hasExtractBitsInsn())
6340       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
6341 
6342     return false;
6343   }
6344 
6345   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
6346     if (GEPI->hasAllZeroIndices()) {
6347       /// The GEP operand must be a pointer, so must its result -> BitCast
6348       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6349                                         GEPI->getName(), GEPI);
6350       GEPI->replaceAllUsesWith(NC);
6351       GEPI->eraseFromParent();
6352       ++NumGEPsElim;
6353       optimizeInst(NC, ModifiedDT);
6354       return true;
6355     }
6356     if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6357       return true;
6358     }
6359     return false;
6360   }
6361 
6362   if (CallInst *CI = dyn_cast<CallInst>(I))
6363     return optimizeCallInst(CI, ModifiedDT);
6364 
6365   if (SelectInst *SI = dyn_cast<SelectInst>(I))
6366     return optimizeSelectInst(SI);
6367 
6368   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
6369     return optimizeShuffleVectorInst(SVI);
6370 
6371   if (auto *Switch = dyn_cast<SwitchInst>(I))
6372     return optimizeSwitchInst(Switch);
6373 
6374   if (isa<ExtractElementInst>(I))
6375     return optimizeExtractElementInst(I);
6376 
6377   return false;
6378 }
6379 
6380 /// Given an OR instruction, check to see if this is a bitreverse
6381 /// idiom. If so, insert the new intrinsic and return true.
6382 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6383                            const TargetLowering &TLI) {
6384   if (!I.getType()->isIntegerTy() ||
6385       !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6386                                     TLI.getValueType(DL, I.getType(), true)))
6387     return false;
6388 
6389   SmallVector<Instruction*, 4> Insts;
6390   if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
6391     return false;
6392   Instruction *LastInst = Insts.back();
6393   I.replaceAllUsesWith(LastInst);
6394   RecursivelyDeleteTriviallyDeadInstructions(&I);
6395   return true;
6396 }
6397 
6398 // In this pass we look for GEP and cast instructions that are used
6399 // across basic blocks and rewrite them to improve basic-block-at-a-time
6400 // selection.
6401 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
6402   SunkAddrs.clear();
6403   bool MadeChange = false;
6404 
6405   CurInstIterator = BB.begin();
6406   while (CurInstIterator != BB.end()) {
6407     MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6408     if (ModifiedDT)
6409       return true;
6410   }
6411 
6412   bool MadeBitReverse = true;
6413   while (TLI && MadeBitReverse) {
6414     MadeBitReverse = false;
6415     for (auto &I : reverse(BB)) {
6416       if (makeBitReverse(I, *DL, *TLI)) {
6417         MadeBitReverse = MadeChange = true;
6418         ModifiedDT = true;
6419         break;
6420       }
6421     }
6422   }
6423   MadeChange |= dupRetToEnableTailCallOpts(&BB);
6424 
6425   return MadeChange;
6426 }
6427 
6428 // llvm.dbg.value is far away from the value then iSel may not be able
6429 // handle it properly. iSel will drop llvm.dbg.value if it can not
6430 // find a node corresponding to the value.
6431 bool CodeGenPrepare::placeDbgValues(Function &F) {
6432   bool MadeChange = false;
6433   for (BasicBlock &BB : F) {
6434     Instruction *PrevNonDbgInst = nullptr;
6435     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
6436       Instruction *Insn = &*BI++;
6437       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
6438       // Leave dbg.values that refer to an alloca alone. These
6439       // intrinsics describe the address of a variable (= the alloca)
6440       // being taken.  They should not be moved next to the alloca
6441       // (and to the beginning of the scope), but rather stay close to
6442       // where said address is used.
6443       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
6444         PrevNonDbgInst = Insn;
6445         continue;
6446       }
6447 
6448       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6449       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
6450         // If VI is a phi in a block with an EHPad terminator, we can't insert
6451         // after it.
6452         if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6453           continue;
6454         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6455         DVI->removeFromParent();
6456         if (isa<PHINode>(VI))
6457           DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6458         else
6459           DVI->insertAfter(VI);
6460         MadeChange = true;
6461         ++NumDbgValueMoved;
6462       }
6463     }
6464   }
6465   return MadeChange;
6466 }
6467 
6468 /// \brief Scale down both weights to fit into uint32_t.
6469 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6470   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6471   uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
6472   NewTrue = NewTrue / Scale;
6473   NewFalse = NewFalse / Scale;
6474 }
6475 
6476 /// \brief Some targets prefer to split a conditional branch like:
6477 /// \code
6478 ///   %0 = icmp ne i32 %a, 0
6479 ///   %1 = icmp ne i32 %b, 0
6480 ///   %or.cond = or i1 %0, %1
6481 ///   br i1 %or.cond, label %TrueBB, label %FalseBB
6482 /// \endcode
6483 /// into multiple branch instructions like:
6484 /// \code
6485 ///   bb1:
6486 ///     %0 = icmp ne i32 %a, 0
6487 ///     br i1 %0, label %TrueBB, label %bb2
6488 ///   bb2:
6489 ///     %1 = icmp ne i32 %b, 0
6490 ///     br i1 %1, label %TrueBB, label %FalseBB
6491 /// \endcode
6492 /// This usually allows instruction selection to do even further optimizations
6493 /// and combine the compare with the branch instruction. Currently this is
6494 /// applied for targets which have "cheap" jump instructions.
6495 ///
6496 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6497 ///
6498 bool CodeGenPrepare::splitBranchCondition(Function &F) {
6499   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
6500     return false;
6501 
6502   bool MadeChange = false;
6503   for (auto &BB : F) {
6504     // Does this BB end with the following?
6505     //   %cond1 = icmp|fcmp|binary instruction ...
6506     //   %cond2 = icmp|fcmp|binary instruction ...
6507     //   %cond.or = or|and i1 %cond1, cond2
6508     //   br i1 %cond.or label %dest1, label %dest2"
6509     BinaryOperator *LogicOp;
6510     BasicBlock *TBB, *FBB;
6511     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6512       continue;
6513 
6514     auto *Br1 = cast<BranchInst>(BB.getTerminator());
6515     if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6516       continue;
6517 
6518     unsigned Opc;
6519     Value *Cond1, *Cond2;
6520     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6521                              m_OneUse(m_Value(Cond2)))))
6522       Opc = Instruction::And;
6523     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6524                                  m_OneUse(m_Value(Cond2)))))
6525       Opc = Instruction::Or;
6526     else
6527       continue;
6528 
6529     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6530         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
6531       continue;
6532 
6533     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6534 
6535     // Create a new BB.
6536     auto TmpBB =
6537         BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6538                            BB.getParent(), BB.getNextNode());
6539 
6540     // Update original basic block by using the first condition directly by the
6541     // branch instruction and removing the no longer needed and/or instruction.
6542     Br1->setCondition(Cond1);
6543     LogicOp->eraseFromParent();
6544 
6545     // Depending on the conditon we have to either replace the true or the false
6546     // successor of the original branch instruction.
6547     if (Opc == Instruction::And)
6548       Br1->setSuccessor(0, TmpBB);
6549     else
6550       Br1->setSuccessor(1, TmpBB);
6551 
6552     // Fill in the new basic block.
6553     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6554     if (auto *I = dyn_cast<Instruction>(Cond2)) {
6555       I->removeFromParent();
6556       I->insertBefore(Br2);
6557     }
6558 
6559     // Update PHI nodes in both successors. The original BB needs to be
6560     // replaced in one successor's PHI nodes, because the branch comes now from
6561     // the newly generated BB (NewBB). In the other successor we need to add one
6562     // incoming edge to the PHI nodes, because both branch instructions target
6563     // now the same successor. Depending on the original branch condition
6564     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6565     // we perform the correct update for the PHI nodes.
6566     // This doesn't change the successor order of the just created branch
6567     // instruction (or any other instruction).
6568     if (Opc == Instruction::Or)
6569       std::swap(TBB, FBB);
6570 
6571     // Replace the old BB with the new BB.
6572     for (auto &I : *TBB) {
6573       PHINode *PN = dyn_cast<PHINode>(&I);
6574       if (!PN)
6575         break;
6576       int i;
6577       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6578         PN->setIncomingBlock(i, TmpBB);
6579     }
6580 
6581     // Add another incoming edge form the new BB.
6582     for (auto &I : *FBB) {
6583       PHINode *PN = dyn_cast<PHINode>(&I);
6584       if (!PN)
6585         break;
6586       auto *Val = PN->getIncomingValueForBlock(&BB);
6587       PN->addIncoming(Val, TmpBB);
6588     }
6589 
6590     // Update the branch weights (from SelectionDAGBuilder::
6591     // FindMergedConditions).
6592     if (Opc == Instruction::Or) {
6593       // Codegen X | Y as:
6594       // BB1:
6595       //   jmp_if_X TBB
6596       //   jmp TmpBB
6597       // TmpBB:
6598       //   jmp_if_Y TBB
6599       //   jmp FBB
6600       //
6601 
6602       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6603       // The requirement is that
6604       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6605       //     = TrueProb for orignal BB.
6606       // Assuming the orignal weights are A and B, one choice is to set BB1's
6607       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6608       // assumes that
6609       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6610       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6611       // TmpBB, but the math is more complicated.
6612       uint64_t TrueWeight, FalseWeight;
6613       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6614         uint64_t NewTrueWeight = TrueWeight;
6615         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6616         scaleWeights(NewTrueWeight, NewFalseWeight);
6617         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6618                          .createBranchWeights(TrueWeight, FalseWeight));
6619 
6620         NewTrueWeight = TrueWeight;
6621         NewFalseWeight = 2 * FalseWeight;
6622         scaleWeights(NewTrueWeight, NewFalseWeight);
6623         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6624                          .createBranchWeights(TrueWeight, FalseWeight));
6625       }
6626     } else {
6627       // Codegen X & Y as:
6628       // BB1:
6629       //   jmp_if_X TmpBB
6630       //   jmp FBB
6631       // TmpBB:
6632       //   jmp_if_Y TBB
6633       //   jmp FBB
6634       //
6635       //  This requires creation of TmpBB after CurBB.
6636 
6637       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6638       // The requirement is that
6639       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6640       //     = FalseProb for orignal BB.
6641       // Assuming the orignal weights are A and B, one choice is to set BB1's
6642       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6643       // assumes that
6644       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6645       uint64_t TrueWeight, FalseWeight;
6646       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6647         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6648         uint64_t NewFalseWeight = FalseWeight;
6649         scaleWeights(NewTrueWeight, NewFalseWeight);
6650         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6651                          .createBranchWeights(TrueWeight, FalseWeight));
6652 
6653         NewTrueWeight = 2 * TrueWeight;
6654         NewFalseWeight = FalseWeight;
6655         scaleWeights(NewTrueWeight, NewFalseWeight);
6656         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6657                          .createBranchWeights(TrueWeight, FalseWeight));
6658       }
6659     }
6660 
6661     // Note: No point in getting fancy here, since the DT info is never
6662     // available to CodeGenPrepare.
6663     ModifiedDT = true;
6664 
6665     MadeChange = true;
6666 
6667     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6668           TmpBB->dump());
6669   }
6670   return MadeChange;
6671 }
6672