blob: 2c1858b944c6525bebf749717e33f6f156ac6adc [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000023#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InlineAsm.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000034#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000035#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000036#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000038#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000039#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000040#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000041#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000044#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000047#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000050using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000051using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000052
Chandler Carruth1b9dde02014-04-22 02:02:50 +000053#define DEBUG_TYPE "codegenprepare"
54
Cameron Zwarichced753f2011-01-05 17:27:27 +000055STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000056STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
57STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000058STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
59 "sunken Cmps");
60STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
61 "of sunken Casts");
62STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
63 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000064STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
65STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
66STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000067STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000068STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000069STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000070STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000071
Cameron Zwarich338d3622011-03-11 21:52:04 +000072static cl::opt<bool> DisableBranchOpts(
73 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
74 cl::desc("Disable branch optimizations in CodeGenPrepare"));
75
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000076static cl::opt<bool>
77 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
78 cl::desc("Disable GC optimizations in CodeGenPrepare"));
79
Benjamin Kramer3d38c172012-05-06 14:25:16 +000080static cl::opt<bool> DisableSelectToBranch(
81 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
82 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000083
Hal Finkelc3998302014-04-12 00:59:48 +000084static cl::opt<bool> AddrSinkUsingGEPs(
85 "addr-sink-using-gep", cl::Hidden, cl::init(false),
86 cl::desc("Address sinking in CGP using GEPs."));
87
Tim Northovercea0abb2014-03-29 08:22:29 +000088static cl::opt<bool> EnableAndCmpSinking(
89 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
90 cl::desc("Enable sinkinig and/cmp into branches."));
91
Quentin Colombetc32615d2014-10-31 17:52:53 +000092static cl::opt<bool> DisableStoreExtract(
93 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
94 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
95
96static cl::opt<bool> StressStoreExtract(
97 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
98 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
99
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000100static cl::opt<bool> DisableExtLdPromotion(
101 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
103 "CodeGenPrepare"));
104
105static cl::opt<bool> StressExtLdPromotion(
106 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
107 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
108 "optimization in CodeGenPrepare"));
109
Eric Christopherc1ea1492008-09-24 05:32:41 +0000110namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000111typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000112struct TypeIsSExt {
113 Type *Ty;
114 bool IsSExt;
115 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
116};
117typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000118class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000119
Chris Lattner2dd09db2009-09-02 06:11:42 +0000120 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000121 /// TLI - Keep a pointer of a TargetLowering to consult for determining
122 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000123 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000124 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000125 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000126 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000127
Chris Lattner7a277142011-01-15 07:14:54 +0000128 /// CurInstIterator - As we scan instructions optimizing them, this is the
129 /// next instruction to optimize. Xforms that can invalidate this should
130 /// update it.
131 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000132
Evan Cheng0663f232011-03-21 01:19:09 +0000133 /// Keeps track of non-local addresses that have been sunk into a block.
134 /// This allows us to avoid inserting duplicate code for blocks with
135 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000136 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000137
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000138 /// Keeps track of all truncates inserted for the current function.
139 SetOfInstrs InsertedTruncsSet;
140 /// Keeps track of the type of the related instruction before their
141 /// promotion for the current function.
142 InstrToOrigTy PromotedInsts;
143
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000144 /// ModifiedDT - If CFG is modified in anyway.
Devang Patel8f606d72011-03-24 15:35:25 +0000145 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000146
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000147 /// OptSize - True if optimizing for size.
148 bool OptSize;
149
Chris Lattnerf2836d12007-03-31 04:06:36 +0000150 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000151 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000152 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Quentin Colombetc32615d2014-10-31 17:52:53 +0000153 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000154 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
155 }
Craig Topper4584cd52014-03-07 09:26:03 +0000156 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000157
Craig Topper4584cd52014-03-07 09:26:03 +0000158 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000159
Craig Topper4584cd52014-03-07 09:26:03 +0000160 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000161 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000162 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000163 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000164 }
165
Chris Lattnerf2836d12007-03-31 04:06:36 +0000166 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000167 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000168 bool EliminateMostlyEmptyBlocks(Function &F);
169 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
170 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000171 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
172 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
Chris Lattner229907c2011-07-18 04:54:35 +0000173 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000174 bool OptimizeInlineAsmInst(CallInst *CS);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000175 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000176 bool MoveExtToFormExtLoad(Instruction *&I);
Evan Chengd3d80172007-12-05 23:58:20 +0000177 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000178 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000179 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000180 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000181 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000182 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000183 bool sinkAndCmp(Function &F);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000184 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
185 Instruction *&Inst,
186 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000187 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000188 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000189 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000190 };
191}
Devang Patel09f162c2007-05-01 21:15:47 +0000192
Devang Patel8c78a0b2007-05-03 01:11:54 +0000193char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000194INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
195 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000196
Bill Wendling7a639ea2013-06-19 21:07:11 +0000197FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
198 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000199}
200
Chris Lattnerf2836d12007-03-31 04:06:36 +0000201bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000202 if (skipOptnoneFunction(F))
203 return false;
204
Chris Lattnerf2836d12007-03-31 04:06:36 +0000205 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000206 // Clear per function information.
207 InsertedTruncsSet.clear();
208 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000209
Devang Patel8f606d72011-03-24 15:35:25 +0000210 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000211 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000212 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000213 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000214 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000215 OptSize = F.hasFnAttribute(Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000216
Preston Gurdcdf540d2012-09-04 18:22:17 +0000217 /// This optimization identifies DIV instructions that can be
218 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000219 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000220 const DenseMap<unsigned int, unsigned int> &BypassWidths =
221 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000222 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000223 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000224 }
225
226 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000227 // unconditional branch.
228 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000229
Devang Patel53771ba2011-08-18 00:50:51 +0000230 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000231 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000232 // find a node corresponding to the value.
233 EverMadeChange |= PlaceDbgValues(F);
234
Tim Northovercea0abb2014-03-29 08:22:29 +0000235 // If there is a mask, compare against zero, and branch that can be combined
236 // into a single target instruction, push the mask and compare into branch
237 // users. Do this before OptimizeBlock -> OptimizeInst ->
238 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000239 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000240 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000241 EverMadeChange |= splitBranchCondition(F);
242 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000243
Chris Lattnerc3748562007-04-02 01:35:34 +0000244 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000245 while (MadeChange) {
246 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000247 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000248 BasicBlock *BB = I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000249 bool ModifiedDTOnIteration = false;
250 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000251
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000252 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000253 if (ModifiedDTOnIteration)
254 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000255 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000256 EverMadeChange |= MadeChange;
257 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000258
259 SunkAddrs.clear();
260
Cameron Zwarich338d3622011-03-11 21:52:04 +0000261 if (!DisableBranchOpts) {
262 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000263 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000264 for (BasicBlock &BB : F) {
265 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
266 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000267 if (!MadeChange) continue;
268
269 for (SmallVectorImpl<BasicBlock*>::iterator
270 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
271 if (pred_begin(*II) == pred_end(*II))
272 WorkList.insert(*II);
273 }
274
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000275 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000276 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000277 while (!WorkList.empty()) {
278 BasicBlock *BB = *WorkList.begin();
279 WorkList.erase(BB);
280 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
281
282 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000283
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000284 for (SmallVectorImpl<BasicBlock*>::iterator
285 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
286 if (pred_begin(*II) == pred_end(*II))
287 WorkList.insert(*II);
288 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000289
Nadav Rotem70409992012-08-14 05:19:07 +0000290 // Merge pairs of basic blocks with unconditional branches, connected by
291 // a single edge.
292 if (EverMadeChange || MadeChange)
293 MadeChange |= EliminateFallThrough(F);
294
Cameron Zwarich338d3622011-03-11 21:52:04 +0000295 EverMadeChange |= MadeChange;
296 }
297
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000298 if (!DisableGCOpts) {
299 SmallVector<Instruction *, 2> Statepoints;
300 for (BasicBlock &BB : F)
301 for (Instruction &I : BB)
302 if (isStatepoint(I))
303 Statepoints.push_back(&I);
304 for (auto &I : Statepoints)
305 EverMadeChange |= simplifyOffsetableRelocate(*I);
306 }
307
Chris Lattnerf2836d12007-03-31 04:06:36 +0000308 return EverMadeChange;
309}
310
Nadav Rotem70409992012-08-14 05:19:07 +0000311/// EliminateFallThrough - Merge basic blocks which are connected
312/// by a single edge, where one of the basic blocks has a single successor
313/// pointing to the other basic block, which has a single predecessor.
314bool CodeGenPrepare::EliminateFallThrough(Function &F) {
315 bool Changed = false;
316 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000317 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000318 BasicBlock *BB = I++;
319 // If the destination block has a single pred, then this is a trivial
320 // edge, just collapse it.
321 BasicBlock *SinglePred = BB->getSinglePredecessor();
322
Evan Cheng64a223a2012-09-28 23:58:57 +0000323 // Don't merge if BB's address is taken.
324 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000325
326 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
327 if (Term && !Term->isConditional()) {
328 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000329 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000330 // Remember if SinglePred was the entry block of the function.
331 // If so, we will need to move BB back to the entry position.
332 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000333 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000334
335 if (isEntry && BB != &BB->getParent()->getEntryBlock())
336 BB->moveBefore(&BB->getParent()->getEntryBlock());
337
338 // We have erased a block. Update the iterator.
339 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000340 }
341 }
342 return Changed;
343}
344
Dale Johannesen4026b042009-03-27 01:13:37 +0000345/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
346/// debug info directives, and an unconditional branch. Passes before isel
347/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
348/// isel. Start by eliminating these blocks so we can split them the way we
349/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000350bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
351 bool MadeChange = false;
352 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000353 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000354 BasicBlock *BB = I++;
355
356 // If this block doesn't end with an uncond branch, ignore it.
357 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
358 if (!BI || !BI->isUnconditional())
359 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000360
Dale Johannesen4026b042009-03-27 01:13:37 +0000361 // If the instruction before the branch (skipping debug info) isn't a phi
362 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000363 BasicBlock::iterator BBI = BI;
364 if (BBI != BB->begin()) {
365 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000366 while (isa<DbgInfoIntrinsic>(BBI)) {
367 if (BBI == BB->begin())
368 break;
369 --BBI;
370 }
371 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
372 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000373 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000374
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 // Do not break infinite loops.
376 BasicBlock *DestBB = BI->getSuccessor(0);
377 if (DestBB == BB)
378 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000379
Chris Lattnerc3748562007-04-02 01:35:34 +0000380 if (!CanMergeBlocks(BB, DestBB))
381 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000382
Chris Lattnerc3748562007-04-02 01:35:34 +0000383 EliminateMostlyEmptyBlock(BB);
384 MadeChange = true;
385 }
386 return MadeChange;
387}
388
389/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
390/// single uncond branch between them, and BB contains no other non-phi
391/// instructions.
392bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
393 const BasicBlock *DestBB) const {
394 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
395 // the successor. If there are more complex condition (e.g. preheaders),
396 // don't mess around with them.
397 BasicBlock::const_iterator BBI = BB->begin();
398 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000399 for (const User *U : PN->users()) {
400 const Instruction *UI = cast<Instruction>(U);
401 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000402 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000403 // If User is inside DestBB block and it is a PHINode then check
404 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000405 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000406 if (UI->getParent() == DestBB) {
407 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000408 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
409 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
410 if (Insn && Insn->getParent() == BB &&
411 Insn->getParent() != UPN->getIncomingBlock(I))
412 return false;
413 }
414 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000415 }
416 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000417
Chris Lattnerc3748562007-04-02 01:35:34 +0000418 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
419 // and DestBB may have conflicting incoming values for the block. If so, we
420 // can't merge the block.
421 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
422 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000423
Chris Lattnerc3748562007-04-02 01:35:34 +0000424 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000425 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
427 // It is faster to get preds from a PHI than with pred_iterator.
428 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
429 BBPreds.insert(BBPN->getIncomingBlock(i));
430 } else {
431 BBPreds.insert(pred_begin(BB), pred_end(BB));
432 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000433
Chris Lattnerc3748562007-04-02 01:35:34 +0000434 // Walk the preds of DestBB.
435 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
436 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
437 if (BBPreds.count(Pred)) { // Common predecessor?
438 BBI = DestBB->begin();
439 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
440 const Value *V1 = PN->getIncomingValueForBlock(Pred);
441 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442
Chris Lattnerc3748562007-04-02 01:35:34 +0000443 // If V2 is a phi node in BB, look up what the mapped value will be.
444 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
445 if (V2PN->getParent() == BB)
446 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000447
Chris Lattnerc3748562007-04-02 01:35:34 +0000448 // If there is a conflict, bail out.
449 if (V1 != V2) return false;
450 }
451 }
452 }
453
454 return true;
455}
456
457
458/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
459/// an unconditional branch in it.
460void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
461 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
462 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000463
David Greene74e2d492010-01-05 01:27:11 +0000464 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000465
Chris Lattnerc3748562007-04-02 01:35:34 +0000466 // If the destination block has a single pred, then this is a trivial edge,
467 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000468 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000469 if (SinglePred != DestBB) {
470 // Remember if SinglePred was the entry block of the function. If so, we
471 // will need to move BB back to the entry position.
472 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000473 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000474
Chris Lattner8a172da2008-11-28 19:54:49 +0000475 if (isEntry && BB != &BB->getParent()->getEntryBlock())
476 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000477
David Greene74e2d492010-01-05 01:27:11 +0000478 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000479 return;
480 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000481 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000482
Chris Lattnerc3748562007-04-02 01:35:34 +0000483 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
484 // to handle the new incoming edges it is about to have.
485 PHINode *PN;
486 for (BasicBlock::iterator BBI = DestBB->begin();
487 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
488 // Remove the incoming value for BB, and remember it.
489 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000490
Chris Lattnerc3748562007-04-02 01:35:34 +0000491 // Two options: either the InVal is a phi node defined in BB or it is some
492 // value that dominates BB.
493 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
494 if (InValPhi && InValPhi->getParent() == BB) {
495 // Add all of the input values of the input PHI as inputs of this phi.
496 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
497 PN->addIncoming(InValPhi->getIncomingValue(i),
498 InValPhi->getIncomingBlock(i));
499 } else {
500 // Otherwise, add one instance of the dominating value for each edge that
501 // we will be adding.
502 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
503 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
504 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
505 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000506 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
507 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000508 }
509 }
510 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000511
Chris Lattnerc3748562007-04-02 01:35:34 +0000512 // The PHIs are now updated, change everything that refers to BB to use
513 // DestBB and remove BB.
514 BB->replaceAllUsesWith(DestBB);
515 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000516 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000517
David Greene74e2d492010-01-05 01:27:11 +0000518 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000519}
520
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000521// Computes a map of base pointer relocation instructions to corresponding
522// derived pointer relocation instructions given a vector of all relocate calls
523static void computeBaseDerivedRelocateMap(
524 const SmallVectorImpl<User *> &AllRelocateCalls,
525 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
526 RelocateInstMap) {
527 // Collect information in two maps: one primarily for locating the base object
528 // while filling the second map; the second map is the final structure holding
529 // a mapping between Base and corresponding Derived relocate calls
530 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
531 for (auto &U : AllRelocateCalls) {
532 GCRelocateOperands ThisRelocate(U);
533 IntrinsicInst *I = cast<IntrinsicInst>(U);
Sanjoy Das499d7032015-05-06 02:36:26 +0000534 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
535 ThisRelocate.getDerivedPtrIndex());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000536 RelocateIdxMap.insert(std::make_pair(K, I));
537 }
538 for (auto &Item : RelocateIdxMap) {
539 std::pair<unsigned, unsigned> Key = Item.first;
540 if (Key.first == Key.second)
541 // Base relocation: nothing to insert
542 continue;
543
544 IntrinsicInst *I = Item.second;
545 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000546
547 // We're iterating over RelocateIdxMap so we cannot modify it.
548 auto MaybeBase = RelocateIdxMap.find(BaseKey);
549 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000550 // TODO: We might want to insert a new base object relocate and gep off
551 // that, if there are enough derived object relocates.
552 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000553
554 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000555 }
556}
557
558// Accepts a GEP and extracts the operands into a vector provided they're all
559// small integer constants
560static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
561 SmallVectorImpl<Value *> &OffsetV) {
562 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
563 // Only accept small constant integer operands
564 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
565 if (!Op || Op->getZExtValue() > 20)
566 return false;
567 }
568
569 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
570 OffsetV.push_back(GEP->getOperand(i));
571 return true;
572}
573
574// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
575// replace, computes a replacement, and affects it.
576static bool
577simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
578 const SmallVectorImpl<IntrinsicInst *> &Targets) {
579 bool MadeChange = false;
580 for (auto &ToReplace : Targets) {
581 GCRelocateOperands MasterRelocate(RelocatedBase);
582 GCRelocateOperands ThisRelocate(ToReplace);
583
Sanjoy Das499d7032015-05-06 02:36:26 +0000584 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000585 "Not relocating a derived object of the original base object");
Sanjoy Das499d7032015-05-06 02:36:26 +0000586 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000587 // A duplicate relocate call. TODO: coalesce duplicates.
588 continue;
589 }
590
Sanjoy Das499d7032015-05-06 02:36:26 +0000591 Value *Base = ThisRelocate.getBasePtr();
592 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000593 if (!Derived || Derived->getPointerOperand() != Base)
594 continue;
595
596 SmallVector<Value *, 2> OffsetV;
597 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
598 continue;
599
600 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000601 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
602
603 // Insert after RelocatedBase
604 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000605 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000606
607 // If gc_relocate does not match the actual type, cast it to the right type.
608 // In theory, there must be a bitcast after gc_relocate if the type does not
609 // match, and we should reuse it to get the derived pointer. But it could be
610 // cases like this:
611 // bb1:
612 // ...
613 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
614 // br label %merge
615 //
616 // bb2:
617 // ...
618 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
619 // br label %merge
620 //
621 // merge:
622 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
623 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
624 //
625 // In this case, we can not find the bitcast any more. So we insert a new bitcast
626 // no matter there is already one or not. In this way, we can handle all cases, and
627 // the extra bitcast should be optimized away in later passes.
628 Instruction *ActualRelocatedBase = RelocatedBase;
629 if (RelocatedBase->getType() != Base->getType()) {
630 ActualRelocatedBase =
631 cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000632 }
David Blaikie68d535c2015-03-24 22:38:16 +0000633 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000634 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000635 Instruction *ReplacementInst = cast<Instruction>(Replacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000636 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000637 // If the newly generated derived pointer's type does not match the original derived
638 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
639 Instruction *ActualReplacement = ReplacementInst;
640 if (ReplacementInst->getType() != ToReplace->getType()) {
641 ActualReplacement =
642 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000643 }
644 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000645 ToReplace->eraseFromParent();
646
647 MadeChange = true;
648 }
649 return MadeChange;
650}
651
652// Turns this:
653//
654// %base = ...
655// %ptr = gep %base + 15
656// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
657// %base' = relocate(%tok, i32 4, i32 4)
658// %ptr' = relocate(%tok, i32 4, i32 5)
659// %val = load %ptr'
660//
661// into this:
662//
663// %base = ...
664// %ptr = gep %base + 15
665// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
666// %base' = gc.relocate(%tok, i32 4, i32 4)
667// %ptr' = gep %base' + 15
668// %val = load %ptr'
669bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
670 bool MadeChange = false;
671 SmallVector<User *, 2> AllRelocateCalls;
672
673 for (auto *U : I.users())
674 if (isGCRelocate(dyn_cast<Instruction>(U)))
675 // Collect all the relocate calls associated with a statepoint
676 AllRelocateCalls.push_back(U);
677
678 // We need atleast one base pointer relocation + one derived pointer
679 // relocation to mangle
680 if (AllRelocateCalls.size() < 2)
681 return false;
682
683 // RelocateInstMap is a mapping from the base relocate instruction to the
684 // corresponding derived relocate instructions
685 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
686 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
687 if (RelocateInstMap.empty())
688 return false;
689
690 for (auto &Item : RelocateInstMap)
691 // Item.first is the RelocatedBase to offset against
692 // Item.second is the vector of Targets to replace
693 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
694 return MadeChange;
695}
696
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000697/// SinkCast - Sink the specified cast instruction into its user blocks
698static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000699 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000700
Chris Lattnerf2836d12007-03-31 04:06:36 +0000701 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000702 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000703
Chris Lattnerf2836d12007-03-31 04:06:36 +0000704 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000705 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000706 UI != E; ) {
707 Use &TheUse = UI.getUse();
708 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000709
Chris Lattnerf2836d12007-03-31 04:06:36 +0000710 // Figure out which BB this cast is used in. For PHI's this is the
711 // appropriate predecessor block.
712 BasicBlock *UserBB = User->getParent();
713 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000714 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000715 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000716
Chris Lattnerf2836d12007-03-31 04:06:36 +0000717 // Preincrement use iterator so we don't invalidate it.
718 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000719
Chris Lattnerf2836d12007-03-31 04:06:36 +0000720 // If this user is in the same block as the cast, don't change the cast.
721 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000722
Chris Lattnerf2836d12007-03-31 04:06:36 +0000723 // If we have already inserted a cast into this block, use it.
724 CastInst *&InsertedCast = InsertedCasts[UserBB];
725
726 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000727 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000728 InsertedCast =
729 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000730 InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000731 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000732
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000733 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000734 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000735 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000736 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000737 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000738
Chris Lattnerf2836d12007-03-31 04:06:36 +0000739 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000740 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000741 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000742 MadeChange = true;
743 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000744
Chris Lattnerf2836d12007-03-31 04:06:36 +0000745 return MadeChange;
746}
747
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000748/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
749/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
750/// sink it into user blocks to reduce the number of virtual
751/// registers that must be created and coalesced.
752///
753/// Return true if any changes are made.
754///
755static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
756 // If this is a noop copy,
757 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
758 EVT DstVT = TLI.getValueType(CI->getType());
759
760 // This is an fp<->int conversion?
761 if (SrcVT.isInteger() != DstVT.isInteger())
762 return false;
763
764 // If this is an extension, it will be a zero or sign extension, which
765 // isn't a noop.
766 if (SrcVT.bitsLT(DstVT)) return false;
767
768 // If these values will be promoted, find out what they will be promoted
769 // to. This helps us consider truncates on PPC as noop copies when they
770 // are.
771 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
772 TargetLowering::TypePromoteInteger)
773 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
774 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
775 TargetLowering::TypePromoteInteger)
776 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
777
778 // If, after promotion, these are the same types, this is a noop copy.
779 if (SrcVT != DstVT)
780 return false;
781
782 return SinkCast(CI);
783}
784
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000785/// CombineUAddWithOverflow - try to combine CI into a call to the
786/// llvm.uadd.with.overflow intrinsic if possible.
787///
788/// Return true if any changes were made.
789static bool CombineUAddWithOverflow(CmpInst *CI) {
790 Value *A, *B;
791 Instruction *AddI;
792 if (!match(CI,
793 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
794 return false;
795
796 Type *Ty = AddI->getType();
797 if (!isa<IntegerType>(Ty))
798 return false;
799
800 // We don't want to move around uses of condition values this late, so we we
801 // check if it is legal to create the call to the intrinsic in the basic
802 // block containing the icmp:
803
804 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
805 return false;
806
807#ifndef NDEBUG
808 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
809 // for now:
810 if (AddI->hasOneUse())
811 assert(*AddI->user_begin() == CI && "expected!");
812#endif
813
814 Module *M = CI->getParent()->getParent()->getParent();
815 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
816
817 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
818
819 auto *UAddWithOverflow =
820 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
821 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
822 auto *Overflow =
823 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
824
825 CI->replaceAllUsesWith(Overflow);
826 AddI->replaceAllUsesWith(UAdd);
827 CI->eraseFromParent();
828 AddI->eraseFromParent();
829 return true;
830}
831
832/// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000833/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000834/// a clear win except on targets with multiple condition code registers
835/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000836///
837/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000838static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000839 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000840
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000841 /// InsertedCmp - Only insert a cmp in each block once.
842 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000843
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000844 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000845 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000846 UI != E; ) {
847 Use &TheUse = UI.getUse();
848 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000849
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000850 // Preincrement use iterator so we don't invalidate it.
851 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000852
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000853 // Don't bother for PHI nodes.
854 if (isa<PHINode>(User))
855 continue;
856
857 // Figure out which BB this cmp is used in.
858 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000859
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000860 // If this user is in the same block as the cmp, don't change the cmp.
861 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000862
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000863 // If we have already inserted a cmp into this block, use it.
864 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
865
866 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000867 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000868 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000869 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000870 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000871 CI->getOperand(1), "", InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000872 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000873
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000874 // Replace a use of the cmp with a use of the new cmp.
875 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000876 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000877 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000878 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000879
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000880 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000881 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000882 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000883 MadeChange = true;
884 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000885
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000886 return MadeChange;
887}
888
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000889static bool OptimizeCmpExpression(CmpInst *CI) {
890 if (SinkCmpExpression(CI))
891 return true;
892
893 if (CombineUAddWithOverflow(CI))
894 return true;
895
896 return false;
897}
898
Yi Jiangd069f632014-04-21 19:34:27 +0000899/// isExtractBitsCandidateUse - Check if the candidates could
900/// be combined with shift instruction, which includes:
901/// 1. Truncate instruction
902/// 2. And instruction and the imm is a mask of the low bits:
903/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000904static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000905 if (!isa<TruncInst>(User)) {
906 if (User->getOpcode() != Instruction::And ||
907 !isa<ConstantInt>(User->getOperand(1)))
908 return false;
909
Quentin Colombetd4f44692014-04-22 01:20:34 +0000910 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000911
Quentin Colombetd4f44692014-04-22 01:20:34 +0000912 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000913 return false;
914 }
915 return true;
916}
917
918/// SinkShiftAndTruncate - sink both shift and truncate instruction
919/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000920static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000921SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
922 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
923 const TargetLowering &TLI) {
924 BasicBlock *UserBB = User->getParent();
925 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
926 TruncInst *TruncI = dyn_cast<TruncInst>(User);
927 bool MadeChange = false;
928
929 for (Value::user_iterator TruncUI = TruncI->user_begin(),
930 TruncE = TruncI->user_end();
931 TruncUI != TruncE;) {
932
933 Use &TruncTheUse = TruncUI.getUse();
934 Instruction *TruncUser = cast<Instruction>(*TruncUI);
935 // Preincrement use iterator so we don't invalidate it.
936
937 ++TruncUI;
938
939 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
940 if (!ISDOpcode)
941 continue;
942
Tim Northovere2239ff2014-07-29 10:20:22 +0000943 // If the use is actually a legal node, there will not be an
944 // implicit truncate.
945 // FIXME: always querying the result type is just an
946 // approximation; some nodes' legality is determined by the
947 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000948 if (TLI.isOperationLegalOrCustom(
949 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000950 continue;
951
952 // Don't bother for PHI nodes.
953 if (isa<PHINode>(TruncUser))
954 continue;
955
956 BasicBlock *TruncUserBB = TruncUser->getParent();
957
958 if (UserBB == TruncUserBB)
959 continue;
960
961 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
962 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
963
964 if (!InsertedShift && !InsertedTrunc) {
965 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
966 // Sink the shift
967 if (ShiftI->getOpcode() == Instruction::AShr)
968 InsertedShift =
969 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
970 else
971 InsertedShift =
972 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
973
974 // Sink the trunc
975 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
976 TruncInsertPt++;
977
978 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
979 TruncI->getType(), "", TruncInsertPt);
980
981 MadeChange = true;
982
983 TruncTheUse = InsertedTrunc;
984 }
985 }
986 return MadeChange;
987}
988
989/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
990/// the uses could potentially be combined with this shift instruction and
991/// generate BitExtract instruction. It will only be applied if the architecture
992/// supports BitExtract instruction. Here is an example:
993/// BB1:
994/// %x.extract.shift = lshr i64 %arg1, 32
995/// BB2:
996/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
997/// ==>
998///
999/// BB2:
1000/// %x.extract.shift.1 = lshr i64 %arg1, 32
1001/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1002///
1003/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1004/// instruction.
1005/// Return true if any changes are made.
1006static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1007 const TargetLowering &TLI) {
1008 BasicBlock *DefBB = ShiftI->getParent();
1009
1010 /// Only insert instructions in each block once.
1011 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1012
1013 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
1014
1015 bool MadeChange = false;
1016 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1017 UI != E;) {
1018 Use &TheUse = UI.getUse();
1019 Instruction *User = cast<Instruction>(*UI);
1020 // Preincrement use iterator so we don't invalidate it.
1021 ++UI;
1022
1023 // Don't bother for PHI nodes.
1024 if (isa<PHINode>(User))
1025 continue;
1026
1027 if (!isExtractBitsCandidateUse(User))
1028 continue;
1029
1030 BasicBlock *UserBB = User->getParent();
1031
1032 if (UserBB == DefBB) {
1033 // If the shift and truncate instruction are in the same BB. The use of
1034 // the truncate(TruncUse) may still introduce another truncate if not
1035 // legal. In this case, we would like to sink both shift and truncate
1036 // instruction to the BB of TruncUse.
1037 // for example:
1038 // BB1:
1039 // i64 shift.result = lshr i64 opnd, imm
1040 // trunc.result = trunc shift.result to i16
1041 //
1042 // BB2:
1043 // ----> We will have an implicit truncate here if the architecture does
1044 // not have i16 compare.
1045 // cmp i16 trunc.result, opnd2
1046 //
1047 if (isa<TruncInst>(User) && shiftIsLegal
1048 // If the type of the truncate is legal, no trucate will be
1049 // introduced in other basic blocks.
1050 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
1051 MadeChange =
1052 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
1053
1054 continue;
1055 }
1056 // If we have already inserted a shift into this block, use it.
1057 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1058
1059 if (!InsertedShift) {
1060 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1061
1062 if (ShiftI->getOpcode() == Instruction::AShr)
1063 InsertedShift =
1064 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
1065 else
1066 InsertedShift =
1067 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
1068
1069 MadeChange = true;
1070 }
1071
1072 // Replace a use of the shift with a use of the new shift.
1073 TheUse = InsertedShift;
1074 }
1075
1076 // If we removed all uses, nuke the shift.
1077 if (ShiftI->use_empty())
1078 ShiftI->eraseFromParent();
1079
1080 return MadeChange;
1081}
1082
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001083// ScalarizeMaskedLoad() translates masked load intrinsic, like
1084// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1085// <16 x i1> %mask, <16 x i32> %passthru)
1086// to a chain of basic blocks, whith loading element one-by-one if
1087// the appropriate mask bit is set
1088//
1089// %1 = bitcast i8* %addr to i32*
1090// %2 = extractelement <16 x i1> %mask, i32 0
1091// %3 = icmp eq i1 %2, true
1092// br i1 %3, label %cond.load, label %else
1093//
1094//cond.load: ; preds = %0
1095// %4 = getelementptr i32* %1, i32 0
1096// %5 = load i32* %4
1097// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1098// br label %else
1099//
1100//else: ; preds = %0, %cond.load
1101// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1102// %7 = extractelement <16 x i1> %mask, i32 1
1103// %8 = icmp eq i1 %7, true
1104// br i1 %8, label %cond.load1, label %else2
1105//
1106//cond.load1: ; preds = %else
1107// %9 = getelementptr i32* %1, i32 1
1108// %10 = load i32* %9
1109// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1110// br label %else2
1111//
1112//else2: ; preds = %else, %cond.load1
1113// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1114// %12 = extractelement <16 x i1> %mask, i32 2
1115// %13 = icmp eq i1 %12, true
1116// br i1 %13, label %cond.load4, label %else5
1117//
1118static void ScalarizeMaskedLoad(CallInst *CI) {
1119 Value *Ptr = CI->getArgOperand(0);
1120 Value *Src0 = CI->getArgOperand(3);
1121 Value *Mask = CI->getArgOperand(2);
1122 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1123 Type *EltTy = VecType->getElementType();
1124
1125 assert(VecType && "Unexpected return type of masked load intrinsic");
1126
1127 IRBuilder<> Builder(CI->getContext());
1128 Instruction *InsertPt = CI;
1129 BasicBlock *IfBlock = CI->getParent();
1130 BasicBlock *CondBlock = nullptr;
1131 BasicBlock *PrevIfBlock = CI->getParent();
1132 Builder.SetInsertPoint(InsertPt);
1133
1134 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1135
1136 // Bitcast %addr fron i8* to EltTy*
1137 Type *NewPtrType =
1138 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1139 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1140 Value *UndefVal = UndefValue::get(VecType);
1141
1142 // The result vector
1143 Value *VResult = UndefVal;
1144
1145 PHINode *Phi = nullptr;
1146 Value *PrevPhi = UndefVal;
1147
1148 unsigned VectorWidth = VecType->getNumElements();
1149 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1150
1151 // Fill the "else" block, created in the previous iteration
1152 //
1153 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1154 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1155 // %to_load = icmp eq i1 %mask_1, true
1156 // br i1 %to_load, label %cond.load, label %else
1157 //
1158 if (Idx > 0) {
1159 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1160 Phi->addIncoming(VResult, CondBlock);
1161 Phi->addIncoming(PrevPhi, PrevIfBlock);
1162 PrevPhi = Phi;
1163 VResult = Phi;
1164 }
1165
1166 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1167 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1168 ConstantInt::get(Predicate->getType(), 1));
1169
1170 // Create "cond" block
1171 //
1172 // %EltAddr = getelementptr i32* %1, i32 0
1173 // %Elt = load i32* %EltAddr
1174 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1175 //
1176 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1177 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001178
1179 Value *Gep =
1180 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001181 LoadInst* Load = Builder.CreateLoad(Gep, false);
1182 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1183
1184 // Create "else" block, fill it in the next iteration
1185 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1186 Builder.SetInsertPoint(InsertPt);
1187 Instruction *OldBr = IfBlock->getTerminator();
1188 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1189 OldBr->eraseFromParent();
1190 PrevIfBlock = IfBlock;
1191 IfBlock = NewIfBlock;
1192 }
1193
1194 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1195 Phi->addIncoming(VResult, CondBlock);
1196 Phi->addIncoming(PrevPhi, PrevIfBlock);
1197 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1198 CI->replaceAllUsesWith(NewI);
1199 CI->eraseFromParent();
1200}
1201
1202// ScalarizeMaskedStore() translates masked store intrinsic, like
1203// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1204// <16 x i1> %mask)
1205// to a chain of basic blocks, that stores element one-by-one if
1206// the appropriate mask bit is set
1207//
1208// %1 = bitcast i8* %addr to i32*
1209// %2 = extractelement <16 x i1> %mask, i32 0
1210// %3 = icmp eq i1 %2, true
1211// br i1 %3, label %cond.store, label %else
1212//
1213// cond.store: ; preds = %0
1214// %4 = extractelement <16 x i32> %val, i32 0
1215// %5 = getelementptr i32* %1, i32 0
1216// store i32 %4, i32* %5
1217// br label %else
1218//
1219// else: ; preds = %0, %cond.store
1220// %6 = extractelement <16 x i1> %mask, i32 1
1221// %7 = icmp eq i1 %6, true
1222// br i1 %7, label %cond.store1, label %else2
1223//
1224// cond.store1: ; preds = %else
1225// %8 = extractelement <16 x i32> %val, i32 1
1226// %9 = getelementptr i32* %1, i32 1
1227// store i32 %8, i32* %9
1228// br label %else2
1229// . . .
1230static void ScalarizeMaskedStore(CallInst *CI) {
1231 Value *Ptr = CI->getArgOperand(1);
1232 Value *Src = CI->getArgOperand(0);
1233 Value *Mask = CI->getArgOperand(3);
1234
1235 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1236 Type *EltTy = VecType->getElementType();
1237
1238 assert(VecType && "Unexpected data type in masked store intrinsic");
1239
1240 IRBuilder<> Builder(CI->getContext());
1241 Instruction *InsertPt = CI;
1242 BasicBlock *IfBlock = CI->getParent();
1243 Builder.SetInsertPoint(InsertPt);
1244 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1245
1246 // Bitcast %addr fron i8* to EltTy*
1247 Type *NewPtrType =
1248 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1249 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1250
1251 unsigned VectorWidth = VecType->getNumElements();
1252 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1253
1254 // Fill the "else" block, created in the previous iteration
1255 //
1256 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1257 // %to_store = icmp eq i1 %mask_1, true
1258 // br i1 %to_load, label %cond.store, label %else
1259 //
1260 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1261 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1262 ConstantInt::get(Predicate->getType(), 1));
1263
1264 // Create "cond" block
1265 //
1266 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1267 // %EltAddr = getelementptr i32* %1, i32 0
1268 // %store i32 %OneElt, i32* %EltAddr
1269 //
1270 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1271 Builder.SetInsertPoint(InsertPt);
1272
1273 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001274 Value *Gep =
1275 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001276 Builder.CreateStore(OneElt, Gep);
1277
1278 // Create "else" block, fill it in the next iteration
1279 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1280 Builder.SetInsertPoint(InsertPt);
1281 Instruction *OldBr = IfBlock->getTerminator();
1282 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1283 OldBr->eraseFromParent();
1284 IfBlock = NewIfBlock;
1285 }
1286 CI->eraseFromParent();
1287}
1288
1289bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001290 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001291
Chris Lattner7a277142011-01-15 07:14:54 +00001292 // Lower inline assembly if we can.
1293 // If we found an inline asm expession, and if the target knows how to
1294 // lower it to normal LLVM code, do so now.
1295 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1296 if (TLI->ExpandInlineAsm(CI)) {
1297 // Avoid invalidating the iterator.
1298 CurInstIterator = BB->begin();
1299 // Avoid processing instructions out of order, which could cause
1300 // reuse before a value is defined.
1301 SunkAddrs.clear();
1302 return true;
1303 }
1304 // Sink address computing for memory operands into the block.
1305 if (OptimizeInlineAsmInst(CI))
1306 return true;
1307 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001308
John Brawn0dbcd652015-03-18 12:01:59 +00001309 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
1310
1311 // Align the pointer arguments to this call if the target thinks it's a good
1312 // idea
1313 unsigned MinSize, PrefAlign;
1314 if (TLI && TD && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1315 for (auto &Arg : CI->arg_operands()) {
1316 // We want to align both objects whose address is used directly and
1317 // objects whose address is used in casts and GEPs, though it only makes
1318 // sense for GEPs if the offset is a multiple of the desired alignment and
1319 // if size - offset meets the size threshold.
1320 if (!Arg->getType()->isPointerTy())
1321 continue;
1322 APInt Offset(TD->getPointerSizeInBits(
1323 cast<PointerType>(Arg->getType())->getAddressSpace()), 0);
1324 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*TD, Offset);
1325 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001326 if ((Offset2 & (PrefAlign-1)) != 0)
1327 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001328 AllocaInst *AI;
John Brawne8fd6c82015-04-13 10:47:39 +00001329 if ((AI = dyn_cast<AllocaInst>(Val)) &&
John Brawn0dbcd652015-03-18 12:01:59 +00001330 AI->getAlignment() < PrefAlign &&
1331 TD->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
1332 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001333 // Global variables can only be aligned if they are defined in this
1334 // object (i.e. they are uniquely initialized in this object), and
1335 // over-aligning global variables that have an explicit section is
1336 // forbidden.
1337 GlobalVariable *GV;
1338 if ((GV = dyn_cast<GlobalVariable>(Val)) &&
1339 GV->hasUniqueInitializer() &&
1340 !GV->hasSection() &&
1341 GV->getAlignment() < PrefAlign &&
1342 TD->getTypeAllocSize(
1343 GV->getType()->getElementType()) >= MinSize + Offset2)
1344 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001345 }
1346 // If this is a memcpy (or similar) then we may be able to improve the
1347 // alignment
1348 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
1349 unsigned Align = getKnownAlignment(MI->getDest(), *TD);
1350 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
1351 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *TD));
1352 if (Align > MI->getAlignment())
1353 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1354 }
1355 }
1356
Eric Christopher4b7948e2010-03-11 02:41:03 +00001357 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001358 if (II) {
1359 switch (II->getIntrinsicID()) {
1360 default: break;
1361 case Intrinsic::objectsize: {
1362 // Lower all uses of llvm.objectsize.*
1363 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1364 Type *ReturnTy = CI->getType();
1365 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001366
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001367 // Substituting this can cause recursive simplifications, which can
1368 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1369 // happens.
1370 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001371
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001372 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001373 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001374
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001375 // If the iterator instruction was recursively deleted, start over at the
1376 // start of the block.
1377 if (IterHandle != CurInstIterator) {
1378 CurInstIterator = BB->begin();
1379 SunkAddrs.clear();
1380 }
1381 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001382 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001383 case Intrinsic::masked_load: {
1384 // Scalarize unsupported vector masked load
1385 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1386 ScalarizeMaskedLoad(CI);
1387 ModifiedDT = true;
1388 return true;
1389 }
1390 return false;
1391 }
1392 case Intrinsic::masked_store: {
1393 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1394 ScalarizeMaskedStore(CI);
1395 ModifiedDT = true;
1396 return true;
1397 }
1398 return false;
1399 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001400 case Intrinsic::aarch64_stlxr:
1401 case Intrinsic::aarch64_stxr: {
1402 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1403 if (!ExtVal || !ExtVal->hasOneUse() ||
1404 ExtVal->getParent() == CI->getParent())
1405 return false;
1406 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1407 ExtVal->moveBefore(CI);
1408 return true;
1409 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001410 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001411
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001412 if (TLI) {
1413 SmallVector<Value*, 2> PtrOps;
1414 Type *AccessTy;
1415 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
1416 while (!PtrOps.empty())
1417 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
1418 return true;
1419 }
Pete Cooper615fd892012-03-13 20:59:56 +00001420 }
1421
Eric Christopher4b7948e2010-03-11 02:41:03 +00001422 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001423 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001424
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001425 // Lower all default uses of _chk calls. This is very similar
1426 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001427 // to fortified library functions (e.g. __memcpy_chk) that have the default
1428 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001429 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001430 if (Value *V = Simplifier.optimizeCall(CI)) {
1431 CI->replaceAllUsesWith(V);
1432 CI->eraseFromParent();
1433 return true;
1434 }
1435 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001436}
Chris Lattner1b93be52011-01-15 07:25:29 +00001437
Evan Cheng0663f232011-03-21 01:19:09 +00001438/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1439/// instructions to the predecessor to enable tail call optimizations. The
1440/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001441/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001442/// bb0:
1443/// %tmp0 = tail call i32 @f0()
1444/// br label %return
1445/// bb1:
1446/// %tmp1 = tail call i32 @f1()
1447/// br label %return
1448/// bb2:
1449/// %tmp2 = tail call i32 @f2()
1450/// br label %return
1451/// return:
1452/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1453/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001454/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001455///
1456/// =>
1457///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001458/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001459/// bb0:
1460/// %tmp0 = tail call i32 @f0()
1461/// ret i32 %tmp0
1462/// bb1:
1463/// %tmp1 = tail call i32 @f1()
1464/// ret i32 %tmp1
1465/// bb2:
1466/// %tmp2 = tail call i32 @f2()
1467/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001468/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +00001469bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001470 if (!TLI)
1471 return false;
1472
Benjamin Kramer455fa352012-11-23 19:17:06 +00001473 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1474 if (!RI)
1475 return false;
1476
Craig Topperc0196b12014-04-14 00:51:57 +00001477 PHINode *PN = nullptr;
1478 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001479 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001480 if (V) {
1481 BCI = dyn_cast<BitCastInst>(V);
1482 if (BCI)
1483 V = BCI->getOperand(0);
1484
1485 PN = dyn_cast<PHINode>(V);
1486 if (!PN)
1487 return false;
1488 }
Evan Cheng0663f232011-03-21 01:19:09 +00001489
Cameron Zwarich4649f172011-03-24 04:52:10 +00001490 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001491 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001492
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001493 // It's not safe to eliminate the sign / zero extension of the return value.
1494 // See llvm::isInTailCallPosition().
1495 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001496 AttributeSet CallerAttrs = F->getAttributes();
1497 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1498 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001499 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001500
Cameron Zwarich4649f172011-03-24 04:52:10 +00001501 // Make sure there are no instructions between the PHI and return, or that the
1502 // return is the first instruction in the block.
1503 if (PN) {
1504 BasicBlock::iterator BI = BB->begin();
1505 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001506 if (&*BI == BCI)
1507 // Also skip over the bitcast.
1508 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001509 if (&*BI != RI)
1510 return false;
1511 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001512 BasicBlock::iterator BI = BB->begin();
1513 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1514 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001515 return false;
1516 }
Evan Cheng0663f232011-03-21 01:19:09 +00001517
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001518 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1519 /// call.
1520 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001521 if (PN) {
1522 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1523 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1524 // Make sure the phi value is indeed produced by the tail call.
1525 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1526 TLI->mayBeEmittedAsTailCall(CI))
1527 TailCalls.push_back(CI);
1528 }
1529 } else {
1530 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001531 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001532 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001533 continue;
1534
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001535 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001536 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1537 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001538 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1539 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001540 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001541
Cameron Zwarich4649f172011-03-24 04:52:10 +00001542 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001543 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001544 TailCalls.push_back(CI);
1545 }
Evan Cheng0663f232011-03-21 01:19:09 +00001546 }
1547
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001548 bool Changed = false;
1549 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1550 CallInst *CI = TailCalls[i];
1551 CallSite CS(CI);
1552
1553 // Conservatively require the attributes of the call to match those of the
1554 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001555 AttributeSet CalleeAttrs = CS.getAttributes();
1556 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001557 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001558 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001559 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001560 continue;
1561
1562 // Make sure the call instruction is followed by an unconditional branch to
1563 // the return block.
1564 BasicBlock *CallBB = CI->getParent();
1565 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1566 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1567 continue;
1568
1569 // Duplicate the return into CallBB.
1570 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001571 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001572 ++NumRetsDup;
1573 }
1574
1575 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001576 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001577 BB->eraseFromParent();
1578
1579 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001580}
1581
Chris Lattner728f9022008-11-25 07:09:13 +00001582//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001583// Memory Optimization
1584//===----------------------------------------------------------------------===//
1585
Chandler Carruthc8925912013-01-05 02:09:22 +00001586namespace {
1587
1588/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1589/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001590struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001591 Value *BaseReg;
1592 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001593 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001594 void print(raw_ostream &OS) const;
1595 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001596
Chandler Carruthc8925912013-01-05 02:09:22 +00001597 bool operator==(const ExtAddrMode& O) const {
1598 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1599 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1600 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1601 }
1602};
1603
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001604#ifndef NDEBUG
1605static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1606 AM.print(OS);
1607 return OS;
1608}
1609#endif
1610
Chandler Carruthc8925912013-01-05 02:09:22 +00001611void ExtAddrMode::print(raw_ostream &OS) const {
1612 bool NeedPlus = false;
1613 OS << "[";
1614 if (BaseGV) {
1615 OS << (NeedPlus ? " + " : "")
1616 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001617 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001618 NeedPlus = true;
1619 }
1620
Richard Trieuc0f91212014-05-30 03:15:17 +00001621 if (BaseOffs) {
1622 OS << (NeedPlus ? " + " : "")
1623 << BaseOffs;
1624 NeedPlus = true;
1625 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001626
1627 if (BaseReg) {
1628 OS << (NeedPlus ? " + " : "")
1629 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001630 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001631 NeedPlus = true;
1632 }
1633 if (Scale) {
1634 OS << (NeedPlus ? " + " : "")
1635 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001636 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001637 }
1638
1639 OS << ']';
1640}
1641
1642#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1643void ExtAddrMode::dump() const {
1644 print(dbgs());
1645 dbgs() << '\n';
1646}
1647#endif
1648
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001649/// \brief This class provides transaction based operation on the IR.
1650/// Every change made through this class is recorded in the internal state and
1651/// can be undone (rollback) until commit is called.
1652class TypePromotionTransaction {
1653
1654 /// \brief This represents the common interface of the individual transaction.
1655 /// Each class implements the logic for doing one specific modification on
1656 /// the IR via the TypePromotionTransaction.
1657 class TypePromotionAction {
1658 protected:
1659 /// The Instruction modified.
1660 Instruction *Inst;
1661
1662 public:
1663 /// \brief Constructor of the action.
1664 /// The constructor performs the related action on the IR.
1665 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1666
1667 virtual ~TypePromotionAction() {}
1668
1669 /// \brief Undo the modification done by this action.
1670 /// When this method is called, the IR must be in the same state as it was
1671 /// before this action was applied.
1672 /// \pre Undoing the action works if and only if the IR is in the exact same
1673 /// state as it was directly after this action was applied.
1674 virtual void undo() = 0;
1675
1676 /// \brief Advocate every change made by this action.
1677 /// When the results on the IR of the action are to be kept, it is important
1678 /// to call this function, otherwise hidden information may be kept forever.
1679 virtual void commit() {
1680 // Nothing to be done, this action is not doing anything.
1681 }
1682 };
1683
1684 /// \brief Utility to remember the position of an instruction.
1685 class InsertionHandler {
1686 /// Position of an instruction.
1687 /// Either an instruction:
1688 /// - Is the first in a basic block: BB is used.
1689 /// - Has a previous instructon: PrevInst is used.
1690 union {
1691 Instruction *PrevInst;
1692 BasicBlock *BB;
1693 } Point;
1694 /// Remember whether or not the instruction had a previous instruction.
1695 bool HasPrevInstruction;
1696
1697 public:
1698 /// \brief Record the position of \p Inst.
1699 InsertionHandler(Instruction *Inst) {
1700 BasicBlock::iterator It = Inst;
1701 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1702 if (HasPrevInstruction)
1703 Point.PrevInst = --It;
1704 else
1705 Point.BB = Inst->getParent();
1706 }
1707
1708 /// \brief Insert \p Inst at the recorded position.
1709 void insert(Instruction *Inst) {
1710 if (HasPrevInstruction) {
1711 if (Inst->getParent())
1712 Inst->removeFromParent();
1713 Inst->insertAfter(Point.PrevInst);
1714 } else {
1715 Instruction *Position = Point.BB->getFirstInsertionPt();
1716 if (Inst->getParent())
1717 Inst->moveBefore(Position);
1718 else
1719 Inst->insertBefore(Position);
1720 }
1721 }
1722 };
1723
1724 /// \brief Move an instruction before another.
1725 class InstructionMoveBefore : public TypePromotionAction {
1726 /// Original position of the instruction.
1727 InsertionHandler Position;
1728
1729 public:
1730 /// \brief Move \p Inst before \p Before.
1731 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1732 : TypePromotionAction(Inst), Position(Inst) {
1733 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1734 Inst->moveBefore(Before);
1735 }
1736
1737 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001738 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001739 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1740 Position.insert(Inst);
1741 }
1742 };
1743
1744 /// \brief Set the operand of an instruction with a new value.
1745 class OperandSetter : public TypePromotionAction {
1746 /// Original operand of the instruction.
1747 Value *Origin;
1748 /// Index of the modified instruction.
1749 unsigned Idx;
1750
1751 public:
1752 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1753 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1754 : TypePromotionAction(Inst), Idx(Idx) {
1755 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1756 << "for:" << *Inst << "\n"
1757 << "with:" << *NewVal << "\n");
1758 Origin = Inst->getOperand(Idx);
1759 Inst->setOperand(Idx, NewVal);
1760 }
1761
1762 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001763 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001764 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1765 << "for: " << *Inst << "\n"
1766 << "with: " << *Origin << "\n");
1767 Inst->setOperand(Idx, Origin);
1768 }
1769 };
1770
1771 /// \brief Hide the operands of an instruction.
1772 /// Do as if this instruction was not using any of its operands.
1773 class OperandsHider : public TypePromotionAction {
1774 /// The list of original operands.
1775 SmallVector<Value *, 4> OriginalValues;
1776
1777 public:
1778 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1779 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1780 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1781 unsigned NumOpnds = Inst->getNumOperands();
1782 OriginalValues.reserve(NumOpnds);
1783 for (unsigned It = 0; It < NumOpnds; ++It) {
1784 // Save the current operand.
1785 Value *Val = Inst->getOperand(It);
1786 OriginalValues.push_back(Val);
1787 // Set a dummy one.
1788 // We could use OperandSetter here, but that would implied an overhead
1789 // that we are not willing to pay.
1790 Inst->setOperand(It, UndefValue::get(Val->getType()));
1791 }
1792 }
1793
1794 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001795 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001796 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1797 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1798 Inst->setOperand(It, OriginalValues[It]);
1799 }
1800 };
1801
1802 /// \brief Build a truncate instruction.
1803 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001804 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001805 public:
1806 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1807 /// result.
1808 /// trunc Opnd to Ty.
1809 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1810 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001811 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1812 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001813 }
1814
Quentin Colombetac55b152014-09-16 22:36:07 +00001815 /// \brief Get the built value.
1816 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001817
1818 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001819 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001820 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1821 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1822 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001823 }
1824 };
1825
1826 /// \brief Build a sign extension instruction.
1827 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001828 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001829 public:
1830 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1831 /// result.
1832 /// sext Opnd to Ty.
1833 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001834 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001835 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001836 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1837 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001838 }
1839
Quentin Colombetac55b152014-09-16 22:36:07 +00001840 /// \brief Get the built value.
1841 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001842
1843 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001844 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001845 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1846 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1847 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001848 }
1849 };
1850
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001851 /// \brief Build a zero extension instruction.
1852 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001853 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001854 public:
1855 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1856 /// result.
1857 /// zext Opnd to Ty.
1858 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001859 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001860 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001861 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1862 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001863 }
1864
Quentin Colombetac55b152014-09-16 22:36:07 +00001865 /// \brief Get the built value.
1866 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001867
1868 /// \brief Remove the built instruction.
1869 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001870 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1871 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1872 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001873 }
1874 };
1875
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001876 /// \brief Mutate an instruction to another type.
1877 class TypeMutator : public TypePromotionAction {
1878 /// Record the original type.
1879 Type *OrigTy;
1880
1881 public:
1882 /// \brief Mutate the type of \p Inst into \p NewTy.
1883 TypeMutator(Instruction *Inst, Type *NewTy)
1884 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1885 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1886 << "\n");
1887 Inst->mutateType(NewTy);
1888 }
1889
1890 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001891 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001892 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1893 << "\n");
1894 Inst->mutateType(OrigTy);
1895 }
1896 };
1897
1898 /// \brief Replace the uses of an instruction by another instruction.
1899 class UsesReplacer : public TypePromotionAction {
1900 /// Helper structure to keep track of the replaced uses.
1901 struct InstructionAndIdx {
1902 /// The instruction using the instruction.
1903 Instruction *Inst;
1904 /// The index where this instruction is used for Inst.
1905 unsigned Idx;
1906 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1907 : Inst(Inst), Idx(Idx) {}
1908 };
1909
1910 /// Keep track of the original uses (pair Instruction, Index).
1911 SmallVector<InstructionAndIdx, 4> OriginalUses;
1912 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1913
1914 public:
1915 /// \brief Replace all the use of \p Inst by \p New.
1916 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1917 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1918 << "\n");
1919 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001920 for (Use &U : Inst->uses()) {
1921 Instruction *UserI = cast<Instruction>(U.getUser());
1922 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001923 }
1924 // Now, we can replace the uses.
1925 Inst->replaceAllUsesWith(New);
1926 }
1927
1928 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001929 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001930 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1931 for (use_iterator UseIt = OriginalUses.begin(),
1932 EndIt = OriginalUses.end();
1933 UseIt != EndIt; ++UseIt) {
1934 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1935 }
1936 }
1937 };
1938
1939 /// \brief Remove an instruction from the IR.
1940 class InstructionRemover : public TypePromotionAction {
1941 /// Original position of the instruction.
1942 InsertionHandler Inserter;
1943 /// Helper structure to hide all the link to the instruction. In other
1944 /// words, this helps to do as if the instruction was removed.
1945 OperandsHider Hider;
1946 /// Keep track of the uses replaced, if any.
1947 UsesReplacer *Replacer;
1948
1949 public:
1950 /// \brief Remove all reference of \p Inst and optinally replace all its
1951 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001952 /// \pre If !Inst->use_empty(), then New != nullptr
1953 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001954 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001955 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001956 if (New)
1957 Replacer = new UsesReplacer(Inst, New);
1958 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1959 Inst->removeFromParent();
1960 }
1961
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00001962 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001963
1964 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001965 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001966
1967 /// \brief Resurrect the instruction and reassign it to the proper uses if
1968 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001969 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001970 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1971 Inserter.insert(Inst);
1972 if (Replacer)
1973 Replacer->undo();
1974 Hider.undo();
1975 }
1976 };
1977
1978public:
1979 /// Restoration point.
1980 /// The restoration point is a pointer to an action instead of an iterator
1981 /// because the iterator may be invalidated but not the pointer.
1982 typedef const TypePromotionAction *ConstRestorationPt;
1983 /// Advocate every changes made in that transaction.
1984 void commit();
1985 /// Undo all the changes made after the given point.
1986 void rollback(ConstRestorationPt Point);
1987 /// Get the current restoration point.
1988 ConstRestorationPt getRestorationPoint() const;
1989
1990 /// \name API for IR modification with state keeping to support rollback.
1991 /// @{
1992 /// Same as Instruction::setOperand.
1993 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1994 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001995 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001996 /// Same as Value::replaceAllUsesWith.
1997 void replaceAllUsesWith(Instruction *Inst, Value *New);
1998 /// Same as Value::mutateType.
1999 void mutateType(Instruction *Inst, Type *NewTy);
2000 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002001 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002002 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002003 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002004 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002005 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002006 /// Same as Instruction::moveBefore.
2007 void moveBefore(Instruction *Inst, Instruction *Before);
2008 /// @}
2009
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002010private:
2011 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002012 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2013 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002014};
2015
2016void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2017 Value *NewVal) {
2018 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002019 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002020}
2021
2022void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2023 Value *NewVal) {
2024 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002025 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002026}
2027
2028void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2029 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002030 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002031}
2032
2033void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002034 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002035}
2036
Quentin Colombetac55b152014-09-16 22:36:07 +00002037Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2038 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002039 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002040 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002041 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002042 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002043}
2044
Quentin Colombetac55b152014-09-16 22:36:07 +00002045Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2046 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002047 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002048 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002049 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002050 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002051}
2052
Quentin Colombetac55b152014-09-16 22:36:07 +00002053Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2054 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002055 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002056 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002057 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002058 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002059}
2060
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002061void TypePromotionTransaction::moveBefore(Instruction *Inst,
2062 Instruction *Before) {
2063 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002064 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002065}
2066
2067TypePromotionTransaction::ConstRestorationPt
2068TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002069 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002070}
2071
2072void TypePromotionTransaction::commit() {
2073 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002074 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002075 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002076 Actions.clear();
2077}
2078
2079void TypePromotionTransaction::rollback(
2080 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002081 while (!Actions.empty() && Point != Actions.back().get()) {
2082 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002083 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002084 }
2085}
2086
Chandler Carruthc8925912013-01-05 02:09:22 +00002087/// \brief A helper class for matching addressing modes.
2088///
2089/// This encapsulates the logic for matching the target-legal addressing modes.
2090class AddressingModeMatcher {
2091 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002092 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002093 const TargetLowering &TLI;
2094
2095 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2096 /// the memory instruction that we're computing this address for.
2097 Type *AccessTy;
2098 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002099
Chandler Carruthc8925912013-01-05 02:09:22 +00002100 /// AddrMode - This is the addressing mode that we're building up. This is
2101 /// part of the return value of this addressing mode matching stuff.
2102 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002103
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002104 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
2105 const SetOfInstrs &InsertedTruncs;
2106 /// A map from the instructions to their type before promotion.
2107 InstrToOrigTy &PromotedInsts;
2108 /// The ongoing transaction where every action should be registered.
2109 TypePromotionTransaction &TPT;
2110
Chandler Carruthc8925912013-01-05 02:09:22 +00002111 /// IgnoreProfitability - This is set to true when we should not do
2112 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
2113 /// always returns true.
2114 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002115
Eric Christopherd75c00c2015-02-26 22:38:34 +00002116 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
2117 const TargetMachine &TM, Type *AT, Instruction *MI,
2118 ExtAddrMode &AM, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002119 InstrToOrigTy &PromotedInsts,
2120 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002121 : AddrModeInsts(AMI), TM(TM),
2122 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2123 ->getTargetLowering()),
2124 AccessTy(AT), MemoryInst(MI), AddrMode(AM),
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002125 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002126 IgnoreProfitability = false;
2127 }
2128public:
Stephen Lin837bba12013-07-15 17:55:02 +00002129
Chandler Carruthc8925912013-01-05 02:09:22 +00002130 /// Match - Find the maximal addressing mode that a load/store of V can fold,
2131 /// give an access type of AccessTy. This returns a list of involved
2132 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002133 /// \p InsertedTruncs The truncate instruction inserted by other
2134 /// CodeGenPrepare
2135 /// optimizations.
2136 /// \p PromotedInsts maps the instructions to their type before promotion.
2137 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00002138 static ExtAddrMode Match(Value *V, Type *AccessTy,
2139 Instruction *MemoryInst,
2140 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002141 const TargetMachine &TM,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002142 const SetOfInstrs &InsertedTruncs,
2143 InstrToOrigTy &PromotedInsts,
2144 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002145 ExtAddrMode Result;
2146
Eric Christopherd75c00c2015-02-26 22:38:34 +00002147 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002148 MemoryInst, Result, InsertedTruncs,
2149 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002150 (void)Success; assert(Success && "Couldn't select *anything*?");
2151 return Result;
2152 }
2153private:
2154 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2155 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002156 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002157 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00002158 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
2159 ExtAddrMode &AMBefore,
2160 ExtAddrMode &AMAfter);
2161 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002162 bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002163 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002164};
2165
2166/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
2167/// Return true and update AddrMode if this addr mode is legal for the target,
2168/// false if not.
2169bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
2170 unsigned Depth) {
2171 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2172 // mode. Just process that directly.
2173 if (Scale == 1)
2174 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002175
Chandler Carruthc8925912013-01-05 02:09:22 +00002176 // If the scale is 0, it takes nothing to add this.
2177 if (Scale == 0)
2178 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002179
Chandler Carruthc8925912013-01-05 02:09:22 +00002180 // If we already have a scale of this value, we can add to it, otherwise, we
2181 // need an available scale field.
2182 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2183 return false;
2184
2185 ExtAddrMode TestAddrMode = AddrMode;
2186
2187 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2188 // [A+B + A*7] -> [B+A*8].
2189 TestAddrMode.Scale += Scale;
2190 TestAddrMode.ScaledReg = ScaleReg;
2191
2192 // If the new address isn't legal, bail out.
2193 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
2194 return false;
2195
2196 // It was legal, so commit it.
2197 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002198
Chandler Carruthc8925912013-01-05 02:09:22 +00002199 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2200 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2201 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002202 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002203 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2204 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2205 TestAddrMode.ScaledReg = AddLHS;
2206 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002207
Chandler Carruthc8925912013-01-05 02:09:22 +00002208 // If this addressing mode is legal, commit it and remember that we folded
2209 // this instruction.
2210 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
2211 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2212 AddrMode = TestAddrMode;
2213 return true;
2214 }
2215 }
2216
2217 // Otherwise, not (x+c)*scale, just return what we have.
2218 return true;
2219}
2220
2221/// MightBeFoldableInst - This is a little filter, which returns true if an
2222/// addressing computation involving I might be folded into a load/store
2223/// accessing it. This doesn't need to be perfect, but needs to accept at least
2224/// the set of instructions that MatchOperationAddr can.
2225static bool MightBeFoldableInst(Instruction *I) {
2226 switch (I->getOpcode()) {
2227 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002228 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002229 // Don't touch identity bitcasts.
2230 if (I->getType() == I->getOperand(0)->getType())
2231 return false;
2232 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2233 case Instruction::PtrToInt:
2234 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2235 return true;
2236 case Instruction::IntToPtr:
2237 // We know the input is intptr_t, so this is foldable.
2238 return true;
2239 case Instruction::Add:
2240 return true;
2241 case Instruction::Mul:
2242 case Instruction::Shl:
2243 // Can only handle X*C and X << C.
2244 return isa<ConstantInt>(I->getOperand(1));
2245 case Instruction::GetElementPtr:
2246 return true;
2247 default:
2248 return false;
2249 }
2250}
2251
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002252/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2253/// \note \p Val is assumed to be the product of some type promotion.
2254/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2255/// to be legal, as the non-promoted value would have had the same state.
2256static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
2257 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2258 if (!PromotedInst)
2259 return false;
2260 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2261 // If the ISDOpcode is undefined, it was undefined before the promotion.
2262 if (!ISDOpcode)
2263 return true;
2264 // Otherwise, check if the promoted instruction is legal or not.
2265 return TLI.isOperationLegalOrCustom(
2266 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
2267}
2268
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002269/// \brief Hepler class to perform type promotion.
2270class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002271 /// \brief Utility function to check whether or not a sign or zero extension
2272 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2273 /// either using the operands of \p Inst or promoting \p Inst.
2274 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002275 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002276 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002277 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002278 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002279 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002280 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002281 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002282 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2283 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284
2285 /// \brief Utility function to determine if \p OpIdx should be promoted when
2286 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002287 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002288 if (isa<SelectInst>(Inst) && OpIdx == 0)
2289 return false;
2290 return true;
2291 }
2292
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002293 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002294 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002295 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002296 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002297 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002298 /// Newly added extensions are inserted in \p Exts.
2299 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002300 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002301 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002302 static Value *promoteOperandForTruncAndAnyExt(
2303 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002304 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002305 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002306 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002307
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002308 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002309 /// operand is promotable and is not a supported trunc or sext.
2310 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002311 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002312 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002313 /// Newly added extensions are inserted in \p Exts.
2314 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002315 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002316 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002317 static Value *promoteOperandForOther(Instruction *Ext,
2318 TypePromotionTransaction &TPT,
2319 InstrToOrigTy &PromotedInsts,
2320 unsigned &CreatedInstsCost,
2321 SmallVectorImpl<Instruction *> *Exts,
2322 SmallVectorImpl<Instruction *> *Truncs,
2323 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002324
2325 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002326 static Value *signExtendOperandForOther(
2327 Instruction *Ext, TypePromotionTransaction &TPT,
2328 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2329 SmallVectorImpl<Instruction *> *Exts,
2330 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2331 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2332 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002333 }
2334
2335 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002336 static Value *zeroExtendOperandForOther(
2337 Instruction *Ext, TypePromotionTransaction &TPT,
2338 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2339 SmallVectorImpl<Instruction *> *Exts,
2340 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2341 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2342 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002343 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002344
2345public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002346 /// Type for the utility function that promotes the operand of Ext.
2347 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002348 InstrToOrigTy &PromotedInsts,
2349 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002350 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002351 SmallVectorImpl<Instruction *> *Truncs,
2352 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002353 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2354 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002355 /// \return NULL if no promotable action is possible with the current
2356 /// sign extension.
2357 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
2358 /// the others CodeGenPrepare optimizations. This information is important
2359 /// because we do not want to promote these instructions as CodeGenPrepare
2360 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2361 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002362 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002363 const TargetLowering &TLI,
2364 const InstrToOrigTy &PromotedInsts);
2365};
2366
2367bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002368 Type *ConsideredExtType,
2369 const InstrToOrigTy &PromotedInsts,
2370 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002371 // The promotion helper does not know how to deal with vector types yet.
2372 // To be able to fix that, we would need to fix the places where we
2373 // statically extend, e.g., constants and such.
2374 if (Inst->getType()->isVectorTy())
2375 return false;
2376
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002377 // We can always get through zext.
2378 if (isa<ZExtInst>(Inst))
2379 return true;
2380
2381 // sext(sext) is ok too.
2382 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002383 return true;
2384
2385 // We can get through binary operator, if it is legal. In other words, the
2386 // binary operator must have a nuw or nsw flag.
2387 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2388 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002389 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2390 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002391 return true;
2392
2393 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002394 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002395 if (!isa<TruncInst>(Inst))
2396 return false;
2397
2398 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002399 // Check if we can use this operand in the extension.
2400 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401 // we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002402 if (!OpndVal->getType()->isIntegerTy() ||
2403 OpndVal->getType()->getIntegerBitWidth() >
2404 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002405 return false;
2406
2407 // If the operand of the truncate is not an instruction, we will not have
2408 // any information on the dropped bits.
2409 // (Actually we could for constant but it is not worth the extra logic).
2410 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2411 if (!Opnd)
2412 return false;
2413
2414 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002415 // I.e., check that trunc just drops extended bits of the same kind of
2416 // the extension.
2417 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002418 const Type *OpndType;
2419 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002420 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
2421 OpndType = It->second.Ty;
2422 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2423 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002424 else
2425 return false;
2426
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002427 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2429 return true;
2430
2431 return false;
2432}
2433
2434TypePromotionHelper::Action TypePromotionHelper::getAction(
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002435 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002437 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2438 "Unexpected instruction type");
2439 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2440 Type *ExtTy = Ext->getType();
2441 bool IsSExt = isa<SExtInst>(Ext);
2442 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443 // get through.
2444 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002445 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002446 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002447
2448 // Do not promote if the operand has been added by codegenprepare.
2449 // Otherwise, it means we are undoing an optimization that is likely to be
2450 // redone, thus causing potential infinite loop.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002451 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002452 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002453
2454 // SExt or Trunc instructions.
2455 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002456 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2457 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002458 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459
2460 // Regular instruction.
2461 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002462 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002463 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002464 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002465}
2466
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002467Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002468 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002469 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002470 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002471 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002472 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2473 // get through it and this method should not be called.
2474 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002475 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002476 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002477 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002478 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002479 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002480 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002481 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002482 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2483 TPT.replaceAllUsesWith(SExt, ZExt);
2484 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002485 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002486 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002487 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2488 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002489 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2490 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002491 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002492
2493 // Remove dead code.
2494 if (SExtOpnd->use_empty())
2495 TPT.eraseInstruction(SExtOpnd);
2496
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002497 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002498 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002499 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002500 if (ExtInst) {
2501 if (Exts)
2502 Exts->push_back(ExtInst);
2503 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2504 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002505 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002506 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002507
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002508 // At this point we have: ext ty opnd to ty.
2509 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2510 Value *NextVal = ExtInst->getOperand(0);
2511 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002512 return NextVal;
2513}
2514
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002515Value *TypePromotionHelper::promoteOperandForOther(
2516 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002517 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002518 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002519 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2520 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002521 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002522 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002523 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002524 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002525 if (!ExtOpnd->hasOneUse()) {
2526 // ExtOpnd will be promoted.
2527 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002528 // promoted version.
2529 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002530 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002531 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2532 ITrunc->removeFromParent();
2533 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002534 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002535 if (Truncs)
2536 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002537 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002538
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002539 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2540 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002541 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002542 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002543 }
2544
2545 // Get through the Instruction:
2546 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002547 // 2. Replace the uses of Ext by Inst.
2548 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002549
2550 // Remember the original type of the instruction before promotion.
2551 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002552 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2553 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002554 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002555 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002556 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002557 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002558 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002559 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002560
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002561 DEBUG(dbgs() << "Propagate Ext to operands\n");
2562 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002563 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002564 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2565 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2566 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002567 DEBUG(dbgs() << "No need to propagate\n");
2568 continue;
2569 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002570 // Check if we can statically extend the operand.
2571 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002572 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002573 DEBUG(dbgs() << "Statically extend\n");
2574 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2575 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2576 : Cst->getValue().zext(BitWidth);
2577 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002578 continue;
2579 }
2580 // UndefValue are typed, so we have to statically sign extend them.
2581 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002582 DEBUG(dbgs() << "Statically extend\n");
2583 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002584 continue;
2585 }
2586
2587 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002588 // Check if Ext was reused to extend an operand.
2589 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002590 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002591 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002592 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2593 : TPT.createZExt(Ext, Opnd, Ext->getType());
2594 if (!isa<Instruction>(ValForExtOpnd)) {
2595 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2596 continue;
2597 }
2598 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002600 if (Exts)
2601 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002602 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002603
2604 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002605 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2606 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002607 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002608 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002609 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002610 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002611 if (ExtForOpnd == Ext) {
2612 DEBUG(dbgs() << "Extension is useless now\n");
2613 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002614 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002615 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002616}
2617
Quentin Colombet867c5502014-02-14 22:23:22 +00002618/// IsPromotionProfitable - Check whether or not promoting an instruction
2619/// to a wider type was profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002620/// \p NewCost gives the cost of extension instructions created by the
2621/// promotion.
2622/// \p OldCost gives the cost of extension instructions before the promotion
2623/// plus the number of instructions that have been
2624/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00002625/// \p PromotedOperand is the value that has been promoted.
2626/// \return True if the promotion is profitable, false otherwise.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002627bool AddressingModeMatcher::IsPromotionProfitable(
2628 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2629 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2630 // The cost of the new extensions is greater than the cost of the
2631 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00002632 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002633 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002634 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002635 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002636 return true;
2637 // The promotion is neutral but it may help folding the sign extension in
2638 // loads for instance.
2639 // Check that we did not create an illegal instruction.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002640 return isPromotedInstructionLegal(TLI, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002641}
2642
Chandler Carruthc8925912013-01-05 02:09:22 +00002643/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2644/// fold the operation into the addressing mode. If so, update the addressing
2645/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002646/// If \p MovedAway is not NULL, it contains the information of whether or
2647/// not AddrInst has to be folded into the addressing mode on success.
2648/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2649/// because it has been moved away.
2650/// Thus AddrInst must not be added in the matched instructions.
2651/// This state can happen when AddrInst is a sext, since it may be moved away.
2652/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2653/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002654bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002655 unsigned Depth,
2656 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002657 // Avoid exponential behavior on extremely deep expression trees.
2658 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002659
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002660 // By default, all matched instructions stay in place.
2661 if (MovedAway)
2662 *MovedAway = false;
2663
Chandler Carruthc8925912013-01-05 02:09:22 +00002664 switch (Opcode) {
2665 case Instruction::PtrToInt:
2666 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2667 return MatchAddr(AddrInst->getOperand(0), Depth);
2668 case Instruction::IntToPtr:
2669 // This inttoptr is a no-op if the integer type is pointer sized.
2670 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002671 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002672 return MatchAddr(AddrInst->getOperand(0), Depth);
2673 return false;
2674 case Instruction::BitCast:
2675 // BitCast is always a noop, and we can handle it as long as it is
2676 // int->int or pointer->pointer (we don't want int<->fp or something).
2677 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2678 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2679 // Don't touch identity bitcasts. These were probably put here by LSR,
2680 // and we don't want to mess around with them. Assume it knows what it
2681 // is doing.
2682 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2683 return MatchAddr(AddrInst->getOperand(0), Depth);
2684 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00002685 case Instruction::AddrSpaceCast: {
2686 unsigned SrcAS
2687 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2688 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2689 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2690 return MatchAddr(AddrInst->getOperand(0), Depth);
2691 return false;
2692 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002693 case Instruction::Add: {
2694 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2695 ExtAddrMode BackupAddrMode = AddrMode;
2696 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002697 // Start a transaction at this point.
2698 // The LHS may match but not the RHS.
2699 // Therefore, we need a higher level restoration point to undo partially
2700 // matched operation.
2701 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2702 TPT.getRestorationPoint();
2703
Chandler Carruthc8925912013-01-05 02:09:22 +00002704 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2705 MatchAddr(AddrInst->getOperand(0), Depth+1))
2706 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002707
Chandler Carruthc8925912013-01-05 02:09:22 +00002708 // Restore the old addr mode info.
2709 AddrMode = BackupAddrMode;
2710 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002711 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002712
Chandler Carruthc8925912013-01-05 02:09:22 +00002713 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2714 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2715 MatchAddr(AddrInst->getOperand(1), Depth+1))
2716 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002717
Chandler Carruthc8925912013-01-05 02:09:22 +00002718 // Otherwise we definitely can't merge the ADD in.
2719 AddrMode = BackupAddrMode;
2720 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002721 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002722 break;
2723 }
2724 //case Instruction::Or:
2725 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2726 //break;
2727 case Instruction::Mul:
2728 case Instruction::Shl: {
2729 // Can only handle X*C and X << C.
2730 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002731 if (!RHS)
2732 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002733 int64_t Scale = RHS->getSExtValue();
2734 if (Opcode == Instruction::Shl)
2735 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002736
Chandler Carruthc8925912013-01-05 02:09:22 +00002737 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2738 }
2739 case Instruction::GetElementPtr: {
2740 // Scan the GEP. We check it if it contains constant offsets and at most
2741 // one variable offset.
2742 int VariableOperand = -1;
2743 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002744
Chandler Carruthc8925912013-01-05 02:09:22 +00002745 int64_t ConstantOffset = 0;
2746 const DataLayout *TD = TLI.getDataLayout();
2747 gep_type_iterator GTI = gep_type_begin(AddrInst);
2748 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2749 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2750 const StructLayout *SL = TD->getStructLayout(STy);
2751 unsigned Idx =
2752 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2753 ConstantOffset += SL->getElementOffset(Idx);
2754 } else {
2755 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2756 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2757 ConstantOffset += CI->getSExtValue()*TypeSize;
2758 } else if (TypeSize) { // Scales of zero don't do anything.
2759 // We only allow one variable index at the moment.
2760 if (VariableOperand != -1)
2761 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002762
Chandler Carruthc8925912013-01-05 02:09:22 +00002763 // Remember the variable index.
2764 VariableOperand = i;
2765 VariableScale = TypeSize;
2766 }
2767 }
2768 }
Stephen Lin837bba12013-07-15 17:55:02 +00002769
Chandler Carruthc8925912013-01-05 02:09:22 +00002770 // A common case is for the GEP to only do a constant offset. In this case,
2771 // just add it to the disp field and check validity.
2772 if (VariableOperand == -1) {
2773 AddrMode.BaseOffs += ConstantOffset;
2774 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2775 // Check to see if we can fold the base pointer in too.
2776 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2777 return true;
2778 }
2779 AddrMode.BaseOffs -= ConstantOffset;
2780 return false;
2781 }
2782
2783 // Save the valid addressing mode in case we can't match.
2784 ExtAddrMode BackupAddrMode = AddrMode;
2785 unsigned OldSize = AddrModeInsts.size();
2786
2787 // See if the scale and offset amount is valid for this target.
2788 AddrMode.BaseOffs += ConstantOffset;
2789
2790 // Match the base operand of the GEP.
2791 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2792 // If it couldn't be matched, just stuff the value in a register.
2793 if (AddrMode.HasBaseReg) {
2794 AddrMode = BackupAddrMode;
2795 AddrModeInsts.resize(OldSize);
2796 return false;
2797 }
2798 AddrMode.HasBaseReg = true;
2799 AddrMode.BaseReg = AddrInst->getOperand(0);
2800 }
2801
2802 // Match the remaining variable portion of the GEP.
2803 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2804 Depth)) {
2805 // If it couldn't be matched, try stuffing the base into a register
2806 // instead of matching it, and retrying the match of the scale.
2807 AddrMode = BackupAddrMode;
2808 AddrModeInsts.resize(OldSize);
2809 if (AddrMode.HasBaseReg)
2810 return false;
2811 AddrMode.HasBaseReg = true;
2812 AddrMode.BaseReg = AddrInst->getOperand(0);
2813 AddrMode.BaseOffs += ConstantOffset;
2814 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2815 VariableScale, Depth)) {
2816 // If even that didn't work, bail.
2817 AddrMode = BackupAddrMode;
2818 AddrModeInsts.resize(OldSize);
2819 return false;
2820 }
2821 }
2822
2823 return true;
2824 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002825 case Instruction::SExt:
2826 case Instruction::ZExt: {
2827 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2828 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002829 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002830
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002831 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002832 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002833 TypePromotionHelper::Action TPH =
2834 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002835 if (!TPH)
2836 return false;
2837
2838 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2839 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00002840 unsigned CreatedInstsCost = 0;
2841 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002842 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00002843 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002844 // SExt has been moved away.
2845 // Thus either it will be rematched later in the recursive calls or it is
2846 // gone. Anyway, we must not fold it into the addressing mode at this point.
2847 // E.g.,
2848 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002849 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002850 // addr = gep base, idx
2851 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002852 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002853 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2854 // addr = gep base, op <- match
2855 if (MovedAway)
2856 *MovedAway = true;
2857
2858 assert(PromotedOperand &&
2859 "TypePromotionHelper should have filtered out those cases");
2860
2861 ExtAddrMode BackupAddrMode = AddrMode;
2862 unsigned OldSize = AddrModeInsts.size();
2863
2864 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet1b274f92015-03-10 21:48:15 +00002865 // The total of the new cost is equals to the cost of the created
2866 // instructions.
2867 // The total of the old cost is equals to the cost of the extension plus
2868 // what we have saved in the addressing mode.
2869 !IsPromotionProfitable(CreatedInstsCost,
2870 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00002871 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002872 AddrMode = BackupAddrMode;
2873 AddrModeInsts.resize(OldSize);
2874 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2875 TPT.rollback(LastKnownGood);
2876 return false;
2877 }
2878 return true;
2879 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002880 }
2881 return false;
2882}
2883
2884/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2885/// addressing mode. If Addr can't be added to AddrMode this returns false and
2886/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2887/// or intptr_t for the target.
2888///
2889bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002890 // Start a transaction at this point that we will rollback if the matching
2891 // fails.
2892 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2893 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002894 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2895 // Fold in immediates if legal for the target.
2896 AddrMode.BaseOffs += CI->getSExtValue();
2897 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2898 return true;
2899 AddrMode.BaseOffs -= CI->getSExtValue();
2900 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2901 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002902 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002903 AddrMode.BaseGV = GV;
2904 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2905 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002906 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002907 }
2908 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2909 ExtAddrMode BackupAddrMode = AddrMode;
2910 unsigned OldSize = AddrModeInsts.size();
2911
2912 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002913 bool MovedAway = false;
2914 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2915 // This instruction may have been move away. If so, there is nothing
2916 // to check here.
2917 if (MovedAway)
2918 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002919 // Okay, it's possible to fold this. Check to see if it is actually
2920 // *profitable* to do so. We use a simple cost model to avoid increasing
2921 // register pressure too much.
2922 if (I->hasOneUse() ||
2923 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2924 AddrModeInsts.push_back(I);
2925 return true;
2926 }
Stephen Lin837bba12013-07-15 17:55:02 +00002927
Chandler Carruthc8925912013-01-05 02:09:22 +00002928 // It isn't profitable to do this, roll back.
2929 //cerr << "NOT FOLDING: " << *I;
2930 AddrMode = BackupAddrMode;
2931 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002932 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002933 }
2934 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2935 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2936 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002937 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002938 } else if (isa<ConstantPointerNull>(Addr)) {
2939 // Null pointer gets folded without affecting the addressing mode.
2940 return true;
2941 }
2942
2943 // Worse case, the target should support [reg] addressing modes. :)
2944 if (!AddrMode.HasBaseReg) {
2945 AddrMode.HasBaseReg = true;
2946 AddrMode.BaseReg = Addr;
2947 // Still check for legality in case the target supports [imm] but not [i+r].
2948 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2949 return true;
2950 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002951 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002952 }
2953
2954 // If the base register is already taken, see if we can do [r+r].
2955 if (AddrMode.Scale == 0) {
2956 AddrMode.Scale = 1;
2957 AddrMode.ScaledReg = Addr;
2958 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2959 return true;
2960 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002961 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002962 }
2963 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002964 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002965 return false;
2966}
2967
2968/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2969/// inline asm call are due to memory operands. If so, return true, otherwise
2970/// return false.
2971static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00002972 const TargetMachine &TM) {
2973 const Function *F = CI->getParent()->getParent();
2974 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2975 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00002976 TargetLowering::AsmOperandInfoVector TargetConstraints =
Eric Christopher11e4df72015-02-26 22:38:43 +00002977 TLI->ParseConstraints(TRI, ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00002978 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2979 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002980
Chandler Carruthc8925912013-01-05 02:09:22 +00002981 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00002982 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00002983
2984 // If this asm operand is our Value*, and if it isn't an indirect memory
2985 // operand, we can't fold it!
2986 if (OpInfo.CallOperandVal == OpVal &&
2987 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2988 !OpInfo.isIndirect))
2989 return false;
2990 }
2991
2992 return true;
2993}
2994
2995/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2996/// memory use. If we find an obviously non-foldable instruction, return true.
2997/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00002998static bool FindAllMemoryUses(
2999 Instruction *I,
3000 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3001 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003002 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003003 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003004 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003005
Chandler Carruthc8925912013-01-05 02:09:22 +00003006 // If this is an obviously unfoldable instruction, bail out.
3007 if (!MightBeFoldableInst(I))
3008 return true;
3009
3010 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003011 for (Use &U : I->uses()) {
3012 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003013
Chandler Carruthcdf47882014-03-09 03:16:01 +00003014 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3015 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003016 continue;
3017 }
Stephen Lin837bba12013-07-15 17:55:02 +00003018
Chandler Carruthcdf47882014-03-09 03:16:01 +00003019 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3020 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003021 if (opNo == 0) return true; // Storing addr, not into addr.
3022 MemoryUses.push_back(std::make_pair(SI, opNo));
3023 continue;
3024 }
Stephen Lin837bba12013-07-15 17:55:02 +00003025
Chandler Carruthcdf47882014-03-09 03:16:01 +00003026 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003027 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3028 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003029
Chandler Carruthc8925912013-01-05 02:09:22 +00003030 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003031 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003032 return true;
3033 continue;
3034 }
Stephen Lin837bba12013-07-15 17:55:02 +00003035
Eric Christopher11e4df72015-02-26 22:38:43 +00003036 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003037 return true;
3038 }
3039
3040 return false;
3041}
3042
3043/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
3044/// the use site that we're folding it into. If so, there is no cost to
3045/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
3046/// that we know are live at the instruction already.
3047bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
3048 Value *KnownLive2) {
3049 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003050 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003051 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003052
Chandler Carruthc8925912013-01-05 02:09:22 +00003053 // All values other than instructions and arguments (e.g. constants) are live.
3054 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003055
Chandler Carruthc8925912013-01-05 02:09:22 +00003056 // If Val is a constant sized alloca in the entry block, it is live, this is
3057 // true because it is just a reference to the stack/frame pointer, which is
3058 // live for the whole function.
3059 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3060 if (AI->isStaticAlloca())
3061 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003062
Chandler Carruthc8925912013-01-05 02:09:22 +00003063 // Check to see if this value is already used in the memory instruction's
3064 // block. If so, it's already live into the block at the very least, so we
3065 // can reasonably fold it.
3066 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3067}
3068
3069/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
3070/// mode of the machine to fold the specified instruction into a load or store
3071/// that ultimately uses it. However, the specified instruction has multiple
3072/// uses. Given this, it may actually increase register pressure to fold it
3073/// into the load. For example, consider this code:
3074///
3075/// X = ...
3076/// Y = X+1
3077/// use(Y) -> nonload/store
3078/// Z = Y+1
3079/// load Z
3080///
3081/// In this case, Y has multiple uses, and can be folded into the load of Z
3082/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3083/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3084/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3085/// number of computations either.
3086///
3087/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3088/// X was live across 'load Z' for other reasons, we actually *would* want to
3089/// fold the addressing mode in the Z case. This would make Y die earlier.
3090bool AddressingModeMatcher::
3091IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
3092 ExtAddrMode &AMAfter) {
3093 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003094
Chandler Carruthc8925912013-01-05 02:09:22 +00003095 // AMBefore is the addressing mode before this instruction was folded into it,
3096 // and AMAfter is the addressing mode after the instruction was folded. Get
3097 // the set of registers referenced by AMAfter and subtract out those
3098 // referenced by AMBefore: this is the set of values which folding in this
3099 // address extends the lifetime of.
3100 //
3101 // Note that there are only two potential values being referenced here,
3102 // BaseReg and ScaleReg (global addresses are always available, as are any
3103 // folded immediates).
3104 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003105
Chandler Carruthc8925912013-01-05 02:09:22 +00003106 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3107 // lifetime wasn't extended by adding this instruction.
3108 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003109 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003110 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003111 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003112
3113 // If folding this instruction (and it's subexprs) didn't extend any live
3114 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003115 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003116 return true;
3117
3118 // If all uses of this instruction are ultimately load/store/inlineasm's,
3119 // check to see if their addressing modes will include this instruction. If
3120 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3121 // uses.
3122 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3123 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003124 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003125 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003126
Chandler Carruthc8925912013-01-05 02:09:22 +00003127 // Now that we know that all uses of this instruction are part of a chain of
3128 // computation involving only operations that could theoretically be folded
3129 // into a memory use, loop over each of these uses and see if they could
3130 // *actually* fold the instruction.
3131 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3132 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3133 Instruction *User = MemoryUses[i].first;
3134 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003135
Chandler Carruthc8925912013-01-05 02:09:22 +00003136 // Get the access type of this use. If the use isn't a pointer, we don't
3137 // know what it accesses.
3138 Value *Address = User->getOperand(OpNo);
3139 if (!Address->getType()->isPointerTy())
3140 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003141 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00003142
Chandler Carruthc8925912013-01-05 02:09:22 +00003143 // Do a match against the root of this address, ignoring profitability. This
3144 // will tell us if the addressing mode for the memory operation will
3145 // *actually* cover the shared instruction.
3146 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003147 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3148 TPT.getRestorationPoint();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003149 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003150 MemoryInst, Result, InsertedTruncs,
3151 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003152 Matcher.IgnoreProfitability = true;
3153 bool Success = Matcher.MatchAddr(Address, 0);
3154 (void)Success; assert(Success && "Couldn't select *anything*?");
3155
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003156 // The match was to check the profitability, the changes made are not
3157 // part of the original matcher. Therefore, they should be dropped
3158 // otherwise the original matcher will not present the right state.
3159 TPT.rollback(LastKnownGood);
3160
Chandler Carruthc8925912013-01-05 02:09:22 +00003161 // If the match didn't cover I, then it won't be shared by it.
3162 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3163 I) == MatchedAddrModeInsts.end())
3164 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003165
Chandler Carruthc8925912013-01-05 02:09:22 +00003166 MatchedAddrModeInsts.clear();
3167 }
Stephen Lin837bba12013-07-15 17:55:02 +00003168
Chandler Carruthc8925912013-01-05 02:09:22 +00003169 return true;
3170}
3171
3172} // end anonymous namespace
3173
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003174/// IsNonLocalValue - Return true if the specified values are defined in a
3175/// different basic block than BB.
3176static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3177 if (Instruction *I = dyn_cast<Instruction>(V))
3178 return I->getParent() != BB;
3179 return false;
3180}
3181
Bob Wilson53bdae32009-12-03 21:47:07 +00003182/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003183/// addressing modes that can do significant amounts of computation. As such,
3184/// instruction selection will try to get the load or store to do as much
3185/// computation as possible for the program. The problem is that isel can only
3186/// see within a single block. As such, we sink as much legal addressing mode
3187/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003188///
3189/// This method is used to optimize both load/store and inline asms with memory
3190/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003191bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00003192 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003193 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003194
3195 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003196 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003197 SmallVector<Value*, 8> worklist;
3198 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003199 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003200
Owen Anderson8ba5f392010-11-27 08:15:55 +00003201 // Use a worklist to iteratively look through PHI nodes, and ensure that
3202 // the addressing mode obtained from the non-PHI roots of the graph
3203 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003204 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003205 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003206 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003207 SmallVector<Instruction*, 16> AddrModeInsts;
3208 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003209 TypePromotionTransaction TPT;
3210 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3211 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003212 while (!worklist.empty()) {
3213 Value *V = worklist.back();
3214 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003215
Owen Anderson8ba5f392010-11-27 08:15:55 +00003216 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003217 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003218 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003219 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003220 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003221
Owen Anderson8ba5f392010-11-27 08:15:55 +00003222 // For a PHI node, push all of its incoming values.
3223 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003224 for (Value *IncValue : P->incoming_values())
3225 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003226 continue;
3227 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003228
Owen Anderson8ba5f392010-11-27 08:15:55 +00003229 // For non-PHIs, determine the addressing mode being computed.
3230 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003231 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Eric Christopherd75c00c2015-02-26 22:38:34 +00003232 V, AccessTy, MemoryInst, NewAddrModeInsts, *TM, InsertedTruncsSet,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003233 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003234
3235 // This check is broken into two cases with very similar code to avoid using
3236 // getNumUses() as much as possible. Some values have a lot of uses, so
3237 // calling getNumUses() unconditionally caused a significant compile-time
3238 // regression.
3239 if (!Consensus) {
3240 Consensus = V;
3241 AddrMode = NewAddrMode;
3242 AddrModeInsts = NewAddrModeInsts;
3243 continue;
3244 } else if (NewAddrMode == AddrMode) {
3245 if (!IsNumUsesConsensusValid) {
3246 NumUsesConsensus = Consensus->getNumUses();
3247 IsNumUsesConsensusValid = true;
3248 }
3249
3250 // Ensure that the obtained addressing mode is equivalent to that obtained
3251 // for all other roots of the PHI traversal. Also, when choosing one
3252 // such root as representative, select the one with the most uses in order
3253 // to keep the cost modeling heuristics in AddressingModeMatcher
3254 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003255 unsigned NumUses = V->getNumUses();
3256 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003257 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003258 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003259 AddrModeInsts = NewAddrModeInsts;
3260 }
3261 continue;
3262 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003263
Craig Topperc0196b12014-04-14 00:51:57 +00003264 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003265 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003266 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003267
Owen Anderson8ba5f392010-11-27 08:15:55 +00003268 // If the addressing mode couldn't be determined, or if multiple different
3269 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003270 if (!Consensus) {
3271 TPT.rollback(LastKnownGood);
3272 return false;
3273 }
3274 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003275
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003276 // Check to see if any of the instructions supersumed by this addr mode are
3277 // non-local to I's BB.
3278 bool AnyNonLocal = false;
3279 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003280 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003281 AnyNonLocal = true;
3282 break;
3283 }
3284 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003285
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003286 // If all the instructions matched are already in this BB, don't do anything.
3287 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003288 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003289 return false;
3290 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003291
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003292 // Insert this computation right after this user. Since our caller is
3293 // scanning from the top of the BB to the bottom, reuse of the expr are
3294 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003295 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003296
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003297 // Now that we determined the addressing expression we want to use and know
3298 // that we have to sink it into this block. Check to see if we have already
3299 // done this for some other load/store instr in this block. If so, reuse the
3300 // computation.
3301 Value *&SunkAddr = SunkAddrs[Addr];
3302 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003303 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003304 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003305 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003306 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003307 } else if (AddrSinkUsingGEPs ||
3308 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003309 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3310 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003311 // By default, we use the GEP-based method when AA is used later. This
3312 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3313 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003314 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00003315 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003316 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003317
3318 // First, find the pointer.
3319 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3320 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003321 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003322 }
3323
3324 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3325 // We can't add more than one pointer together, nor can we scale a
3326 // pointer (both of which seem meaningless).
3327 if (ResultPtr || AddrMode.Scale != 1)
3328 return false;
3329
3330 ResultPtr = AddrMode.ScaledReg;
3331 AddrMode.Scale = 0;
3332 }
3333
3334 if (AddrMode.BaseGV) {
3335 if (ResultPtr)
3336 return false;
3337
3338 ResultPtr = AddrMode.BaseGV;
3339 }
3340
3341 // If the real base value actually came from an inttoptr, then the matcher
3342 // will look through it and provide only the integer value. In that case,
3343 // use it here.
3344 if (!ResultPtr && AddrMode.BaseReg) {
3345 ResultPtr =
3346 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003347 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003348 } else if (!ResultPtr && AddrMode.Scale == 1) {
3349 ResultPtr =
3350 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3351 AddrMode.Scale = 0;
3352 }
3353
3354 if (!ResultPtr &&
3355 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3356 SunkAddr = Constant::getNullValue(Addr->getType());
3357 } else if (!ResultPtr) {
3358 return false;
3359 } else {
3360 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003361 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3362 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003363
3364 // Start with the base register. Do this first so that subsequent address
3365 // matching finds it last, which will prevent it from trying to match it
3366 // as the scaled value in case it happens to be a mul. That would be
3367 // problematic if we've sunk a different mul for the scale, because then
3368 // we'd end up sinking both muls.
3369 if (AddrMode.BaseReg) {
3370 Value *V = AddrMode.BaseReg;
3371 if (V->getType() != IntPtrTy)
3372 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3373
3374 ResultIndex = V;
3375 }
3376
3377 // Add the scale value.
3378 if (AddrMode.Scale) {
3379 Value *V = AddrMode.ScaledReg;
3380 if (V->getType() == IntPtrTy) {
3381 // done.
3382 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3383 cast<IntegerType>(V->getType())->getBitWidth()) {
3384 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3385 } else {
3386 // It is only safe to sign extend the BaseReg if we know that the math
3387 // required to create it did not overflow before we extend it. Since
3388 // the original IR value was tossed in favor of a constant back when
3389 // the AddrMode was created we need to bail out gracefully if widths
3390 // do not match instead of extending it.
3391 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3392 if (I && (ResultIndex != AddrMode.BaseReg))
3393 I->eraseFromParent();
3394 return false;
3395 }
3396
3397 if (AddrMode.Scale != 1)
3398 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3399 "sunkaddr");
3400 if (ResultIndex)
3401 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3402 else
3403 ResultIndex = V;
3404 }
3405
3406 // Add in the Base Offset if present.
3407 if (AddrMode.BaseOffs) {
3408 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3409 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003410 // We need to add this separately from the scale above to help with
3411 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003412 if (ResultPtr->getType() != I8PtrTy)
3413 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003414 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003415 }
3416
3417 ResultIndex = V;
3418 }
3419
3420 if (!ResultIndex) {
3421 SunkAddr = ResultPtr;
3422 } else {
3423 if (ResultPtr->getType() != I8PtrTy)
3424 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003425 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003426 }
3427
3428 if (SunkAddr->getType() != Addr->getType())
3429 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3430 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003431 } else {
David Greene74e2d492010-01-05 01:27:11 +00003432 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003433 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00003434 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003435 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003436
3437 // Start with the base register. Do this first so that subsequent address
3438 // matching finds it last, which will prevent it from trying to match it
3439 // as the scaled value in case it happens to be a mul. That would be
3440 // problematic if we've sunk a different mul for the scale, because then
3441 // we'd end up sinking both muls.
3442 if (AddrMode.BaseReg) {
3443 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003444 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003445 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003446 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003447 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003448 Result = V;
3449 }
3450
3451 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003452 if (AddrMode.Scale) {
3453 Value *V = AddrMode.ScaledReg;
3454 if (V->getType() == IntPtrTy) {
3455 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003456 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003457 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003458 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3459 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003460 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003461 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003462 // It is only safe to sign extend the BaseReg if we know that the math
3463 // required to create it did not overflow before we extend it. Since
3464 // the original IR value was tossed in favor of a constant back when
3465 // the AddrMode was created we need to bail out gracefully if widths
3466 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003467 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003468 if (I && (Result != AddrMode.BaseReg))
3469 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003470 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003471 }
3472 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003473 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3474 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003475 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003476 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003477 else
3478 Result = V;
3479 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003480
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003481 // Add in the BaseGV if present.
3482 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003483 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003484 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003485 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003486 else
3487 Result = V;
3488 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003489
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003490 // Add in the Base Offset if present.
3491 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003492 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003493 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003494 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003495 else
3496 Result = V;
3497 }
3498
Craig Topperc0196b12014-04-14 00:51:57 +00003499 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003500 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003501 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003502 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003503 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003504
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003505 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003506
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003507 // If we have no uses, recursively delete the value and all dead instructions
3508 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003509 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003510 // This can cause recursive deletion, which can invalidate our iterator.
3511 // Use a WeakVH to hold onto it in case this happens.
3512 WeakVH IterHandle(CurInstIterator);
3513 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003514
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003515 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003516
3517 if (IterHandle != CurInstIterator) {
3518 // If the iterator instruction was recursively deleted, start over at the
3519 // start of the block.
3520 CurInstIterator = BB->begin();
3521 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003522 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003523 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003524 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003525 return true;
3526}
3527
Evan Cheng1da25002008-02-26 02:42:37 +00003528/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00003529/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00003530/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00003531bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003532 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003533
Eric Christopher11e4df72015-02-26 22:38:43 +00003534 const TargetRegisterInfo *TRI =
3535 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Nadav Rotem465834c2012-07-24 10:51:42 +00003536 TargetLowering::AsmOperandInfoVector
Eric Christopher11e4df72015-02-26 22:38:43 +00003537 TargetConstraints = TLI->ParseConstraints(TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003538 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003539 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3540 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003541
Evan Cheng1da25002008-02-26 02:42:37 +00003542 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003543 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003544
Eli Friedman666bbe32008-02-26 18:37:49 +00003545 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3546 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003547 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00003548 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003549 } else if (OpInfo.Type == InlineAsm::isInput)
3550 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003551 }
3552
3553 return MadeChange;
3554}
3555
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003556/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3557/// sign extensions.
3558static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3559 assert(!Inst->use_empty() && "Input must have at least one use");
3560 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3561 bool IsSExt = isa<SExtInst>(FirstUser);
3562 Type *ExtTy = FirstUser->getType();
3563 for (const User *U : Inst->users()) {
3564 const Instruction *UI = cast<Instruction>(U);
3565 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3566 return false;
3567 Type *CurTy = UI->getType();
3568 // Same input and output types: Same instruction after CSE.
3569 if (CurTy == ExtTy)
3570 continue;
3571
3572 // If IsSExt is true, we are in this situation:
3573 // a = Inst
3574 // b = sext ty1 a to ty2
3575 // c = sext ty1 a to ty3
3576 // Assuming ty2 is shorter than ty3, this could be turned into:
3577 // a = Inst
3578 // b = sext ty1 a to ty2
3579 // c = sext ty2 b to ty3
3580 // However, the last sext is not free.
3581 if (IsSExt)
3582 return false;
3583
3584 // This is a ZExt, maybe this is free to extend from one type to another.
3585 // In that case, we would not account for a different use.
3586 Type *NarrowTy;
3587 Type *LargeTy;
3588 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3589 CurTy->getScalarType()->getIntegerBitWidth()) {
3590 NarrowTy = CurTy;
3591 LargeTy = ExtTy;
3592 } else {
3593 NarrowTy = ExtTy;
3594 LargeTy = CurTy;
3595 }
3596
3597 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3598 return false;
3599 }
3600 // All uses are the same or can be derived from one another for free.
3601 return true;
3602}
3603
3604/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3605/// load instruction.
3606/// If an ext(load) can be formed, it is returned via \p LI for the load
3607/// and \p Inst for the extension.
3608/// Otherwise LI == nullptr and Inst == nullptr.
3609/// When some promotion happened, \p TPT contains the proper state to
3610/// revert them.
3611///
3612/// \return true when promoting was necessary to expose the ext(load)
3613/// opportunity, false otherwise.
3614///
3615/// Example:
3616/// \code
3617/// %ld = load i32* %addr
3618/// %add = add nuw i32 %ld, 4
3619/// %zext = zext i32 %add to i64
3620/// \endcode
3621/// =>
3622/// \code
3623/// %ld = load i32* %addr
3624/// %zext = zext i32 %ld to i64
3625/// %add = add nuw i64 %zext, 4
3626/// \encode
3627/// Thanks to the promotion, we can match zext(load i32*) to i64.
3628bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3629 LoadInst *&LI, Instruction *&Inst,
3630 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003631 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003632 // Iterate over all the extensions to see if one form an ext(load).
3633 for (auto I : Exts) {
3634 // Check if we directly have ext(load).
3635 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3636 Inst = I;
3637 // No promotion happened here.
3638 return false;
3639 }
3640 // Check whether or not we want to do any promotion.
3641 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3642 continue;
3643 // Get the action to perform the promotion.
3644 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3645 I, InsertedTruncsSet, *TLI, PromotedInsts);
3646 // Check if we can promote.
3647 if (!TPH)
3648 continue;
3649 // Save the current state.
3650 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3651 TPT.getRestorationPoint();
3652 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003653 unsigned NewCreatedInstsCost = 0;
3654 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003655 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003656 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3657 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003658 assert(PromotedVal &&
3659 "TypePromotionHelper should have filtered out those cases");
3660
3661 // We would be able to merge only one extension in a load.
3662 // Therefore, if we have more than 1 new extension we heuristically
3663 // cut this search path, because it means we degrade the code quality.
3664 // With exactly 2, the transformation is neutral, because we will merge
3665 // one extension but leave one. However, we optimistically keep going,
3666 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003667 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3668 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003669 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00003670 (TotalCreatedInstsCost > 1 ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003671 !isPromotedInstructionLegal(*TLI, PromotedVal))) {
3672 // The promotion is not profitable, rollback to the previous state.
3673 TPT.rollback(LastKnownGood);
3674 continue;
3675 }
3676 // The promotion is profitable.
3677 // Check if it exposes an ext(load).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003678 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
3679 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003680 // If we have created a new extension, i.e., now we have two
3681 // extensions. We must make sure one of them is merged with
3682 // the load, otherwise we may degrade the code quality.
3683 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3684 // Promotion happened.
3685 return true;
3686 // If this does not help to expose an ext(load) then, rollback.
3687 TPT.rollback(LastKnownGood);
3688 }
3689 // None of the extension can form an ext(load).
3690 LI = nullptr;
3691 Inst = nullptr;
3692 return false;
3693}
3694
Dan Gohman99429a02009-10-16 20:59:35 +00003695/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3696/// basic block as the load, unless conditions are unfavorable. This allows
3697/// SelectionDAG to fold the extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003698/// \p I[in/out] the extension may be modified during the process if some
3699/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003700///
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003701bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3702 // Try to promote a chain of computation if it allows to form
3703 // an extended load.
3704 TypePromotionTransaction TPT;
3705 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3706 TPT.getRestorationPoint();
3707 SmallVector<Instruction *, 1> Exts;
3708 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003709 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003710 LoadInst *LI = nullptr;
3711 Instruction *OldExt = I;
3712 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3713 if (!LI || !I) {
3714 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3715 "the code must remain the same");
3716 I = OldExt;
3717 return false;
3718 }
Dan Gohman99429a02009-10-16 20:59:35 +00003719
3720 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003721 // Make the cheap checks first if we did not promote.
3722 // If we promoted, we need to check if it is indeed profitable.
3723 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003724 return false;
3725
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003726 EVT VT = TLI->getValueType(I->getType());
3727 EVT LoadVT = TLI->getValueType(LI->getType());
3728
Dan Gohman99429a02009-10-16 20:59:35 +00003729 // If the load has other users and the truncate is not free, this probably
3730 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003731 if (!LI->hasOneUse() && TLI &&
3732 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003733 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3734 I = OldExt;
3735 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003736 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003737 }
Dan Gohman99429a02009-10-16 20:59:35 +00003738
3739 // Check whether the target supports casts folded into loads.
3740 unsigned LType;
3741 if (isa<ZExtInst>(I))
3742 LType = ISD::ZEXTLOAD;
3743 else {
3744 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3745 LType = ISD::SEXTLOAD;
3746 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003747 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003748 I = OldExt;
3749 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003750 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003751 }
Dan Gohman99429a02009-10-16 20:59:35 +00003752
3753 // Move the extend into the same block as the load, so that SelectionDAG
3754 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003755 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003756 I->removeFromParent();
3757 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003758 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003759 return true;
3760}
3761
Evan Chengd3d80172007-12-05 23:58:20 +00003762bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3763 BasicBlock *DefBB = I->getParent();
3764
Bob Wilsonff714f92010-09-21 21:44:14 +00003765 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003766 // other uses of the source with result of extension.
3767 Value *Src = I->getOperand(0);
3768 if (Src->hasOneUse())
3769 return false;
3770
Evan Cheng2011df42007-12-13 07:50:36 +00003771 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003772 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003773 return false;
3774
Evan Cheng7bc89422007-12-12 00:51:06 +00003775 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003776 // this block.
3777 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003778 return false;
3779
Evan Chengd3d80172007-12-05 23:58:20 +00003780 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003781 for (User *U : I->users()) {
3782 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003783
3784 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003785 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003786 if (UserBB == DefBB) continue;
3787 DefIsLiveOut = true;
3788 break;
3789 }
3790 if (!DefIsLiveOut)
3791 return false;
3792
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003793 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003794 for (User *U : Src->users()) {
3795 Instruction *UI = cast<Instruction>(U);
3796 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003797 if (UserBB == DefBB) continue;
3798 // Be conservative. We don't want this xform to end up introducing
3799 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003800 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003801 return false;
3802 }
3803
Evan Chengd3d80172007-12-05 23:58:20 +00003804 // InsertedTruncs - Only insert one trunc in each block once.
3805 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3806
3807 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003808 for (Use &U : Src->uses()) {
3809 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003810
3811 // Figure out which BB this ext is used in.
3812 BasicBlock *UserBB = User->getParent();
3813 if (UserBB == DefBB) continue;
3814
3815 // Both src and def are live in this block. Rewrite the use.
3816 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3817
3818 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003819 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003820 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003821 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003822 }
3823
3824 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003825 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003826 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003827 MadeChange = true;
3828 }
3829
3830 return MadeChange;
3831}
3832
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003833/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3834/// turned into an explicit branch.
3835static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3836 // FIXME: This should use the same heuristics as IfConversion to determine
3837 // whether a select is better represented as a branch. This requires that
3838 // branch probability metadata is preserved for the select, which is not the
3839 // case currently.
3840
3841 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3842
3843 // If the branch is predicted right, an out of order CPU can avoid blocking on
3844 // the compare. Emit cmovs on compares with a memory operand as branches to
3845 // avoid stalls on the load from memory. If the compare has more than one use
3846 // there's probably another cmov or setcc around so it's not worth emitting a
3847 // branch.
3848 if (!Cmp)
3849 return false;
3850
3851 Value *CmpOp0 = Cmp->getOperand(0);
3852 Value *CmpOp1 = Cmp->getOperand(1);
3853
3854 // We check that the memory operand has one use to avoid uses of the loaded
3855 // value directly after the compare, making branches unprofitable.
3856 return Cmp->hasOneUse() &&
3857 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3858 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3859}
3860
3861
Nadav Rotem9d832022012-09-02 12:10:19 +00003862/// If we have a SelectInst that will likely profit from branch prediction,
3863/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003864bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003865 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3866
3867 // Can we convert the 'select' to CF ?
3868 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003869 return false;
3870
Nadav Rotem9d832022012-09-02 12:10:19 +00003871 TargetLowering::SelectSupportKind SelectKind;
3872 if (VectorCond)
3873 SelectKind = TargetLowering::VectorMaskSelect;
3874 else if (SI->getType()->isVectorTy())
3875 SelectKind = TargetLowering::ScalarCondVectorVal;
3876 else
3877 SelectKind = TargetLowering::ScalarValSelect;
3878
3879 // Do we have efficient codegen support for this kind of 'selects' ?
3880 if (TLI->isSelectSupported(SelectKind)) {
3881 // We have efficient codegen support for the select instruction.
3882 // Check if it is profitable to keep this 'select'.
3883 if (!TLI->isPredictableSelectExpensive() ||
3884 !isFormingBranchFromSelectProfitable(SI))
3885 return false;
3886 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003887
3888 ModifiedDT = true;
3889
3890 // First, we split the block containing the select into 2 blocks.
3891 BasicBlock *StartBlock = SI->getParent();
3892 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3893 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3894
3895 // Create a new block serving as the landing pad for the branch.
3896 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3897 NextBlock->getParent(), NextBlock);
3898
3899 // Move the unconditional branch from the block with the select in it into our
3900 // landing pad block.
3901 StartBlock->getTerminator()->eraseFromParent();
3902 BranchInst::Create(NextBlock, SmallBlock);
3903
3904 // Insert the real conditional branch based on the original condition.
3905 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3906
3907 // The select itself is replaced with a PHI Node.
3908 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3909 PN->takeName(SI);
3910 PN->addIncoming(SI->getTrueValue(), StartBlock);
3911 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3912 SI->replaceAllUsesWith(PN);
3913 SI->eraseFromParent();
3914
3915 // Instruct OptimizeBlock to skip to the next block.
3916 CurInstIterator = StartBlock->end();
3917 ++NumSelectsExpanded;
3918 return true;
3919}
3920
Benjamin Kramer573ff362014-03-01 17:24:40 +00003921static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003922 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3923 int SplatElem = -1;
3924 for (unsigned i = 0; i < Mask.size(); ++i) {
3925 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3926 return false;
3927 SplatElem = Mask[i];
3928 }
3929
3930 return true;
3931}
3932
3933/// Some targets have expensive vector shifts if the lanes aren't all the same
3934/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3935/// it's often worth sinking a shufflevector splat down to its use so that
3936/// codegen can spot all lanes are identical.
3937bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3938 BasicBlock *DefBB = SVI->getParent();
3939
3940 // Only do this xform if variable vector shifts are particularly expensive.
3941 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3942 return false;
3943
3944 // We only expect better codegen by sinking a shuffle if we can recognise a
3945 // constant splat.
3946 if (!isBroadcastShuffle(SVI))
3947 return false;
3948
3949 // InsertedShuffles - Only insert a shuffle in each block once.
3950 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3951
3952 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003953 for (User *U : SVI->users()) {
3954 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003955
3956 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003957 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003958 if (UserBB == DefBB) continue;
3959
3960 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003961 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003962
3963 // Everything checks out, sink the shuffle if the user's block doesn't
3964 // already have a copy.
3965 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3966
3967 if (!InsertedShuffle) {
3968 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3969 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3970 SVI->getOperand(1),
3971 SVI->getOperand(2), "", InsertPt);
3972 }
3973
Chandler Carruthcdf47882014-03-09 03:16:01 +00003974 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003975 MadeChange = true;
3976 }
3977
3978 // If we removed all uses, nuke the shuffle.
3979 if (SVI->use_empty()) {
3980 SVI->eraseFromParent();
3981 MadeChange = true;
3982 }
3983
3984 return MadeChange;
3985}
3986
Quentin Colombetc32615d2014-10-31 17:52:53 +00003987namespace {
3988/// \brief Helper class to promote a scalar operation to a vector one.
3989/// This class is used to move downward extractelement transition.
3990/// E.g.,
3991/// a = vector_op <2 x i32>
3992/// b = extractelement <2 x i32> a, i32 0
3993/// c = scalar_op b
3994/// store c
3995///
3996/// =>
3997/// a = vector_op <2 x i32>
3998/// c = vector_op a (equivalent to scalar_op on the related lane)
3999/// * d = extractelement <2 x i32> c, i32 0
4000/// * store d
4001/// Assuming both extractelement and store can be combine, we get rid of the
4002/// transition.
4003class VectorPromoteHelper {
4004 /// Used to perform some checks on the legality of vector operations.
4005 const TargetLowering &TLI;
4006
4007 /// Used to estimated the cost of the promoted chain.
4008 const TargetTransformInfo &TTI;
4009
4010 /// The transition being moved downwards.
4011 Instruction *Transition;
4012 /// The sequence of instructions to be promoted.
4013 SmallVector<Instruction *, 4> InstsToBePromoted;
4014 /// Cost of combining a store and an extract.
4015 unsigned StoreExtractCombineCost;
4016 /// Instruction that will be combined with the transition.
4017 Instruction *CombineInst;
4018
4019 /// \brief The instruction that represents the current end of the transition.
4020 /// Since we are faking the promotion until we reach the end of the chain
4021 /// of computation, we need a way to get the current end of the transition.
4022 Instruction *getEndOfTransition() const {
4023 if (InstsToBePromoted.empty())
4024 return Transition;
4025 return InstsToBePromoted.back();
4026 }
4027
4028 /// \brief Return the index of the original value in the transition.
4029 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4030 /// c, is at index 0.
4031 unsigned getTransitionOriginalValueIdx() const {
4032 assert(isa<ExtractElementInst>(Transition) &&
4033 "Other kind of transitions are not supported yet");
4034 return 0;
4035 }
4036
4037 /// \brief Return the index of the index in the transition.
4038 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4039 /// is at index 1.
4040 unsigned getTransitionIdx() const {
4041 assert(isa<ExtractElementInst>(Transition) &&
4042 "Other kind of transitions are not supported yet");
4043 return 1;
4044 }
4045
4046 /// \brief Get the type of the transition.
4047 /// This is the type of the original value.
4048 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4049 /// transition is <2 x i32>.
4050 Type *getTransitionType() const {
4051 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4052 }
4053
4054 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4055 /// I.e., we have the following sequence:
4056 /// Def = Transition <ty1> a to <ty2>
4057 /// b = ToBePromoted <ty2> Def, ...
4058 /// =>
4059 /// b = ToBePromoted <ty1> a, ...
4060 /// Def = Transition <ty1> ToBePromoted to <ty2>
4061 void promoteImpl(Instruction *ToBePromoted);
4062
4063 /// \brief Check whether or not it is profitable to promote all the
4064 /// instructions enqueued to be promoted.
4065 bool isProfitableToPromote() {
4066 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4067 unsigned Index = isa<ConstantInt>(ValIdx)
4068 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4069 : -1;
4070 Type *PromotedType = getTransitionType();
4071
4072 StoreInst *ST = cast<StoreInst>(CombineInst);
4073 unsigned AS = ST->getPointerAddressSpace();
4074 unsigned Align = ST->getAlignment();
4075 // Check if this store is supported.
4076 if (!TLI.allowsMisalignedMemoryAccesses(
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004077 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004078 // If this is not supported, there is no way we can combine
4079 // the extract with the store.
4080 return false;
4081 }
4082
4083 // The scalar chain of computation has to pay for the transition
4084 // scalar to vector.
4085 // The vector chain has to account for the combining cost.
4086 uint64_t ScalarCost =
4087 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4088 uint64_t VectorCost = StoreExtractCombineCost;
4089 for (const auto &Inst : InstsToBePromoted) {
4090 // Compute the cost.
4091 // By construction, all instructions being promoted are arithmetic ones.
4092 // Moreover, one argument is a constant that can be viewed as a splat
4093 // constant.
4094 Value *Arg0 = Inst->getOperand(0);
4095 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4096 isa<ConstantFP>(Arg0);
4097 TargetTransformInfo::OperandValueKind Arg0OVK =
4098 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4099 : TargetTransformInfo::OK_AnyValue;
4100 TargetTransformInfo::OperandValueKind Arg1OVK =
4101 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4102 : TargetTransformInfo::OK_AnyValue;
4103 ScalarCost += TTI.getArithmeticInstrCost(
4104 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4105 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4106 Arg0OVK, Arg1OVK);
4107 }
4108 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4109 << ScalarCost << "\nVector: " << VectorCost << '\n');
4110 return ScalarCost > VectorCost;
4111 }
4112
4113 /// \brief Generate a constant vector with \p Val with the same
4114 /// number of elements as the transition.
4115 /// \p UseSplat defines whether or not \p Val should be replicated
4116 /// accross the whole vector.
4117 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4118 /// otherwise we generate a vector with as many undef as possible:
4119 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4120 /// used at the index of the extract.
4121 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4122 unsigned ExtractIdx = UINT_MAX;
4123 if (!UseSplat) {
4124 // If we cannot determine where the constant must be, we have to
4125 // use a splat constant.
4126 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4127 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4128 ExtractIdx = CstVal->getSExtValue();
4129 else
4130 UseSplat = true;
4131 }
4132
4133 unsigned End = getTransitionType()->getVectorNumElements();
4134 if (UseSplat)
4135 return ConstantVector::getSplat(End, Val);
4136
4137 SmallVector<Constant *, 4> ConstVec;
4138 UndefValue *UndefVal = UndefValue::get(Val->getType());
4139 for (unsigned Idx = 0; Idx != End; ++Idx) {
4140 if (Idx == ExtractIdx)
4141 ConstVec.push_back(Val);
4142 else
4143 ConstVec.push_back(UndefVal);
4144 }
4145 return ConstantVector::get(ConstVec);
4146 }
4147
4148 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4149 /// in \p Use can trigger undefined behavior.
4150 static bool canCauseUndefinedBehavior(const Instruction *Use,
4151 unsigned OperandIdx) {
4152 // This is not safe to introduce undef when the operand is on
4153 // the right hand side of a division-like instruction.
4154 if (OperandIdx != 1)
4155 return false;
4156 switch (Use->getOpcode()) {
4157 default:
4158 return false;
4159 case Instruction::SDiv:
4160 case Instruction::UDiv:
4161 case Instruction::SRem:
4162 case Instruction::URem:
4163 return true;
4164 case Instruction::FDiv:
4165 case Instruction::FRem:
4166 return !Use->hasNoNaNs();
4167 }
4168 llvm_unreachable(nullptr);
4169 }
4170
4171public:
4172 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
4173 Instruction *Transition, unsigned CombineCost)
4174 : TLI(TLI), TTI(TTI), Transition(Transition),
4175 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4176 assert(Transition && "Do not know how to promote null");
4177 }
4178
4179 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4180 bool canPromote(const Instruction *ToBePromoted) const {
4181 // We could support CastInst too.
4182 return isa<BinaryOperator>(ToBePromoted);
4183 }
4184
4185 /// \brief Check if it is profitable to promote \p ToBePromoted
4186 /// by moving downward the transition through.
4187 bool shouldPromote(const Instruction *ToBePromoted) const {
4188 // Promote only if all the operands can be statically expanded.
4189 // Indeed, we do not want to introduce any new kind of transitions.
4190 for (const Use &U : ToBePromoted->operands()) {
4191 const Value *Val = U.get();
4192 if (Val == getEndOfTransition()) {
4193 // If the use is a division and the transition is on the rhs,
4194 // we cannot promote the operation, otherwise we may create a
4195 // division by zero.
4196 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4197 return false;
4198 continue;
4199 }
4200 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4201 !isa<ConstantFP>(Val))
4202 return false;
4203 }
4204 // Check that the resulting operation is legal.
4205 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4206 if (!ISDOpcode)
4207 return false;
4208 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004209 TLI.isOperationLegalOrCustom(
4210 ISDOpcode, TLI.getValueType(getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004211 }
4212
4213 /// \brief Check whether or not \p Use can be combined
4214 /// with the transition.
4215 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4216 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4217
4218 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4219 void enqueueForPromotion(Instruction *ToBePromoted) {
4220 InstsToBePromoted.push_back(ToBePromoted);
4221 }
4222
4223 /// \brief Set the instruction that will be combined with the transition.
4224 void recordCombineInstruction(Instruction *ToBeCombined) {
4225 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4226 CombineInst = ToBeCombined;
4227 }
4228
4229 /// \brief Promote all the instructions enqueued for promotion if it is
4230 /// is profitable.
4231 /// \return True if the promotion happened, false otherwise.
4232 bool promote() {
4233 // Check if there is something to promote.
4234 // Right now, if we do not have anything to combine with,
4235 // we assume the promotion is not profitable.
4236 if (InstsToBePromoted.empty() || !CombineInst)
4237 return false;
4238
4239 // Check cost.
4240 if (!StressStoreExtract && !isProfitableToPromote())
4241 return false;
4242
4243 // Promote.
4244 for (auto &ToBePromoted : InstsToBePromoted)
4245 promoteImpl(ToBePromoted);
4246 InstsToBePromoted.clear();
4247 return true;
4248 }
4249};
4250} // End of anonymous namespace.
4251
4252void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4253 // At this point, we know that all the operands of ToBePromoted but Def
4254 // can be statically promoted.
4255 // For Def, we need to use its parameter in ToBePromoted:
4256 // b = ToBePromoted ty1 a
4257 // Def = Transition ty1 b to ty2
4258 // Move the transition down.
4259 // 1. Replace all uses of the promoted operation by the transition.
4260 // = ... b => = ... Def.
4261 assert(ToBePromoted->getType() == Transition->getType() &&
4262 "The type of the result of the transition does not match "
4263 "the final type");
4264 ToBePromoted->replaceAllUsesWith(Transition);
4265 // 2. Update the type of the uses.
4266 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4267 Type *TransitionTy = getTransitionType();
4268 ToBePromoted->mutateType(TransitionTy);
4269 // 3. Update all the operands of the promoted operation with promoted
4270 // operands.
4271 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4272 for (Use &U : ToBePromoted->operands()) {
4273 Value *Val = U.get();
4274 Value *NewVal = nullptr;
4275 if (Val == Transition)
4276 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4277 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4278 isa<ConstantFP>(Val)) {
4279 // Use a splat constant if it is not safe to use undef.
4280 NewVal = getConstantVector(
4281 cast<Constant>(Val),
4282 isa<UndefValue>(Val) ||
4283 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4284 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004285 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4286 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004287 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4288 }
4289 Transition->removeFromParent();
4290 Transition->insertAfter(ToBePromoted);
4291 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4292}
4293
4294/// Some targets can do store(extractelement) with one instruction.
4295/// Try to push the extractelement towards the stores when the target
4296/// has this feature and this is profitable.
4297bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4298 unsigned CombineCost = UINT_MAX;
4299 if (DisableStoreExtract || !TLI ||
4300 (!StressStoreExtract &&
4301 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4302 Inst->getOperand(1), CombineCost)))
4303 return false;
4304
4305 // At this point we know that Inst is a vector to scalar transition.
4306 // Try to move it down the def-use chain, until:
4307 // - We can combine the transition with its single use
4308 // => we got rid of the transition.
4309 // - We escape the current basic block
4310 // => we would need to check that we are moving it at a cheaper place and
4311 // we do not do that for now.
4312 BasicBlock *Parent = Inst->getParent();
4313 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4314 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
4315 // If the transition has more than one use, assume this is not going to be
4316 // beneficial.
4317 while (Inst->hasOneUse()) {
4318 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4319 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4320
4321 if (ToBePromoted->getParent() != Parent) {
4322 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4323 << ToBePromoted->getParent()->getName()
4324 << ") than the transition (" << Parent->getName() << ").\n");
4325 return false;
4326 }
4327
4328 if (VPH.canCombine(ToBePromoted)) {
4329 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4330 << "will be combined with: " << *ToBePromoted << '\n');
4331 VPH.recordCombineInstruction(ToBePromoted);
4332 bool Changed = VPH.promote();
4333 NumStoreExtractExposed += Changed;
4334 return Changed;
4335 }
4336
4337 DEBUG(dbgs() << "Try promoting.\n");
4338 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4339 return false;
4340
4341 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4342
4343 VPH.enqueueForPromotion(ToBePromoted);
4344 Inst = ToBePromoted;
4345 }
4346 return false;
4347}
4348
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004349bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004350 if (PHINode *P = dyn_cast<PHINode>(I)) {
4351 // It is possible for very late stage optimizations (such as SimplifyCFG)
4352 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4353 // trivial PHI, go ahead and zap it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004354 const DataLayout &DL = I->getModule()->getDataLayout();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00004355 if (Value *V = SimplifyInstruction(P, DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004356 P->replaceAllUsesWith(V);
4357 P->eraseFromParent();
4358 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004359 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004360 }
Chris Lattneree588de2011-01-15 07:29:01 +00004361 return false;
4362 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004363
Chris Lattneree588de2011-01-15 07:29:01 +00004364 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004365 // If the source of the cast is a constant, then this should have
4366 // already been constant folded. The only reason NOT to constant fold
4367 // it is if something (e.g. LSR) was careful to place the constant
4368 // evaluation in a block other than then one that uses it (e.g. to hoist
4369 // the address of globals out of a loop). If this is the case, we don't
4370 // want to forward-subst the cast.
4371 if (isa<Constant>(CI->getOperand(0)))
4372 return false;
4373
Chris Lattneree588de2011-01-15 07:29:01 +00004374 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
4375 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004376
Chris Lattneree588de2011-01-15 07:29:01 +00004377 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004378 /// Sink a zext or sext into its user blocks if the target type doesn't
4379 /// fit in one register
4380 if (TLI && TLI->getTypeAction(CI->getContext(),
4381 TLI->getValueType(CI->getType())) ==
4382 TargetLowering::TypeExpandInteger) {
4383 return SinkCast(CI);
4384 } else {
4385 bool MadeChange = MoveExtToFormExtLoad(I);
4386 return MadeChange | OptimizeExtUses(I);
4387 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004388 }
Chris Lattneree588de2011-01-15 07:29:01 +00004389 return false;
4390 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004391
Chris Lattneree588de2011-01-15 07:29:01 +00004392 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004393 if (!TLI || !TLI->hasMultipleConditionRegisters())
4394 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004395
Chris Lattneree588de2011-01-15 07:29:01 +00004396 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004397 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00004398 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
4399 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004400 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004401
Chris Lattneree588de2011-01-15 07:29:01 +00004402 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004403 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00004404 return OptimizeMemoryInst(I, SI->getOperand(1),
4405 SI->getOperand(0)->getType());
4406 return false;
4407 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004408
Yi Jiangd069f632014-04-21 19:34:27 +00004409 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4410
4411 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4412 BinOp->getOpcode() == Instruction::LShr)) {
4413 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4414 if (TLI && CI && TLI->hasExtractBitsInsn())
4415 return OptimizeExtractBits(BinOp, CI, *TLI);
4416
4417 return false;
4418 }
4419
Chris Lattneree588de2011-01-15 07:29:01 +00004420 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004421 if (GEPI->hasAllZeroIndices()) {
4422 /// The GEP operand must be a pointer, so must its result -> BitCast
4423 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4424 GEPI->getName(), GEPI);
4425 GEPI->replaceAllUsesWith(NC);
4426 GEPI->eraseFromParent();
4427 ++NumGEPsElim;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004428 OptimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004429 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004430 }
Chris Lattneree588de2011-01-15 07:29:01 +00004431 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004432 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004433
Chris Lattneree588de2011-01-15 07:29:01 +00004434 if (CallInst *CI = dyn_cast<CallInst>(I))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004435 return OptimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004436
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004437 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4438 return OptimizeSelectInst(SI);
4439
Tim Northoveraeb8e062014-02-19 10:02:43 +00004440 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4441 return OptimizeShuffleVectorInst(SVI);
4442
Quentin Colombetc32615d2014-10-31 17:52:53 +00004443 if (isa<ExtractElementInst>(I))
4444 return OptimizeExtractElementInst(I);
4445
Chris Lattneree588de2011-01-15 07:29:01 +00004446 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004447}
4448
Chris Lattnerf2836d12007-03-31 04:06:36 +00004449// In this pass we look for GEP and cast instructions that are used
4450// across basic blocks and rewrite them to improve basic-block-at-a-time
4451// selection.
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004452bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004453 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004454 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004455
Chris Lattner7a277142011-01-15 07:14:54 +00004456 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004457 while (CurInstIterator != BB.end()) {
4458 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4459 if (ModifiedDT)
4460 return true;
4461 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00004462 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4463
Chris Lattnerf2836d12007-03-31 04:06:36 +00004464 return MadeChange;
4465}
Devang Patel53771ba2011-08-18 00:50:51 +00004466
4467// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004468// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004469// find a node corresponding to the value.
4470bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4471 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004472 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004473 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004474 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithe90f1162015-01-08 21:07:55 +00004475 Instruction *Insn = BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00004476 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004477 // Leave dbg.values that refer to an alloca alone. These
4478 // instrinsics describe the address of a variable (= the alloca)
4479 // being taken. They should not be moved next to the alloca
4480 // (and to the beginning of the scope), but rather stay close to
4481 // where said address is used.
4482 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004483 PrevNonDbgInst = Insn;
4484 continue;
4485 }
4486
4487 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4488 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4489 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4490 DVI->removeFromParent();
4491 if (isa<PHINode>(VI))
4492 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4493 else
4494 DVI->insertAfter(VI);
4495 MadeChange = true;
4496 ++NumDbgValueMoved;
4497 }
4498 }
4499 }
4500 return MadeChange;
4501}
Tim Northovercea0abb2014-03-29 08:22:29 +00004502
4503// If there is a sequence that branches based on comparing a single bit
4504// against zero that can be combined into a single instruction, and the
4505// target supports folding these into a single instruction, sink the
4506// mask and compare into the branch uses. Do this before OptimizeBlock ->
4507// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4508// searched for.
4509bool CodeGenPrepare::sinkAndCmp(Function &F) {
4510 if (!EnableAndCmpSinking)
4511 return false;
4512 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4513 return false;
4514 bool MadeChange = false;
4515 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4516 BasicBlock *BB = I++;
4517
4518 // Does this BB end with the following?
4519 // %andVal = and %val, #single-bit-set
4520 // %icmpVal = icmp %andResult, 0
4521 // br i1 %cmpVal label %dest1, label %dest2"
4522 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4523 if (!Brcc || !Brcc->isConditional())
4524 continue;
4525 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4526 if (!Cmp || Cmp->getParent() != BB)
4527 continue;
4528 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4529 if (!Zero || !Zero->isZero())
4530 continue;
4531 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4532 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4533 continue;
4534 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4535 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4536 continue;
4537 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4538
4539 // Push the "and; icmp" for any users that are conditional branches.
4540 // Since there can only be one branch use per BB, we don't need to keep
4541 // track of which BBs we insert into.
4542 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4543 UI != E; ) {
4544 Use &TheUse = *UI;
4545 // Find brcc use.
4546 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4547 ++UI;
4548 if (!BrccUser || !BrccUser->isConditional())
4549 continue;
4550 BasicBlock *UserBB = BrccUser->getParent();
4551 if (UserBB == BB) continue;
4552 DEBUG(dbgs() << "found Brcc use\n");
4553
4554 // Sink the "and; icmp" to use.
4555 MadeChange = true;
4556 BinaryOperator *NewAnd =
4557 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4558 BrccUser);
4559 CmpInst *NewCmp =
4560 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4561 "", BrccUser);
4562 TheUse = NewCmp;
4563 ++NumAndCmpsMoved;
4564 DEBUG(BrccUser->getParent()->dump());
4565 }
4566 }
4567 return MadeChange;
4568}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004569
Juergen Ributzka194350a2014-12-09 17:32:12 +00004570/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4571/// success, or returns false if no or invalid metadata was found.
4572static bool extractBranchMetadata(BranchInst *BI,
4573 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4574 assert(BI->isConditional() &&
4575 "Looking for probabilities on unconditional branch?");
4576 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4577 if (!ProfileData || ProfileData->getNumOperands() != 3)
4578 return false;
4579
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004580 const auto *CITrue =
4581 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4582 const auto *CIFalse =
4583 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004584 if (!CITrue || !CIFalse)
4585 return false;
4586
4587 ProbTrue = CITrue->getValue().getZExtValue();
4588 ProbFalse = CIFalse->getValue().getZExtValue();
4589
4590 return true;
4591}
4592
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004593/// \brief Scale down both weights to fit into uint32_t.
4594static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4595 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4596 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4597 NewTrue = NewTrue / Scale;
4598 NewFalse = NewFalse / Scale;
4599}
4600
4601/// \brief Some targets prefer to split a conditional branch like:
4602/// \code
4603/// %0 = icmp ne i32 %a, 0
4604/// %1 = icmp ne i32 %b, 0
4605/// %or.cond = or i1 %0, %1
4606/// br i1 %or.cond, label %TrueBB, label %FalseBB
4607/// \endcode
4608/// into multiple branch instructions like:
4609/// \code
4610/// bb1:
4611/// %0 = icmp ne i32 %a, 0
4612/// br i1 %0, label %TrueBB, label %bb2
4613/// bb2:
4614/// %1 = icmp ne i32 %b, 0
4615/// br i1 %1, label %TrueBB, label %FalseBB
4616/// \endcode
4617/// This usually allows instruction selection to do even further optimizations
4618/// and combine the compare with the branch instruction. Currently this is
4619/// applied for targets which have "cheap" jump instructions.
4620///
4621/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4622///
4623bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00004624 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004625 return false;
4626
4627 bool MadeChange = false;
4628 for (auto &BB : F) {
4629 // Does this BB end with the following?
4630 // %cond1 = icmp|fcmp|binary instruction ...
4631 // %cond2 = icmp|fcmp|binary instruction ...
4632 // %cond.or = or|and i1 %cond1, cond2
4633 // br i1 %cond.or label %dest1, label %dest2"
4634 BinaryOperator *LogicOp;
4635 BasicBlock *TBB, *FBB;
4636 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4637 continue;
4638
4639 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004640 Value *Cond1, *Cond2;
4641 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4642 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004643 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004644 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4645 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004646 Opc = Instruction::Or;
4647 else
4648 continue;
4649
4650 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4651 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4652 continue;
4653
4654 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4655
4656 // Create a new BB.
4657 auto *InsertBefore = std::next(Function::iterator(BB))
4658 .getNodePtrUnchecked();
4659 auto TmpBB = BasicBlock::Create(BB.getContext(),
4660 BB.getName() + ".cond.split",
4661 BB.getParent(), InsertBefore);
4662
4663 // Update original basic block by using the first condition directly by the
4664 // branch instruction and removing the no longer needed and/or instruction.
4665 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4666 Br1->setCondition(Cond1);
4667 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004668
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004669 // Depending on the conditon we have to either replace the true or the false
4670 // successor of the original branch instruction.
4671 if (Opc == Instruction::And)
4672 Br1->setSuccessor(0, TmpBB);
4673 else
4674 Br1->setSuccessor(1, TmpBB);
4675
4676 // Fill in the new basic block.
4677 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004678 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4679 I->removeFromParent();
4680 I->insertBefore(Br2);
4681 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004682
4683 // Update PHI nodes in both successors. The original BB needs to be
4684 // replaced in one succesor's PHI nodes, because the branch comes now from
4685 // the newly generated BB (NewBB). In the other successor we need to add one
4686 // incoming edge to the PHI nodes, because both branch instructions target
4687 // now the same successor. Depending on the original branch condition
4688 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4689 // we perfrom the correct update for the PHI nodes.
4690 // This doesn't change the successor order of the just created branch
4691 // instruction (or any other instruction).
4692 if (Opc == Instruction::Or)
4693 std::swap(TBB, FBB);
4694
4695 // Replace the old BB with the new BB.
4696 for (auto &I : *TBB) {
4697 PHINode *PN = dyn_cast<PHINode>(&I);
4698 if (!PN)
4699 break;
4700 int i;
4701 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4702 PN->setIncomingBlock(i, TmpBB);
4703 }
4704
4705 // Add another incoming edge form the new BB.
4706 for (auto &I : *FBB) {
4707 PHINode *PN = dyn_cast<PHINode>(&I);
4708 if (!PN)
4709 break;
4710 auto *Val = PN->getIncomingValueForBlock(&BB);
4711 PN->addIncoming(Val, TmpBB);
4712 }
4713
4714 // Update the branch weights (from SelectionDAGBuilder::
4715 // FindMergedConditions).
4716 if (Opc == Instruction::Or) {
4717 // Codegen X | Y as:
4718 // BB1:
4719 // jmp_if_X TBB
4720 // jmp TmpBB
4721 // TmpBB:
4722 // jmp_if_Y TBB
4723 // jmp FBB
4724 //
4725
4726 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4727 // The requirement is that
4728 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4729 // = TrueProb for orignal BB.
4730 // Assuming the orignal weights are A and B, one choice is to set BB1's
4731 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4732 // assumes that
4733 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4734 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4735 // TmpBB, but the math is more complicated.
4736 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004737 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004738 uint64_t NewTrueWeight = TrueWeight;
4739 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4740 scaleWeights(NewTrueWeight, NewFalseWeight);
4741 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4742 .createBranchWeights(TrueWeight, FalseWeight));
4743
4744 NewTrueWeight = TrueWeight;
4745 NewFalseWeight = 2 * FalseWeight;
4746 scaleWeights(NewTrueWeight, NewFalseWeight);
4747 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4748 .createBranchWeights(TrueWeight, FalseWeight));
4749 }
4750 } else {
4751 // Codegen X & Y as:
4752 // BB1:
4753 // jmp_if_X TmpBB
4754 // jmp FBB
4755 // TmpBB:
4756 // jmp_if_Y TBB
4757 // jmp FBB
4758 //
4759 // This requires creation of TmpBB after CurBB.
4760
4761 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4762 // The requirement is that
4763 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4764 // = FalseProb for orignal BB.
4765 // Assuming the orignal weights are A and B, one choice is to set BB1's
4766 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4767 // assumes that
4768 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4769 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004770 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004771 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4772 uint64_t NewFalseWeight = FalseWeight;
4773 scaleWeights(NewTrueWeight, NewFalseWeight);
4774 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4775 .createBranchWeights(TrueWeight, FalseWeight));
4776
4777 NewTrueWeight = 2 * TrueWeight;
4778 NewFalseWeight = FalseWeight;
4779 scaleWeights(NewTrueWeight, NewFalseWeight);
4780 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4781 .createBranchWeights(TrueWeight, FalseWeight));
4782 }
4783 }
4784
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004785 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00004786 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004787 ModifiedDT = true;
4788
4789 MadeChange = true;
4790
4791 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4792 TmpBB->dump());
4793 }
4794 return MadeChange;
4795}