OSDN Git Service

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