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