blob: 7550df278e5d7cefe69a8dec2bc5b2ff1e6eb39c [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"
Quentin Colombetc32615d2014-10-31 17:52:53 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000022#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InlineAsm.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000033#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000034#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000035#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000036#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000037#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000038#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000039#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000040#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000041#include "llvm/Target/TargetLibraryInfo.h"
42#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000043#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000046#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000048using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000049using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000050
Chandler Carruth1b9dde02014-04-22 02:02:50 +000051#define DEBUG_TYPE "codegenprepare"
52
Cameron Zwarichced753f2011-01-05 17:27:27 +000053STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000054STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
55STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000056STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
57 "sunken Cmps");
58STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
59 "of sunken Casts");
60STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
61 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000062STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
63STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
64STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000065STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000066STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000067STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000068STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000069
Cameron Zwarich338d3622011-03-11 21:52:04 +000070static cl::opt<bool> DisableBranchOpts(
71 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
72 cl::desc("Disable branch optimizations in CodeGenPrepare"));
73
Benjamin Kramer3d38c172012-05-06 14:25:16 +000074static cl::opt<bool> DisableSelectToBranch(
75 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000077
Hal Finkelc3998302014-04-12 00:59:48 +000078static cl::opt<bool> AddrSinkUsingGEPs(
79 "addr-sink-using-gep", cl::Hidden, cl::init(false),
80 cl::desc("Address sinking in CGP using GEPs."));
81
Tim Northovercea0abb2014-03-29 08:22:29 +000082static cl::opt<bool> EnableAndCmpSinking(
83 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
84 cl::desc("Enable sinkinig and/cmp into branches."));
85
Quentin Colombetc32615d2014-10-31 17:52:53 +000086static cl::opt<bool> DisableStoreExtract(
87 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
88 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
89
90static cl::opt<bool> StressStoreExtract(
91 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
92 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
93
Quentin Colombetfc2201e2014-12-17 01:36:17 +000094static cl::opt<bool> DisableExtLdPromotion(
95 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
96 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
97 "CodeGenPrepare"));
98
99static cl::opt<bool> StressExtLdPromotion(
100 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
101 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
102 "optimization in CodeGenPrepare"));
103
Eric Christopherc1ea1492008-09-24 05:32:41 +0000104namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000105typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000106struct TypeIsSExt {
107 Type *Ty;
108 bool IsSExt;
109 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
110};
111typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000112class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000113
Chris Lattner2dd09db2009-09-02 06:11:42 +0000114 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000115 /// TLI - Keep a pointer of a TargetLowering to consult for determining
116 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000117 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000118 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000119 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000120 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +0000121 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +0000122
Chris Lattner7a277142011-01-15 07:14:54 +0000123 /// CurInstIterator - As we scan instructions optimizing them, this is the
124 /// next instruction to optimize. Xforms that can invalidate this should
125 /// update it.
126 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000127
Evan Cheng0663f232011-03-21 01:19:09 +0000128 /// Keeps track of non-local addresses that have been sunk into a block.
129 /// This allows us to avoid inserting duplicate code for blocks with
130 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000131 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000132
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000133 /// Keeps track of all truncates inserted for the current function.
134 SetOfInstrs InsertedTruncsSet;
135 /// Keeps track of the type of the related instruction before their
136 /// promotion for the current function.
137 InstrToOrigTy PromotedInsts;
138
Devang Patel8f606d72011-03-24 15:35:25 +0000139 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000140 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000141 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000142
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000143 /// OptSize - True if optimizing for size.
144 bool OptSize;
145
Chris Lattnerf2836d12007-03-31 04:06:36 +0000146 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000147 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000148 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Quentin Colombetc32615d2014-10-31 17:52:53 +0000149 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000150 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
151 }
Craig Topper4584cd52014-03-07 09:26:03 +0000152 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000153
Craig Topper4584cd52014-03-07 09:26:03 +0000154 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000155
Craig Topper4584cd52014-03-07 09:26:03 +0000156 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000157 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000158 AU.addRequired<TargetLibraryInfo>();
Quentin Colombetc32615d2014-10-31 17:52:53 +0000159 AU.addRequired<TargetTransformInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000160 }
161
Chris Lattnerf2836d12007-03-31 04:06:36 +0000162 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000163 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000164 bool EliminateMostlyEmptyBlocks(Function &F);
165 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
166 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000167 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
168 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
Chris Lattner229907c2011-07-18 04:54:35 +0000169 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000170 bool OptimizeInlineAsmInst(CallInst *CS);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000171 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000172 bool MoveExtToFormExtLoad(Instruction *&I);
Evan Chengd3d80172007-12-05 23:58:20 +0000173 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000174 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000175 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000176 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000177 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000178 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000179 bool sinkAndCmp(Function &F);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000180 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
181 Instruction *&Inst,
182 const SmallVectorImpl<Instruction *> &Exts,
183 unsigned CreatedInst);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000184 bool splitBranchCondition(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000185 };
186}
Devang Patel09f162c2007-05-01 21:15:47 +0000187
Devang Patel8c78a0b2007-05-03 01:11:54 +0000188char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000189INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
190 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000191
Bill Wendling7a639ea2013-06-19 21:07:11 +0000192FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
193 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000194}
195
Chris Lattnerf2836d12007-03-31 04:06:36 +0000196bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000197 if (skipOptnoneFunction(F))
198 return false;
199
Chris Lattnerf2836d12007-03-31 04:06:36 +0000200 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000201 // Clear per function information.
202 InsertedTruncsSet.clear();
203 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000204
Devang Patel8f606d72011-03-24 15:35:25 +0000205 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000206 if (TM)
207 TLI = TM->getSubtargetImpl()->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000208 TLInfo = &getAnalysis<TargetLibraryInfo>();
Quentin Colombetc32615d2014-10-31 17:52:53 +0000209 TTI = &getAnalysis<TargetTransformInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000210 DominatorTreeWrapperPass *DTWP =
211 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000212 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Bill Wendling698e84f2012-12-30 10:32:01 +0000213 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
214 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000215
Preston Gurdcdf540d2012-09-04 18:22:17 +0000216 /// This optimization identifies DIV instructions that can be
217 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000218 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000219 const DenseMap<unsigned int, unsigned int> &BypassWidths =
220 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000221 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000222 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000223 }
224
225 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000226 // unconditional branch.
227 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000228
Devang Patel53771ba2011-08-18 00:50:51 +0000229 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000230 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000231 // find a node corresponding to the value.
232 EverMadeChange |= PlaceDbgValues(F);
233
Tim Northovercea0abb2014-03-29 08:22:29 +0000234 // If there is a mask, compare against zero, and branch that can be combined
235 // into a single target instruction, push the mask and compare into branch
236 // users. Do this before OptimizeBlock -> OptimizeInst ->
237 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000238 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000239 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000240 EverMadeChange |= splitBranchCondition(F);
241 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000242
Chris Lattnerc3748562007-04-02 01:35:34 +0000243 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000244 while (MadeChange) {
245 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000246 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000247 BasicBlock *BB = I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000248 bool ModifiedDTOnIteration = false;
249 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
250
251 // Restart BB iteration if the dominator tree of the Function was changed
252 ModifiedDT |= ModifiedDTOnIteration;
253 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
Evan Cheng0663f232011-03-21 01:19:09 +0000295 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000296 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000297 EverMadeChange |= MadeChange;
298 }
299
Devang Patel8f606d72011-03-24 15:35:25 +0000300 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000301 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000302
Chris Lattnerf2836d12007-03-31 04:06:36 +0000303 return EverMadeChange;
304}
305
Nadav Rotem70409992012-08-14 05:19:07 +0000306/// EliminateFallThrough - Merge basic blocks which are connected
307/// by a single edge, where one of the basic blocks has a single successor
308/// pointing to the other basic block, which has a single predecessor.
309bool CodeGenPrepare::EliminateFallThrough(Function &F) {
310 bool Changed = false;
311 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000312 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000313 BasicBlock *BB = I++;
314 // If the destination block has a single pred, then this is a trivial
315 // edge, just collapse it.
316 BasicBlock *SinglePred = BB->getSinglePredecessor();
317
Evan Cheng64a223a2012-09-28 23:58:57 +0000318 // Don't merge if BB's address is taken.
319 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000320
321 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
322 if (Term && !Term->isConditional()) {
323 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000324 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000325 // Remember if SinglePred was the entry block of the function.
326 // If so, we will need to move BB back to the entry position.
327 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
328 MergeBasicBlockIntoOnlyPred(BB, this);
329
330 if (isEntry && BB != &BB->getParent()->getEntryBlock())
331 BB->moveBefore(&BB->getParent()->getEntryBlock());
332
333 // We have erased a block. Update the iterator.
334 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000335 }
336 }
337 return Changed;
338}
339
Dale Johannesen4026b042009-03-27 01:13:37 +0000340/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
341/// debug info directives, and an unconditional branch. Passes before isel
342/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
343/// isel. Start by eliminating these blocks so we can split them the way we
344/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000345bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
346 bool MadeChange = false;
347 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000348 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000349 BasicBlock *BB = I++;
350
351 // If this block doesn't end with an uncond branch, ignore it.
352 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
353 if (!BI || !BI->isUnconditional())
354 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000355
Dale Johannesen4026b042009-03-27 01:13:37 +0000356 // If the instruction before the branch (skipping debug info) isn't a phi
357 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000358 BasicBlock::iterator BBI = BI;
359 if (BBI != BB->begin()) {
360 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000361 while (isa<DbgInfoIntrinsic>(BBI)) {
362 if (BBI == BB->begin())
363 break;
364 --BBI;
365 }
366 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
367 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000368 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000369
Chris Lattnerc3748562007-04-02 01:35:34 +0000370 // Do not break infinite loops.
371 BasicBlock *DestBB = BI->getSuccessor(0);
372 if (DestBB == BB)
373 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000374
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 if (!CanMergeBlocks(BB, DestBB))
376 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000377
Chris Lattnerc3748562007-04-02 01:35:34 +0000378 EliminateMostlyEmptyBlock(BB);
379 MadeChange = true;
380 }
381 return MadeChange;
382}
383
384/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
385/// single uncond branch between them, and BB contains no other non-phi
386/// instructions.
387bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
388 const BasicBlock *DestBB) const {
389 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
390 // the successor. If there are more complex condition (e.g. preheaders),
391 // don't mess around with them.
392 BasicBlock::const_iterator BBI = BB->begin();
393 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000394 for (const User *U : PN->users()) {
395 const Instruction *UI = cast<Instruction>(U);
396 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000397 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000398 // If User is inside DestBB block and it is a PHINode then check
399 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000400 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000401 if (UI->getParent() == DestBB) {
402 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000403 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
404 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
405 if (Insn && Insn->getParent() == BB &&
406 Insn->getParent() != UPN->getIncomingBlock(I))
407 return false;
408 }
409 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000410 }
411 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000412
Chris Lattnerc3748562007-04-02 01:35:34 +0000413 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
414 // and DestBB may have conflicting incoming values for the block. If so, we
415 // can't merge the block.
416 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
417 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000418
Chris Lattnerc3748562007-04-02 01:35:34 +0000419 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000420 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000421 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
422 // It is faster to get preds from a PHI than with pred_iterator.
423 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
424 BBPreds.insert(BBPN->getIncomingBlock(i));
425 } else {
426 BBPreds.insert(pred_begin(BB), pred_end(BB));
427 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000428
Chris Lattnerc3748562007-04-02 01:35:34 +0000429 // Walk the preds of DestBB.
430 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
431 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
432 if (BBPreds.count(Pred)) { // Common predecessor?
433 BBI = DestBB->begin();
434 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
435 const Value *V1 = PN->getIncomingValueForBlock(Pred);
436 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000437
Chris Lattnerc3748562007-04-02 01:35:34 +0000438 // If V2 is a phi node in BB, look up what the mapped value will be.
439 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
440 if (V2PN->getParent() == BB)
441 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442
Chris Lattnerc3748562007-04-02 01:35:34 +0000443 // If there is a conflict, bail out.
444 if (V1 != V2) return false;
445 }
446 }
447 }
448
449 return true;
450}
451
452
453/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
454/// an unconditional branch in it.
455void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
456 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
457 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000458
David Greene74e2d492010-01-05 01:27:11 +0000459 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000460
Chris Lattnerc3748562007-04-02 01:35:34 +0000461 // If the destination block has a single pred, then this is a trivial edge,
462 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000463 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000464 if (SinglePred != DestBB) {
465 // Remember if SinglePred was the entry block of the function. If so, we
466 // will need to move BB back to the entry position.
467 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000468 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000469
Chris Lattner8a172da2008-11-28 19:54:49 +0000470 if (isEntry && BB != &BB->getParent()->getEntryBlock())
471 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000472
David Greene74e2d492010-01-05 01:27:11 +0000473 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000474 return;
475 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000476 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000477
Chris Lattnerc3748562007-04-02 01:35:34 +0000478 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
479 // to handle the new incoming edges it is about to have.
480 PHINode *PN;
481 for (BasicBlock::iterator BBI = DestBB->begin();
482 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
483 // Remove the incoming value for BB, and remember it.
484 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000485
Chris Lattnerc3748562007-04-02 01:35:34 +0000486 // Two options: either the InVal is a phi node defined in BB or it is some
487 // value that dominates BB.
488 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
489 if (InValPhi && InValPhi->getParent() == BB) {
490 // Add all of the input values of the input PHI as inputs of this phi.
491 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
492 PN->addIncoming(InValPhi->getIncomingValue(i),
493 InValPhi->getIncomingBlock(i));
494 } else {
495 // Otherwise, add one instance of the dominating value for each edge that
496 // we will be adding.
497 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
498 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
499 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
500 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000501 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
502 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000503 }
504 }
505 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000506
Chris Lattnerc3748562007-04-02 01:35:34 +0000507 // The PHIs are now updated, change everything that refers to BB to use
508 // DestBB and remove BB.
509 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000510 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000511 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
512 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
513 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
514 DT->changeImmediateDominator(DestBB, NewIDom);
515 DT->eraseNode(BB);
516 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000517 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000518 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000519
David Greene74e2d492010-01-05 01:27:11 +0000520 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000521}
522
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000523/// SinkCast - Sink the specified cast instruction into its user blocks
524static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000525 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000526
Chris Lattnerf2836d12007-03-31 04:06:36 +0000527 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000528 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000529
Chris Lattnerf2836d12007-03-31 04:06:36 +0000530 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000531 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000532 UI != E; ) {
533 Use &TheUse = UI.getUse();
534 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000535
Chris Lattnerf2836d12007-03-31 04:06:36 +0000536 // Figure out which BB this cast is used in. For PHI's this is the
537 // appropriate predecessor block.
538 BasicBlock *UserBB = User->getParent();
539 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000540 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000541 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000542
Chris Lattnerf2836d12007-03-31 04:06:36 +0000543 // Preincrement use iterator so we don't invalidate it.
544 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000545
Chris Lattnerf2836d12007-03-31 04:06:36 +0000546 // If this user is in the same block as the cast, don't change the cast.
547 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000548
Chris Lattnerf2836d12007-03-31 04:06:36 +0000549 // If we have already inserted a cast into this block, use it.
550 CastInst *&InsertedCast = InsertedCasts[UserBB];
551
552 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000553 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000554 InsertedCast =
555 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000556 InsertPt);
557 MadeChange = true;
558 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000559
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000560 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000561 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000562 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000563 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000564
Chris Lattnerf2836d12007-03-31 04:06:36 +0000565 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000566 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000567 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000568 MadeChange = true;
569 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000570
Chris Lattnerf2836d12007-03-31 04:06:36 +0000571 return MadeChange;
572}
573
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000574/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
575/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
576/// sink it into user blocks to reduce the number of virtual
577/// registers that must be created and coalesced.
578///
579/// Return true if any changes are made.
580///
581static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
582 // If this is a noop copy,
583 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
584 EVT DstVT = TLI.getValueType(CI->getType());
585
586 // This is an fp<->int conversion?
587 if (SrcVT.isInteger() != DstVT.isInteger())
588 return false;
589
590 // If this is an extension, it will be a zero or sign extension, which
591 // isn't a noop.
592 if (SrcVT.bitsLT(DstVT)) return false;
593
594 // If these values will be promoted, find out what they will be promoted
595 // to. This helps us consider truncates on PPC as noop copies when they
596 // are.
597 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
598 TargetLowering::TypePromoteInteger)
599 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
600 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
601 TargetLowering::TypePromoteInteger)
602 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
603
604 // If, after promotion, these are the same types, this is a noop copy.
605 if (SrcVT != DstVT)
606 return false;
607
608 return SinkCast(CI);
609}
610
Eric Christopherc1ea1492008-09-24 05:32:41 +0000611/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000612/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000613/// a clear win except on targets with multiple condition code registers
614/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000615///
616/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000617static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000618 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000619
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000620 /// InsertedCmp - Only insert a cmp in each block once.
621 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000622
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000623 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000624 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000625 UI != E; ) {
626 Use &TheUse = UI.getUse();
627 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000628
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000629 // Preincrement use iterator so we don't invalidate it.
630 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000631
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000632 // Don't bother for PHI nodes.
633 if (isa<PHINode>(User))
634 continue;
635
636 // Figure out which BB this cmp is used in.
637 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000638
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000639 // If this user is in the same block as the cmp, don't change the cmp.
640 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000641
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000642 // If we have already inserted a cmp into this block, use it.
643 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
644
645 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000646 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000647 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000648 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000649 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000650 CI->getOperand(1), "", InsertPt);
651 MadeChange = true;
652 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000653
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000654 // Replace a use of the cmp with a use of the new cmp.
655 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000656 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000657 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000658
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000659 // If we removed all uses, nuke the cmp.
660 if (CI->use_empty())
661 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000662
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000663 return MadeChange;
664}
665
Yi Jiangd069f632014-04-21 19:34:27 +0000666/// isExtractBitsCandidateUse - Check if the candidates could
667/// be combined with shift instruction, which includes:
668/// 1. Truncate instruction
669/// 2. And instruction and the imm is a mask of the low bits:
670/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000671static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000672 if (!isa<TruncInst>(User)) {
673 if (User->getOpcode() != Instruction::And ||
674 !isa<ConstantInt>(User->getOperand(1)))
675 return false;
676
Quentin Colombetd4f44692014-04-22 01:20:34 +0000677 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000678
Quentin Colombetd4f44692014-04-22 01:20:34 +0000679 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000680 return false;
681 }
682 return true;
683}
684
685/// SinkShiftAndTruncate - sink both shift and truncate instruction
686/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000687static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000688SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
689 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
690 const TargetLowering &TLI) {
691 BasicBlock *UserBB = User->getParent();
692 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
693 TruncInst *TruncI = dyn_cast<TruncInst>(User);
694 bool MadeChange = false;
695
696 for (Value::user_iterator TruncUI = TruncI->user_begin(),
697 TruncE = TruncI->user_end();
698 TruncUI != TruncE;) {
699
700 Use &TruncTheUse = TruncUI.getUse();
701 Instruction *TruncUser = cast<Instruction>(*TruncUI);
702 // Preincrement use iterator so we don't invalidate it.
703
704 ++TruncUI;
705
706 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
707 if (!ISDOpcode)
708 continue;
709
Tim Northovere2239ff2014-07-29 10:20:22 +0000710 // If the use is actually a legal node, there will not be an
711 // implicit truncate.
712 // FIXME: always querying the result type is just an
713 // approximation; some nodes' legality is determined by the
714 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000715 if (TLI.isOperationLegalOrCustom(
716 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000717 continue;
718
719 // Don't bother for PHI nodes.
720 if (isa<PHINode>(TruncUser))
721 continue;
722
723 BasicBlock *TruncUserBB = TruncUser->getParent();
724
725 if (UserBB == TruncUserBB)
726 continue;
727
728 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
729 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
730
731 if (!InsertedShift && !InsertedTrunc) {
732 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
733 // Sink the shift
734 if (ShiftI->getOpcode() == Instruction::AShr)
735 InsertedShift =
736 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
737 else
738 InsertedShift =
739 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
740
741 // Sink the trunc
742 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
743 TruncInsertPt++;
744
745 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
746 TruncI->getType(), "", TruncInsertPt);
747
748 MadeChange = true;
749
750 TruncTheUse = InsertedTrunc;
751 }
752 }
753 return MadeChange;
754}
755
756/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
757/// the uses could potentially be combined with this shift instruction and
758/// generate BitExtract instruction. It will only be applied if the architecture
759/// supports BitExtract instruction. Here is an example:
760/// BB1:
761/// %x.extract.shift = lshr i64 %arg1, 32
762/// BB2:
763/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
764/// ==>
765///
766/// BB2:
767/// %x.extract.shift.1 = lshr i64 %arg1, 32
768/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
769///
770/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
771/// instruction.
772/// Return true if any changes are made.
773static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
774 const TargetLowering &TLI) {
775 BasicBlock *DefBB = ShiftI->getParent();
776
777 /// Only insert instructions in each block once.
778 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
779
780 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
781
782 bool MadeChange = false;
783 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
784 UI != E;) {
785 Use &TheUse = UI.getUse();
786 Instruction *User = cast<Instruction>(*UI);
787 // Preincrement use iterator so we don't invalidate it.
788 ++UI;
789
790 // Don't bother for PHI nodes.
791 if (isa<PHINode>(User))
792 continue;
793
794 if (!isExtractBitsCandidateUse(User))
795 continue;
796
797 BasicBlock *UserBB = User->getParent();
798
799 if (UserBB == DefBB) {
800 // If the shift and truncate instruction are in the same BB. The use of
801 // the truncate(TruncUse) may still introduce another truncate if not
802 // legal. In this case, we would like to sink both shift and truncate
803 // instruction to the BB of TruncUse.
804 // for example:
805 // BB1:
806 // i64 shift.result = lshr i64 opnd, imm
807 // trunc.result = trunc shift.result to i16
808 //
809 // BB2:
810 // ----> We will have an implicit truncate here if the architecture does
811 // not have i16 compare.
812 // cmp i16 trunc.result, opnd2
813 //
814 if (isa<TruncInst>(User) && shiftIsLegal
815 // If the type of the truncate is legal, no trucate will be
816 // introduced in other basic blocks.
817 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
818 MadeChange =
819 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
820
821 continue;
822 }
823 // If we have already inserted a shift into this block, use it.
824 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
825
826 if (!InsertedShift) {
827 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
828
829 if (ShiftI->getOpcode() == Instruction::AShr)
830 InsertedShift =
831 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
832 else
833 InsertedShift =
834 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
835
836 MadeChange = true;
837 }
838
839 // Replace a use of the shift with a use of the new shift.
840 TheUse = InsertedShift;
841 }
842
843 // If we removed all uses, nuke the shift.
844 if (ShiftI->use_empty())
845 ShiftI->eraseFromParent();
846
847 return MadeChange;
848}
849
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000850namespace {
851class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
852protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000853 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000854 CI->replaceAllUsesWith(With);
855 CI->eraseFromParent();
856 }
Craig Topper4584cd52014-03-07 09:26:03 +0000857 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000858 if (ConstantInt *SizeCI =
859 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
860 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000861 return false;
862 }
863};
864} // end anonymous namespace
865
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000866// ScalarizeMaskedLoad() translates masked load intrinsic, like
867// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
868// <16 x i1> %mask, <16 x i32> %passthru)
869// to a chain of basic blocks, whith loading element one-by-one if
870// the appropriate mask bit is set
871//
872// %1 = bitcast i8* %addr to i32*
873// %2 = extractelement <16 x i1> %mask, i32 0
874// %3 = icmp eq i1 %2, true
875// br i1 %3, label %cond.load, label %else
876//
877//cond.load: ; preds = %0
878// %4 = getelementptr i32* %1, i32 0
879// %5 = load i32* %4
880// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
881// br label %else
882//
883//else: ; preds = %0, %cond.load
884// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
885// %7 = extractelement <16 x i1> %mask, i32 1
886// %8 = icmp eq i1 %7, true
887// br i1 %8, label %cond.load1, label %else2
888//
889//cond.load1: ; preds = %else
890// %9 = getelementptr i32* %1, i32 1
891// %10 = load i32* %9
892// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
893// br label %else2
894//
895//else2: ; preds = %else, %cond.load1
896// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
897// %12 = extractelement <16 x i1> %mask, i32 2
898// %13 = icmp eq i1 %12, true
899// br i1 %13, label %cond.load4, label %else5
900//
901static void ScalarizeMaskedLoad(CallInst *CI) {
902 Value *Ptr = CI->getArgOperand(0);
903 Value *Src0 = CI->getArgOperand(3);
904 Value *Mask = CI->getArgOperand(2);
905 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
906 Type *EltTy = VecType->getElementType();
907
908 assert(VecType && "Unexpected return type of masked load intrinsic");
909
910 IRBuilder<> Builder(CI->getContext());
911 Instruction *InsertPt = CI;
912 BasicBlock *IfBlock = CI->getParent();
913 BasicBlock *CondBlock = nullptr;
914 BasicBlock *PrevIfBlock = CI->getParent();
915 Builder.SetInsertPoint(InsertPt);
916
917 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
918
919 // Bitcast %addr fron i8* to EltTy*
920 Type *NewPtrType =
921 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
922 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
923 Value *UndefVal = UndefValue::get(VecType);
924
925 // The result vector
926 Value *VResult = UndefVal;
927
928 PHINode *Phi = nullptr;
929 Value *PrevPhi = UndefVal;
930
931 unsigned VectorWidth = VecType->getNumElements();
932 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
933
934 // Fill the "else" block, created in the previous iteration
935 //
936 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
937 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
938 // %to_load = icmp eq i1 %mask_1, true
939 // br i1 %to_load, label %cond.load, label %else
940 //
941 if (Idx > 0) {
942 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
943 Phi->addIncoming(VResult, CondBlock);
944 Phi->addIncoming(PrevPhi, PrevIfBlock);
945 PrevPhi = Phi;
946 VResult = Phi;
947 }
948
949 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
950 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
951 ConstantInt::get(Predicate->getType(), 1));
952
953 // Create "cond" block
954 //
955 // %EltAddr = getelementptr i32* %1, i32 0
956 // %Elt = load i32* %EltAddr
957 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
958 //
959 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
960 Builder.SetInsertPoint(InsertPt);
961
962 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
963 LoadInst* Load = Builder.CreateLoad(Gep, false);
964 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
965
966 // Create "else" block, fill it in the next iteration
967 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
968 Builder.SetInsertPoint(InsertPt);
969 Instruction *OldBr = IfBlock->getTerminator();
970 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
971 OldBr->eraseFromParent();
972 PrevIfBlock = IfBlock;
973 IfBlock = NewIfBlock;
974 }
975
976 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
977 Phi->addIncoming(VResult, CondBlock);
978 Phi->addIncoming(PrevPhi, PrevIfBlock);
979 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
980 CI->replaceAllUsesWith(NewI);
981 CI->eraseFromParent();
982}
983
984// ScalarizeMaskedStore() translates masked store intrinsic, like
985// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
986// <16 x i1> %mask)
987// to a chain of basic blocks, that stores element one-by-one if
988// the appropriate mask bit is set
989//
990// %1 = bitcast i8* %addr to i32*
991// %2 = extractelement <16 x i1> %mask, i32 0
992// %3 = icmp eq i1 %2, true
993// br i1 %3, label %cond.store, label %else
994//
995// cond.store: ; preds = %0
996// %4 = extractelement <16 x i32> %val, i32 0
997// %5 = getelementptr i32* %1, i32 0
998// store i32 %4, i32* %5
999// br label %else
1000//
1001// else: ; preds = %0, %cond.store
1002// %6 = extractelement <16 x i1> %mask, i32 1
1003// %7 = icmp eq i1 %6, true
1004// br i1 %7, label %cond.store1, label %else2
1005//
1006// cond.store1: ; preds = %else
1007// %8 = extractelement <16 x i32> %val, i32 1
1008// %9 = getelementptr i32* %1, i32 1
1009// store i32 %8, i32* %9
1010// br label %else2
1011// . . .
1012static void ScalarizeMaskedStore(CallInst *CI) {
1013 Value *Ptr = CI->getArgOperand(1);
1014 Value *Src = CI->getArgOperand(0);
1015 Value *Mask = CI->getArgOperand(3);
1016
1017 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1018 Type *EltTy = VecType->getElementType();
1019
1020 assert(VecType && "Unexpected data type in masked store intrinsic");
1021
1022 IRBuilder<> Builder(CI->getContext());
1023 Instruction *InsertPt = CI;
1024 BasicBlock *IfBlock = CI->getParent();
1025 Builder.SetInsertPoint(InsertPt);
1026 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1027
1028 // Bitcast %addr fron i8* to EltTy*
1029 Type *NewPtrType =
1030 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1031 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1032
1033 unsigned VectorWidth = VecType->getNumElements();
1034 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1035
1036 // Fill the "else" block, created in the previous iteration
1037 //
1038 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1039 // %to_store = icmp eq i1 %mask_1, true
1040 // br i1 %to_load, label %cond.store, label %else
1041 //
1042 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1043 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1044 ConstantInt::get(Predicate->getType(), 1));
1045
1046 // Create "cond" block
1047 //
1048 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1049 // %EltAddr = getelementptr i32* %1, i32 0
1050 // %store i32 %OneElt, i32* %EltAddr
1051 //
1052 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1053 Builder.SetInsertPoint(InsertPt);
1054
1055 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1056 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1057 Builder.CreateStore(OneElt, Gep);
1058
1059 // Create "else" block, fill it in the next iteration
1060 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1061 Builder.SetInsertPoint(InsertPt);
1062 Instruction *OldBr = IfBlock->getTerminator();
1063 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1064 OldBr->eraseFromParent();
1065 IfBlock = NewIfBlock;
1066 }
1067 CI->eraseFromParent();
1068}
1069
1070bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001071 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001072
Chris Lattner7a277142011-01-15 07:14:54 +00001073 // Lower inline assembly if we can.
1074 // If we found an inline asm expession, and if the target knows how to
1075 // lower it to normal LLVM code, do so now.
1076 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1077 if (TLI->ExpandInlineAsm(CI)) {
1078 // Avoid invalidating the iterator.
1079 CurInstIterator = BB->begin();
1080 // Avoid processing instructions out of order, which could cause
1081 // reuse before a value is defined.
1082 SunkAddrs.clear();
1083 return true;
1084 }
1085 // Sink address computing for memory operands into the block.
1086 if (OptimizeInlineAsmInst(CI))
1087 return true;
1088 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001089
Eric Christopher4b7948e2010-03-11 02:41:03 +00001090 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001091 if (II) {
1092 switch (II->getIntrinsicID()) {
1093 default: break;
1094 case Intrinsic::objectsize: {
1095 // Lower all uses of llvm.objectsize.*
1096 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1097 Type *ReturnTy = CI->getType();
1098 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001099
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001100 // Substituting this can cause recursive simplifications, which can
1101 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1102 // happens.
1103 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001104
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001105 replaceAndRecursivelySimplify(CI, RetVal,
1106 TLI ? TLI->getDataLayout() : nullptr,
1107 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +00001108
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001109 // If the iterator instruction was recursively deleted, start over at the
1110 // start of the block.
1111 if (IterHandle != CurInstIterator) {
1112 CurInstIterator = BB->begin();
1113 SunkAddrs.clear();
1114 }
1115 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001116 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001117 case Intrinsic::masked_load: {
1118 // Scalarize unsupported vector masked load
1119 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1120 ScalarizeMaskedLoad(CI);
1121 ModifiedDT = true;
1122 return true;
1123 }
1124 return false;
1125 }
1126 case Intrinsic::masked_store: {
1127 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1128 ScalarizeMaskedStore(CI);
1129 ModifiedDT = true;
1130 return true;
1131 }
1132 return false;
1133 }
1134 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001135
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001136 if (TLI) {
1137 SmallVector<Value*, 2> PtrOps;
1138 Type *AccessTy;
1139 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
1140 while (!PtrOps.empty())
1141 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
1142 return true;
1143 }
Pete Cooper615fd892012-03-13 20:59:56 +00001144 }
1145
Eric Christopher4b7948e2010-03-11 02:41:03 +00001146 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001147 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001148
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001149 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +00001150 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001151 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001152
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001153 // Lower all default uses of _chk calls. This is very similar
1154 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +00001155 // that have the default "don't know" as the objectsize. Anything else
1156 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001157 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +00001158 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +00001159}
Chris Lattner1b93be52011-01-15 07:25:29 +00001160
Evan Cheng0663f232011-03-21 01:19:09 +00001161/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1162/// instructions to the predecessor to enable tail call optimizations. The
1163/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001164/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001165/// bb0:
1166/// %tmp0 = tail call i32 @f0()
1167/// br label %return
1168/// bb1:
1169/// %tmp1 = tail call i32 @f1()
1170/// br label %return
1171/// bb2:
1172/// %tmp2 = tail call i32 @f2()
1173/// br label %return
1174/// return:
1175/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1176/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001177/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001178///
1179/// =>
1180///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001181/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001182/// bb0:
1183/// %tmp0 = tail call i32 @f0()
1184/// ret i32 %tmp0
1185/// bb1:
1186/// %tmp1 = tail call i32 @f1()
1187/// ret i32 %tmp1
1188/// bb2:
1189/// %tmp2 = tail call i32 @f2()
1190/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001191/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +00001192bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001193 if (!TLI)
1194 return false;
1195
Benjamin Kramer455fa352012-11-23 19:17:06 +00001196 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1197 if (!RI)
1198 return false;
1199
Craig Topperc0196b12014-04-14 00:51:57 +00001200 PHINode *PN = nullptr;
1201 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001202 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001203 if (V) {
1204 BCI = dyn_cast<BitCastInst>(V);
1205 if (BCI)
1206 V = BCI->getOperand(0);
1207
1208 PN = dyn_cast<PHINode>(V);
1209 if (!PN)
1210 return false;
1211 }
Evan Cheng0663f232011-03-21 01:19:09 +00001212
Cameron Zwarich4649f172011-03-24 04:52:10 +00001213 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001214 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001215
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001216 // It's not safe to eliminate the sign / zero extension of the return value.
1217 // See llvm::isInTailCallPosition().
1218 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001219 AttributeSet CallerAttrs = F->getAttributes();
1220 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1221 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001222 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001223
Cameron Zwarich4649f172011-03-24 04:52:10 +00001224 // Make sure there are no instructions between the PHI and return, or that the
1225 // return is the first instruction in the block.
1226 if (PN) {
1227 BasicBlock::iterator BI = BB->begin();
1228 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001229 if (&*BI == BCI)
1230 // Also skip over the bitcast.
1231 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001232 if (&*BI != RI)
1233 return false;
1234 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001235 BasicBlock::iterator BI = BB->begin();
1236 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1237 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001238 return false;
1239 }
Evan Cheng0663f232011-03-21 01:19:09 +00001240
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001241 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1242 /// call.
1243 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001244 if (PN) {
1245 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1246 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1247 // Make sure the phi value is indeed produced by the tail call.
1248 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1249 TLI->mayBeEmittedAsTailCall(CI))
1250 TailCalls.push_back(CI);
1251 }
1252 } else {
1253 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001254 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001255 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001256 continue;
1257
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001258 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001259 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1260 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001261 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1262 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001263 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001264
Cameron Zwarich4649f172011-03-24 04:52:10 +00001265 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001266 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001267 TailCalls.push_back(CI);
1268 }
Evan Cheng0663f232011-03-21 01:19:09 +00001269 }
1270
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001271 bool Changed = false;
1272 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1273 CallInst *CI = TailCalls[i];
1274 CallSite CS(CI);
1275
1276 // Conservatively require the attributes of the call to match those of the
1277 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001278 AttributeSet CalleeAttrs = CS.getAttributes();
1279 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001280 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001281 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001282 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001283 continue;
1284
1285 // Make sure the call instruction is followed by an unconditional branch to
1286 // the return block.
1287 BasicBlock *CallBB = CI->getParent();
1288 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1289 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1290 continue;
1291
1292 // Duplicate the return into CallBB.
1293 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001294 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001295 ++NumRetsDup;
1296 }
1297
1298 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001299 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001300 BB->eraseFromParent();
1301
1302 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001303}
1304
Chris Lattner728f9022008-11-25 07:09:13 +00001305//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001306// Memory Optimization
1307//===----------------------------------------------------------------------===//
1308
Chandler Carruthc8925912013-01-05 02:09:22 +00001309namespace {
1310
1311/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1312/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001313struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001314 Value *BaseReg;
1315 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001316 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001317 void print(raw_ostream &OS) const;
1318 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001319
Chandler Carruthc8925912013-01-05 02:09:22 +00001320 bool operator==(const ExtAddrMode& O) const {
1321 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1322 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1323 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1324 }
1325};
1326
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001327#ifndef NDEBUG
1328static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1329 AM.print(OS);
1330 return OS;
1331}
1332#endif
1333
Chandler Carruthc8925912013-01-05 02:09:22 +00001334void ExtAddrMode::print(raw_ostream &OS) const {
1335 bool NeedPlus = false;
1336 OS << "[";
1337 if (BaseGV) {
1338 OS << (NeedPlus ? " + " : "")
1339 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001340 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001341 NeedPlus = true;
1342 }
1343
Richard Trieuc0f91212014-05-30 03:15:17 +00001344 if (BaseOffs) {
1345 OS << (NeedPlus ? " + " : "")
1346 << BaseOffs;
1347 NeedPlus = true;
1348 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001349
1350 if (BaseReg) {
1351 OS << (NeedPlus ? " + " : "")
1352 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001353 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001354 NeedPlus = true;
1355 }
1356 if (Scale) {
1357 OS << (NeedPlus ? " + " : "")
1358 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001359 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001360 }
1361
1362 OS << ']';
1363}
1364
1365#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1366void ExtAddrMode::dump() const {
1367 print(dbgs());
1368 dbgs() << '\n';
1369}
1370#endif
1371
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001372/// \brief This class provides transaction based operation on the IR.
1373/// Every change made through this class is recorded in the internal state and
1374/// can be undone (rollback) until commit is called.
1375class TypePromotionTransaction {
1376
1377 /// \brief This represents the common interface of the individual transaction.
1378 /// Each class implements the logic for doing one specific modification on
1379 /// the IR via the TypePromotionTransaction.
1380 class TypePromotionAction {
1381 protected:
1382 /// The Instruction modified.
1383 Instruction *Inst;
1384
1385 public:
1386 /// \brief Constructor of the action.
1387 /// The constructor performs the related action on the IR.
1388 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1389
1390 virtual ~TypePromotionAction() {}
1391
1392 /// \brief Undo the modification done by this action.
1393 /// When this method is called, the IR must be in the same state as it was
1394 /// before this action was applied.
1395 /// \pre Undoing the action works if and only if the IR is in the exact same
1396 /// state as it was directly after this action was applied.
1397 virtual void undo() = 0;
1398
1399 /// \brief Advocate every change made by this action.
1400 /// When the results on the IR of the action are to be kept, it is important
1401 /// to call this function, otherwise hidden information may be kept forever.
1402 virtual void commit() {
1403 // Nothing to be done, this action is not doing anything.
1404 }
1405 };
1406
1407 /// \brief Utility to remember the position of an instruction.
1408 class InsertionHandler {
1409 /// Position of an instruction.
1410 /// Either an instruction:
1411 /// - Is the first in a basic block: BB is used.
1412 /// - Has a previous instructon: PrevInst is used.
1413 union {
1414 Instruction *PrevInst;
1415 BasicBlock *BB;
1416 } Point;
1417 /// Remember whether or not the instruction had a previous instruction.
1418 bool HasPrevInstruction;
1419
1420 public:
1421 /// \brief Record the position of \p Inst.
1422 InsertionHandler(Instruction *Inst) {
1423 BasicBlock::iterator It = Inst;
1424 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1425 if (HasPrevInstruction)
1426 Point.PrevInst = --It;
1427 else
1428 Point.BB = Inst->getParent();
1429 }
1430
1431 /// \brief Insert \p Inst at the recorded position.
1432 void insert(Instruction *Inst) {
1433 if (HasPrevInstruction) {
1434 if (Inst->getParent())
1435 Inst->removeFromParent();
1436 Inst->insertAfter(Point.PrevInst);
1437 } else {
1438 Instruction *Position = Point.BB->getFirstInsertionPt();
1439 if (Inst->getParent())
1440 Inst->moveBefore(Position);
1441 else
1442 Inst->insertBefore(Position);
1443 }
1444 }
1445 };
1446
1447 /// \brief Move an instruction before another.
1448 class InstructionMoveBefore : public TypePromotionAction {
1449 /// Original position of the instruction.
1450 InsertionHandler Position;
1451
1452 public:
1453 /// \brief Move \p Inst before \p Before.
1454 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1455 : TypePromotionAction(Inst), Position(Inst) {
1456 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1457 Inst->moveBefore(Before);
1458 }
1459
1460 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001461 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001462 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1463 Position.insert(Inst);
1464 }
1465 };
1466
1467 /// \brief Set the operand of an instruction with a new value.
1468 class OperandSetter : public TypePromotionAction {
1469 /// Original operand of the instruction.
1470 Value *Origin;
1471 /// Index of the modified instruction.
1472 unsigned Idx;
1473
1474 public:
1475 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1476 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1477 : TypePromotionAction(Inst), Idx(Idx) {
1478 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1479 << "for:" << *Inst << "\n"
1480 << "with:" << *NewVal << "\n");
1481 Origin = Inst->getOperand(Idx);
1482 Inst->setOperand(Idx, NewVal);
1483 }
1484
1485 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001486 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001487 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1488 << "for: " << *Inst << "\n"
1489 << "with: " << *Origin << "\n");
1490 Inst->setOperand(Idx, Origin);
1491 }
1492 };
1493
1494 /// \brief Hide the operands of an instruction.
1495 /// Do as if this instruction was not using any of its operands.
1496 class OperandsHider : public TypePromotionAction {
1497 /// The list of original operands.
1498 SmallVector<Value *, 4> OriginalValues;
1499
1500 public:
1501 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1502 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1503 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1504 unsigned NumOpnds = Inst->getNumOperands();
1505 OriginalValues.reserve(NumOpnds);
1506 for (unsigned It = 0; It < NumOpnds; ++It) {
1507 // Save the current operand.
1508 Value *Val = Inst->getOperand(It);
1509 OriginalValues.push_back(Val);
1510 // Set a dummy one.
1511 // We could use OperandSetter here, but that would implied an overhead
1512 // that we are not willing to pay.
1513 Inst->setOperand(It, UndefValue::get(Val->getType()));
1514 }
1515 }
1516
1517 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001518 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001519 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1520 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1521 Inst->setOperand(It, OriginalValues[It]);
1522 }
1523 };
1524
1525 /// \brief Build a truncate instruction.
1526 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001527 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001528 public:
1529 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1530 /// result.
1531 /// trunc Opnd to Ty.
1532 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1533 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001534 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1535 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001536 }
1537
Quentin Colombetac55b152014-09-16 22:36:07 +00001538 /// \brief Get the built value.
1539 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001540
1541 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001542 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001543 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1544 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1545 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001546 }
1547 };
1548
1549 /// \brief Build a sign extension instruction.
1550 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001551 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001552 public:
1553 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1554 /// result.
1555 /// sext Opnd to Ty.
1556 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001557 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001558 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001559 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1560 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001561 }
1562
Quentin Colombetac55b152014-09-16 22:36:07 +00001563 /// \brief Get the built value.
1564 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001565
1566 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001567 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001568 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1569 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1570 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001571 }
1572 };
1573
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001574 /// \brief Build a zero extension instruction.
1575 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001576 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001577 public:
1578 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1579 /// result.
1580 /// zext Opnd to Ty.
1581 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001582 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001583 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001584 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1585 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001586 }
1587
Quentin Colombetac55b152014-09-16 22:36:07 +00001588 /// \brief Get the built value.
1589 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001590
1591 /// \brief Remove the built instruction.
1592 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001593 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1594 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1595 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001596 }
1597 };
1598
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001599 /// \brief Mutate an instruction to another type.
1600 class TypeMutator : public TypePromotionAction {
1601 /// Record the original type.
1602 Type *OrigTy;
1603
1604 public:
1605 /// \brief Mutate the type of \p Inst into \p NewTy.
1606 TypeMutator(Instruction *Inst, Type *NewTy)
1607 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1608 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1609 << "\n");
1610 Inst->mutateType(NewTy);
1611 }
1612
1613 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001614 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001615 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1616 << "\n");
1617 Inst->mutateType(OrigTy);
1618 }
1619 };
1620
1621 /// \brief Replace the uses of an instruction by another instruction.
1622 class UsesReplacer : public TypePromotionAction {
1623 /// Helper structure to keep track of the replaced uses.
1624 struct InstructionAndIdx {
1625 /// The instruction using the instruction.
1626 Instruction *Inst;
1627 /// The index where this instruction is used for Inst.
1628 unsigned Idx;
1629 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1630 : Inst(Inst), Idx(Idx) {}
1631 };
1632
1633 /// Keep track of the original uses (pair Instruction, Index).
1634 SmallVector<InstructionAndIdx, 4> OriginalUses;
1635 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1636
1637 public:
1638 /// \brief Replace all the use of \p Inst by \p New.
1639 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1640 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1641 << "\n");
1642 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001643 for (Use &U : Inst->uses()) {
1644 Instruction *UserI = cast<Instruction>(U.getUser());
1645 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001646 }
1647 // Now, we can replace the uses.
1648 Inst->replaceAllUsesWith(New);
1649 }
1650
1651 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001652 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001653 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1654 for (use_iterator UseIt = OriginalUses.begin(),
1655 EndIt = OriginalUses.end();
1656 UseIt != EndIt; ++UseIt) {
1657 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1658 }
1659 }
1660 };
1661
1662 /// \brief Remove an instruction from the IR.
1663 class InstructionRemover : public TypePromotionAction {
1664 /// Original position of the instruction.
1665 InsertionHandler Inserter;
1666 /// Helper structure to hide all the link to the instruction. In other
1667 /// words, this helps to do as if the instruction was removed.
1668 OperandsHider Hider;
1669 /// Keep track of the uses replaced, if any.
1670 UsesReplacer *Replacer;
1671
1672 public:
1673 /// \brief Remove all reference of \p Inst and optinally replace all its
1674 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001675 /// \pre If !Inst->use_empty(), then New != nullptr
1676 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001677 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001678 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001679 if (New)
1680 Replacer = new UsesReplacer(Inst, New);
1681 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1682 Inst->removeFromParent();
1683 }
1684
1685 ~InstructionRemover() { delete Replacer; }
1686
1687 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001688 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001689
1690 /// \brief Resurrect the instruction and reassign it to the proper uses if
1691 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001692 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001693 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1694 Inserter.insert(Inst);
1695 if (Replacer)
1696 Replacer->undo();
1697 Hider.undo();
1698 }
1699 };
1700
1701public:
1702 /// Restoration point.
1703 /// The restoration point is a pointer to an action instead of an iterator
1704 /// because the iterator may be invalidated but not the pointer.
1705 typedef const TypePromotionAction *ConstRestorationPt;
1706 /// Advocate every changes made in that transaction.
1707 void commit();
1708 /// Undo all the changes made after the given point.
1709 void rollback(ConstRestorationPt Point);
1710 /// Get the current restoration point.
1711 ConstRestorationPt getRestorationPoint() const;
1712
1713 /// \name API for IR modification with state keeping to support rollback.
1714 /// @{
1715 /// Same as Instruction::setOperand.
1716 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1717 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001718 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001719 /// Same as Value::replaceAllUsesWith.
1720 void replaceAllUsesWith(Instruction *Inst, Value *New);
1721 /// Same as Value::mutateType.
1722 void mutateType(Instruction *Inst, Type *NewTy);
1723 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00001724 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001725 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001726 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001727 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001728 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001729 /// Same as Instruction::moveBefore.
1730 void moveBefore(Instruction *Inst, Instruction *Before);
1731 /// @}
1732
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001733private:
1734 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001735 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1736 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001737};
1738
1739void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1740 Value *NewVal) {
1741 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001742 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001743}
1744
1745void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1746 Value *NewVal) {
1747 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001748 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001749}
1750
1751void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1752 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001753 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001754}
1755
1756void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001757 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001758}
1759
Quentin Colombetac55b152014-09-16 22:36:07 +00001760Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1761 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001762 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001763 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001764 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001765 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001766}
1767
Quentin Colombetac55b152014-09-16 22:36:07 +00001768Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1769 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001770 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001771 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001772 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001773 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001774}
1775
Quentin Colombetac55b152014-09-16 22:36:07 +00001776Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1777 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001778 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001779 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001780 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001781 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001782}
1783
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001784void TypePromotionTransaction::moveBefore(Instruction *Inst,
1785 Instruction *Before) {
1786 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001787 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001788}
1789
1790TypePromotionTransaction::ConstRestorationPt
1791TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00001792 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001793}
1794
1795void TypePromotionTransaction::commit() {
1796 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00001797 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001798 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001799 Actions.clear();
1800}
1801
1802void TypePromotionTransaction::rollback(
1803 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00001804 while (!Actions.empty() && Point != Actions.back().get()) {
1805 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001806 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001807 }
1808}
1809
Chandler Carruthc8925912013-01-05 02:09:22 +00001810/// \brief A helper class for matching addressing modes.
1811///
1812/// This encapsulates the logic for matching the target-legal addressing modes.
1813class AddressingModeMatcher {
1814 SmallVectorImpl<Instruction*> &AddrModeInsts;
1815 const TargetLowering &TLI;
1816
1817 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1818 /// the memory instruction that we're computing this address for.
1819 Type *AccessTy;
1820 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001821
Chandler Carruthc8925912013-01-05 02:09:22 +00001822 /// AddrMode - This is the addressing mode that we're building up. This is
1823 /// part of the return value of this addressing mode matching stuff.
1824 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001825
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001826 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1827 const SetOfInstrs &InsertedTruncs;
1828 /// A map from the instructions to their type before promotion.
1829 InstrToOrigTy &PromotedInsts;
1830 /// The ongoing transaction where every action should be registered.
1831 TypePromotionTransaction &TPT;
1832
Chandler Carruthc8925912013-01-05 02:09:22 +00001833 /// IgnoreProfitability - This is set to true when we should not do
1834 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1835 /// always returns true.
1836 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001837
Chandler Carruthc8925912013-01-05 02:09:22 +00001838 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1839 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001840 Instruction *MI, ExtAddrMode &AM,
1841 const SetOfInstrs &InsertedTruncs,
1842 InstrToOrigTy &PromotedInsts,
1843 TypePromotionTransaction &TPT)
1844 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1845 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001846 IgnoreProfitability = false;
1847 }
1848public:
Stephen Lin837bba12013-07-15 17:55:02 +00001849
Chandler Carruthc8925912013-01-05 02:09:22 +00001850 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1851 /// give an access type of AccessTy. This returns a list of involved
1852 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001853 /// \p InsertedTruncs The truncate instruction inserted by other
1854 /// CodeGenPrepare
1855 /// optimizations.
1856 /// \p PromotedInsts maps the instructions to their type before promotion.
1857 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001858 static ExtAddrMode Match(Value *V, Type *AccessTy,
1859 Instruction *MemoryInst,
1860 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001861 const TargetLowering &TLI,
1862 const SetOfInstrs &InsertedTruncs,
1863 InstrToOrigTy &PromotedInsts,
1864 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001865 ExtAddrMode Result;
1866
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001867 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1868 MemoryInst, Result, InsertedTruncs,
1869 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001870 (void)Success; assert(Success && "Couldn't select *anything*?");
1871 return Result;
1872 }
1873private:
1874 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1875 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001876 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00001877 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00001878 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1879 ExtAddrMode &AMBefore,
1880 ExtAddrMode &AMAfter);
1881 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001882 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1883 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001884};
1885
1886/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1887/// Return true and update AddrMode if this addr mode is legal for the target,
1888/// false if not.
1889bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1890 unsigned Depth) {
1891 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1892 // mode. Just process that directly.
1893 if (Scale == 1)
1894 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001895
Chandler Carruthc8925912013-01-05 02:09:22 +00001896 // If the scale is 0, it takes nothing to add this.
1897 if (Scale == 0)
1898 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001899
Chandler Carruthc8925912013-01-05 02:09:22 +00001900 // If we already have a scale of this value, we can add to it, otherwise, we
1901 // need an available scale field.
1902 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1903 return false;
1904
1905 ExtAddrMode TestAddrMode = AddrMode;
1906
1907 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1908 // [A+B + A*7] -> [B+A*8].
1909 TestAddrMode.Scale += Scale;
1910 TestAddrMode.ScaledReg = ScaleReg;
1911
1912 // If the new address isn't legal, bail out.
1913 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1914 return false;
1915
1916 // It was legal, so commit it.
1917 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001918
Chandler Carruthc8925912013-01-05 02:09:22 +00001919 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1920 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1921 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00001922 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00001923 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1924 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1925 TestAddrMode.ScaledReg = AddLHS;
1926 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001927
Chandler Carruthc8925912013-01-05 02:09:22 +00001928 // If this addressing mode is legal, commit it and remember that we folded
1929 // this instruction.
1930 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1931 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1932 AddrMode = TestAddrMode;
1933 return true;
1934 }
1935 }
1936
1937 // Otherwise, not (x+c)*scale, just return what we have.
1938 return true;
1939}
1940
1941/// MightBeFoldableInst - This is a little filter, which returns true if an
1942/// addressing computation involving I might be folded into a load/store
1943/// accessing it. This doesn't need to be perfect, but needs to accept at least
1944/// the set of instructions that MatchOperationAddr can.
1945static bool MightBeFoldableInst(Instruction *I) {
1946 switch (I->getOpcode()) {
1947 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00001948 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00001949 // Don't touch identity bitcasts.
1950 if (I->getType() == I->getOperand(0)->getType())
1951 return false;
1952 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1953 case Instruction::PtrToInt:
1954 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1955 return true;
1956 case Instruction::IntToPtr:
1957 // We know the input is intptr_t, so this is foldable.
1958 return true;
1959 case Instruction::Add:
1960 return true;
1961 case Instruction::Mul:
1962 case Instruction::Shl:
1963 // Can only handle X*C and X << C.
1964 return isa<ConstantInt>(I->getOperand(1));
1965 case Instruction::GetElementPtr:
1966 return true;
1967 default:
1968 return false;
1969 }
1970}
1971
Quentin Colombetfc2201e2014-12-17 01:36:17 +00001972/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
1973/// \note \p Val is assumed to be the product of some type promotion.
1974/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
1975/// to be legal, as the non-promoted value would have had the same state.
1976static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
1977 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
1978 if (!PromotedInst)
1979 return false;
1980 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1981 // If the ISDOpcode is undefined, it was undefined before the promotion.
1982 if (!ISDOpcode)
1983 return true;
1984 // Otherwise, check if the promoted instruction is legal or not.
1985 return TLI.isOperationLegalOrCustom(
1986 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
1987}
1988
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001989/// \brief Hepler class to perform type promotion.
1990class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001991 /// \brief Utility function to check whether or not a sign or zero extension
1992 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1993 /// either using the operands of \p Inst or promoting \p Inst.
1994 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001995 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001996 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001997 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001998 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001999 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002000 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002001 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002002 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2003 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002004
2005 /// \brief Utility function to determine if \p OpIdx should be promoted when
2006 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002007 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002008 if (isa<SelectInst>(Inst) && OpIdx == 0)
2009 return false;
2010 return true;
2011 }
2012
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002013 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002014 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002015 /// \p PromotedInsts maps the instructions to their type before promotion.
2016 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002017 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002018 /// Newly added extensions are inserted in \p Exts.
2019 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002020 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002021 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002022 static Value *promoteOperandForTruncAndAnyExt(
2023 Instruction *Ext, TypePromotionTransaction &TPT,
2024 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2025 SmallVectorImpl<Instruction *> *Exts,
2026 SmallVectorImpl<Instruction *> *Truncs);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002027
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002028 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002029 /// operand is promotable and is not a supported trunc or sext.
2030 /// \p PromotedInsts maps the instructions to their type before promotion.
2031 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002032 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002033 /// Newly added extensions are inserted in \p Exts.
2034 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002035 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002036 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002037 static Value *
2038 promoteOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2039 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2040 SmallVectorImpl<Instruction *> *Exts,
2041 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002042
2043 /// \see promoteOperandForOther.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002044 static Value *
2045 signExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2046 InstrToOrigTy &PromotedInsts,
2047 unsigned &CreatedInsts,
2048 SmallVectorImpl<Instruction *> *Exts,
2049 SmallVectorImpl<Instruction *> *Truncs) {
2050 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2051 Truncs, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002052 }
2053
2054 /// \see promoteOperandForOther.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002055 static Value *
2056 zeroExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2057 InstrToOrigTy &PromotedInsts,
2058 unsigned &CreatedInsts,
2059 SmallVectorImpl<Instruction *> *Exts,
2060 SmallVectorImpl<Instruction *> *Truncs) {
2061 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2062 Truncs, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002063 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002064
2065public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002066 /// Type for the utility function that promotes the operand of Ext.
2067 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002068 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2069 SmallVectorImpl<Instruction *> *Exts,
2070 SmallVectorImpl<Instruction *> *Truncs);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002071 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2072 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002073 /// \return NULL if no promotable action is possible with the current
2074 /// sign extension.
2075 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
2076 /// the others CodeGenPrepare optimizations. This information is important
2077 /// because we do not want to promote these instructions as CodeGenPrepare
2078 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2079 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002080 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002081 const TargetLowering &TLI,
2082 const InstrToOrigTy &PromotedInsts);
2083};
2084
2085bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002086 Type *ConsideredExtType,
2087 const InstrToOrigTy &PromotedInsts,
2088 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002089 // The promotion helper does not know how to deal with vector types yet.
2090 // To be able to fix that, we would need to fix the places where we
2091 // statically extend, e.g., constants and such.
2092 if (Inst->getType()->isVectorTy())
2093 return false;
2094
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002095 // We can always get through zext.
2096 if (isa<ZExtInst>(Inst))
2097 return true;
2098
2099 // sext(sext) is ok too.
2100 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002101 return true;
2102
2103 // We can get through binary operator, if it is legal. In other words, the
2104 // binary operator must have a nuw or nsw flag.
2105 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2106 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002107 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2108 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002109 return true;
2110
2111 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002112 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002113 if (!isa<TruncInst>(Inst))
2114 return false;
2115
2116 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002117 // Check if we can use this operand in the extension.
2118 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002119 // we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002120 if (!OpndVal->getType()->isIntegerTy() ||
2121 OpndVal->getType()->getIntegerBitWidth() >
2122 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002123 return false;
2124
2125 // If the operand of the truncate is not an instruction, we will not have
2126 // any information on the dropped bits.
2127 // (Actually we could for constant but it is not worth the extra logic).
2128 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2129 if (!Opnd)
2130 return false;
2131
2132 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002133 // I.e., check that trunc just drops extended bits of the same kind of
2134 // the extension.
2135 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002136 const Type *OpndType;
2137 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002138 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
2139 OpndType = It->second.Ty;
2140 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2141 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002142 else
2143 return false;
2144
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002145 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002146 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2147 return true;
2148
2149 return false;
2150}
2151
2152TypePromotionHelper::Action TypePromotionHelper::getAction(
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002153 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002154 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002155 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2156 "Unexpected instruction type");
2157 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2158 Type *ExtTy = Ext->getType();
2159 bool IsSExt = isa<SExtInst>(Ext);
2160 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002161 // get through.
2162 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002163 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002164 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002165
2166 // Do not promote if the operand has been added by codegenprepare.
2167 // Otherwise, it means we are undoing an optimization that is likely to be
2168 // redone, thus causing potential infinite loop.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002169 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002170 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002171
2172 // SExt or Trunc instructions.
2173 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002174 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2175 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002176 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002177
2178 // Regular instruction.
2179 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002180 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002181 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002182 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002183}
2184
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002185Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002186 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002187 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2188 SmallVectorImpl<Instruction *> *Exts,
2189 SmallVectorImpl<Instruction *> *Truncs) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002190 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2191 // get through it and this method should not be called.
2192 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002193 Value *ExtVal = SExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002194 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002195 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002196 // => zext(opnd).
Quentin Colombetac55b152014-09-16 22:36:07 +00002197 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002198 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2199 TPT.replaceAllUsesWith(SExt, ZExt);
2200 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002201 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002202 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002203 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2204 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002205 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2206 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002207 CreatedInsts = 0;
2208
2209 // Remove dead code.
2210 if (SExtOpnd->use_empty())
2211 TPT.eraseInstruction(SExtOpnd);
2212
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002213 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002214 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002215 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2216 if (ExtInst && Exts)
2217 Exts->push_back(ExtInst);
Quentin Colombetac55b152014-09-16 22:36:07 +00002218 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002219 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002220
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002221 // At this point we have: ext ty opnd to ty.
2222 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2223 Value *NextVal = ExtInst->getOperand(0);
2224 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002225 return NextVal;
2226}
2227
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002228Value *TypePromotionHelper::promoteOperandForOther(
2229 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002230 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2231 SmallVectorImpl<Instruction *> *Exts,
2232 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002233 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002234 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002235 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002236 CreatedInsts = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002237 if (!ExtOpnd->hasOneUse()) {
2238 // ExtOpnd will be promoted.
2239 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002240 // promoted version.
2241 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002242 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002243 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2244 ITrunc->removeFromParent();
2245 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002246 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002247 if (Truncs)
2248 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002249 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002250
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002251 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2252 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002253 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002254 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255 }
2256
2257 // Get through the Instruction:
2258 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002259 // 2. Replace the uses of Ext by Inst.
2260 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002261
2262 // Remember the original type of the instruction before promotion.
2263 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002264 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2265 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002266 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002267 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002268 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002269 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002270 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002271 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002272
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002273 DEBUG(dbgs() << "Propagate Ext to operands\n");
2274 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002275 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002276 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2277 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2278 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002279 DEBUG(dbgs() << "No need to propagate\n");
2280 continue;
2281 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002282 // Check if we can statically extend the operand.
2283 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002285 DEBUG(dbgs() << "Statically extend\n");
2286 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2287 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2288 : Cst->getValue().zext(BitWidth);
2289 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002290 continue;
2291 }
2292 // UndefValue are typed, so we have to statically sign extend them.
2293 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002294 DEBUG(dbgs() << "Statically extend\n");
2295 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296 continue;
2297 }
2298
2299 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002300 // Check if Ext was reused to extend an operand.
2301 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002302 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002303 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002304 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2305 : TPT.createZExt(Ext, Opnd, Ext->getType());
2306 if (!isa<Instruction>(ValForExtOpnd)) {
2307 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2308 continue;
2309 }
2310 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002311 ++CreatedInsts;
2312 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002313 if (Exts)
2314 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002315 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002316
2317 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002318 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2319 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002320 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002321 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002323 if (ExtForOpnd == Ext) {
2324 DEBUG(dbgs() << "Extension is useless now\n");
2325 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002327 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002328}
2329
Quentin Colombet867c5502014-02-14 22:23:22 +00002330/// IsPromotionProfitable - Check whether or not promoting an instruction
2331/// to a wider type was profitable.
2332/// \p MatchedSize gives the number of instructions that have been matched
2333/// in the addressing mode after the promotion was applied.
2334/// \p SizeWithPromotion gives the number of created instructions for
2335/// the promotion plus the number of instructions that have been
2336/// matched in the addressing mode before the promotion.
2337/// \p PromotedOperand is the value that has been promoted.
2338/// \return True if the promotion is profitable, false otherwise.
2339bool
2340AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2341 unsigned SizeWithPromotion,
2342 Value *PromotedOperand) const {
2343 // We folded less instructions than what we created to promote the operand.
2344 // This is not profitable.
2345 if (MatchedSize < SizeWithPromotion)
2346 return false;
2347 if (MatchedSize > SizeWithPromotion)
2348 return true;
2349 // The promotion is neutral but it may help folding the sign extension in
2350 // loads for instance.
2351 // Check that we did not create an illegal instruction.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002352 return isPromotedInstructionLegal(TLI, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002353}
2354
Chandler Carruthc8925912013-01-05 02:09:22 +00002355/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2356/// fold the operation into the addressing mode. If so, update the addressing
2357/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002358/// If \p MovedAway is not NULL, it contains the information of whether or
2359/// not AddrInst has to be folded into the addressing mode on success.
2360/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2361/// because it has been moved away.
2362/// Thus AddrInst must not be added in the matched instructions.
2363/// This state can happen when AddrInst is a sext, since it may be moved away.
2364/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2365/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002366bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002367 unsigned Depth,
2368 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002369 // Avoid exponential behavior on extremely deep expression trees.
2370 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002371
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002372 // By default, all matched instructions stay in place.
2373 if (MovedAway)
2374 *MovedAway = false;
2375
Chandler Carruthc8925912013-01-05 02:09:22 +00002376 switch (Opcode) {
2377 case Instruction::PtrToInt:
2378 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2379 return MatchAddr(AddrInst->getOperand(0), Depth);
2380 case Instruction::IntToPtr:
2381 // This inttoptr is a no-op if the integer type is pointer sized.
2382 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002383 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002384 return MatchAddr(AddrInst->getOperand(0), Depth);
2385 return false;
2386 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002387 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002388 // BitCast is always a noop, and we can handle it as long as it is
2389 // int->int or pointer->pointer (we don't want int<->fp or something).
2390 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2391 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2392 // Don't touch identity bitcasts. These were probably put here by LSR,
2393 // and we don't want to mess around with them. Assume it knows what it
2394 // is doing.
2395 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2396 return MatchAddr(AddrInst->getOperand(0), Depth);
2397 return false;
2398 case Instruction::Add: {
2399 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2400 ExtAddrMode BackupAddrMode = AddrMode;
2401 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002402 // Start a transaction at this point.
2403 // The LHS may match but not the RHS.
2404 // Therefore, we need a higher level restoration point to undo partially
2405 // matched operation.
2406 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2407 TPT.getRestorationPoint();
2408
Chandler Carruthc8925912013-01-05 02:09:22 +00002409 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2410 MatchAddr(AddrInst->getOperand(0), Depth+1))
2411 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002412
Chandler Carruthc8925912013-01-05 02:09:22 +00002413 // Restore the old addr mode info.
2414 AddrMode = BackupAddrMode;
2415 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002416 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002417
Chandler Carruthc8925912013-01-05 02:09:22 +00002418 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2419 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2420 MatchAddr(AddrInst->getOperand(1), Depth+1))
2421 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002422
Chandler Carruthc8925912013-01-05 02:09:22 +00002423 // Otherwise we definitely can't merge the ADD in.
2424 AddrMode = BackupAddrMode;
2425 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002426 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002427 break;
2428 }
2429 //case Instruction::Or:
2430 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2431 //break;
2432 case Instruction::Mul:
2433 case Instruction::Shl: {
2434 // Can only handle X*C and X << C.
2435 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002436 if (!RHS)
2437 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002438 int64_t Scale = RHS->getSExtValue();
2439 if (Opcode == Instruction::Shl)
2440 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002441
Chandler Carruthc8925912013-01-05 02:09:22 +00002442 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2443 }
2444 case Instruction::GetElementPtr: {
2445 // Scan the GEP. We check it if it contains constant offsets and at most
2446 // one variable offset.
2447 int VariableOperand = -1;
2448 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002449
Chandler Carruthc8925912013-01-05 02:09:22 +00002450 int64_t ConstantOffset = 0;
2451 const DataLayout *TD = TLI.getDataLayout();
2452 gep_type_iterator GTI = gep_type_begin(AddrInst);
2453 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2454 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2455 const StructLayout *SL = TD->getStructLayout(STy);
2456 unsigned Idx =
2457 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2458 ConstantOffset += SL->getElementOffset(Idx);
2459 } else {
2460 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2461 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2462 ConstantOffset += CI->getSExtValue()*TypeSize;
2463 } else if (TypeSize) { // Scales of zero don't do anything.
2464 // We only allow one variable index at the moment.
2465 if (VariableOperand != -1)
2466 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002467
Chandler Carruthc8925912013-01-05 02:09:22 +00002468 // Remember the variable index.
2469 VariableOperand = i;
2470 VariableScale = TypeSize;
2471 }
2472 }
2473 }
Stephen Lin837bba12013-07-15 17:55:02 +00002474
Chandler Carruthc8925912013-01-05 02:09:22 +00002475 // A common case is for the GEP to only do a constant offset. In this case,
2476 // just add it to the disp field and check validity.
2477 if (VariableOperand == -1) {
2478 AddrMode.BaseOffs += ConstantOffset;
2479 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2480 // Check to see if we can fold the base pointer in too.
2481 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2482 return true;
2483 }
2484 AddrMode.BaseOffs -= ConstantOffset;
2485 return false;
2486 }
2487
2488 // Save the valid addressing mode in case we can't match.
2489 ExtAddrMode BackupAddrMode = AddrMode;
2490 unsigned OldSize = AddrModeInsts.size();
2491
2492 // See if the scale and offset amount is valid for this target.
2493 AddrMode.BaseOffs += ConstantOffset;
2494
2495 // Match the base operand of the GEP.
2496 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2497 // If it couldn't be matched, just stuff the value in a register.
2498 if (AddrMode.HasBaseReg) {
2499 AddrMode = BackupAddrMode;
2500 AddrModeInsts.resize(OldSize);
2501 return false;
2502 }
2503 AddrMode.HasBaseReg = true;
2504 AddrMode.BaseReg = AddrInst->getOperand(0);
2505 }
2506
2507 // Match the remaining variable portion of the GEP.
2508 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2509 Depth)) {
2510 // If it couldn't be matched, try stuffing the base into a register
2511 // instead of matching it, and retrying the match of the scale.
2512 AddrMode = BackupAddrMode;
2513 AddrModeInsts.resize(OldSize);
2514 if (AddrMode.HasBaseReg)
2515 return false;
2516 AddrMode.HasBaseReg = true;
2517 AddrMode.BaseReg = AddrInst->getOperand(0);
2518 AddrMode.BaseOffs += ConstantOffset;
2519 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2520 VariableScale, Depth)) {
2521 // If even that didn't work, bail.
2522 AddrMode = BackupAddrMode;
2523 AddrModeInsts.resize(OldSize);
2524 return false;
2525 }
2526 }
2527
2528 return true;
2529 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002530 case Instruction::SExt:
2531 case Instruction::ZExt: {
2532 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2533 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002534 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002535
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002536 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002537 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002538 TypePromotionHelper::Action TPH =
2539 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002540 if (!TPH)
2541 return false;
2542
2543 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2544 TPT.getRestorationPoint();
2545 unsigned CreatedInsts = 0;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002546 Value *PromotedOperand =
2547 TPH(Ext, TPT, PromotedInsts, CreatedInsts, nullptr, nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002548 // SExt has been moved away.
2549 // Thus either it will be rematched later in the recursive calls or it is
2550 // gone. Anyway, we must not fold it into the addressing mode at this point.
2551 // E.g.,
2552 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002553 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002554 // addr = gep base, idx
2555 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002556 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002557 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2558 // addr = gep base, op <- match
2559 if (MovedAway)
2560 *MovedAway = true;
2561
2562 assert(PromotedOperand &&
2563 "TypePromotionHelper should have filtered out those cases");
2564
2565 ExtAddrMode BackupAddrMode = AddrMode;
2566 unsigned OldSize = AddrModeInsts.size();
2567
2568 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002569 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2570 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002571 AddrMode = BackupAddrMode;
2572 AddrModeInsts.resize(OldSize);
2573 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2574 TPT.rollback(LastKnownGood);
2575 return false;
2576 }
2577 return true;
2578 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002579 }
2580 return false;
2581}
2582
2583/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2584/// addressing mode. If Addr can't be added to AddrMode this returns false and
2585/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2586/// or intptr_t for the target.
2587///
2588bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002589 // Start a transaction at this point that we will rollback if the matching
2590 // fails.
2591 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2592 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002593 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2594 // Fold in immediates if legal for the target.
2595 AddrMode.BaseOffs += CI->getSExtValue();
2596 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2597 return true;
2598 AddrMode.BaseOffs -= CI->getSExtValue();
2599 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2600 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002601 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002602 AddrMode.BaseGV = GV;
2603 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2604 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002605 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002606 }
2607 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2608 ExtAddrMode BackupAddrMode = AddrMode;
2609 unsigned OldSize = AddrModeInsts.size();
2610
2611 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002612 bool MovedAway = false;
2613 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2614 // This instruction may have been move away. If so, there is nothing
2615 // to check here.
2616 if (MovedAway)
2617 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002618 // Okay, it's possible to fold this. Check to see if it is actually
2619 // *profitable* to do so. We use a simple cost model to avoid increasing
2620 // register pressure too much.
2621 if (I->hasOneUse() ||
2622 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2623 AddrModeInsts.push_back(I);
2624 return true;
2625 }
Stephen Lin837bba12013-07-15 17:55:02 +00002626
Chandler Carruthc8925912013-01-05 02:09:22 +00002627 // It isn't profitable to do this, roll back.
2628 //cerr << "NOT FOLDING: " << *I;
2629 AddrMode = BackupAddrMode;
2630 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002631 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002632 }
2633 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2634 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2635 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002636 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002637 } else if (isa<ConstantPointerNull>(Addr)) {
2638 // Null pointer gets folded without affecting the addressing mode.
2639 return true;
2640 }
2641
2642 // Worse case, the target should support [reg] addressing modes. :)
2643 if (!AddrMode.HasBaseReg) {
2644 AddrMode.HasBaseReg = true;
2645 AddrMode.BaseReg = Addr;
2646 // Still check for legality in case the target supports [imm] but not [i+r].
2647 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2648 return true;
2649 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002650 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002651 }
2652
2653 // If the base register is already taken, see if we can do [r+r].
2654 if (AddrMode.Scale == 0) {
2655 AddrMode.Scale = 1;
2656 AddrMode.ScaledReg = Addr;
2657 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2658 return true;
2659 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002660 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002661 }
2662 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002663 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002664 return false;
2665}
2666
2667/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2668/// inline asm call are due to memory operands. If so, return true, otherwise
2669/// return false.
2670static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2671 const TargetLowering &TLI) {
2672 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2673 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2674 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002675
Chandler Carruthc8925912013-01-05 02:09:22 +00002676 // Compute the constraint code and ConstraintType to use.
2677 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2678
2679 // If this asm operand is our Value*, and if it isn't an indirect memory
2680 // operand, we can't fold it!
2681 if (OpInfo.CallOperandVal == OpVal &&
2682 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2683 !OpInfo.isIndirect))
2684 return false;
2685 }
2686
2687 return true;
2688}
2689
2690/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2691/// memory use. If we find an obviously non-foldable instruction, return true.
2692/// Add the ultimately found memory instructions to MemoryUses.
2693static bool FindAllMemoryUses(Instruction *I,
2694 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Craig Topper71b7b682014-08-21 05:55:13 +00002695 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
Chandler Carruthc8925912013-01-05 02:09:22 +00002696 const TargetLowering &TLI) {
2697 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00002698 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00002699 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002700
Chandler Carruthc8925912013-01-05 02:09:22 +00002701 // If this is an obviously unfoldable instruction, bail out.
2702 if (!MightBeFoldableInst(I))
2703 return true;
2704
2705 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002706 for (Use &U : I->uses()) {
2707 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002708
Chandler Carruthcdf47882014-03-09 03:16:01 +00002709 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2710 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002711 continue;
2712 }
Stephen Lin837bba12013-07-15 17:55:02 +00002713
Chandler Carruthcdf47882014-03-09 03:16:01 +00002714 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2715 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002716 if (opNo == 0) return true; // Storing addr, not into addr.
2717 MemoryUses.push_back(std::make_pair(SI, opNo));
2718 continue;
2719 }
Stephen Lin837bba12013-07-15 17:55:02 +00002720
Chandler Carruthcdf47882014-03-09 03:16:01 +00002721 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002722 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2723 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002724
Chandler Carruthc8925912013-01-05 02:09:22 +00002725 // If this is a memory operand, we're cool, otherwise bail out.
2726 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2727 return true;
2728 continue;
2729 }
Stephen Lin837bba12013-07-15 17:55:02 +00002730
Chandler Carruthcdf47882014-03-09 03:16:01 +00002731 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002732 return true;
2733 }
2734
2735 return false;
2736}
2737
2738/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2739/// the use site that we're folding it into. If so, there is no cost to
2740/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2741/// that we know are live at the instruction already.
2742bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2743 Value *KnownLive2) {
2744 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002745 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002746 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002747
Chandler Carruthc8925912013-01-05 02:09:22 +00002748 // All values other than instructions and arguments (e.g. constants) are live.
2749 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002750
Chandler Carruthc8925912013-01-05 02:09:22 +00002751 // If Val is a constant sized alloca in the entry block, it is live, this is
2752 // true because it is just a reference to the stack/frame pointer, which is
2753 // live for the whole function.
2754 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2755 if (AI->isStaticAlloca())
2756 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002757
Chandler Carruthc8925912013-01-05 02:09:22 +00002758 // Check to see if this value is already used in the memory instruction's
2759 // block. If so, it's already live into the block at the very least, so we
2760 // can reasonably fold it.
2761 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2762}
2763
2764/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2765/// mode of the machine to fold the specified instruction into a load or store
2766/// that ultimately uses it. However, the specified instruction has multiple
2767/// uses. Given this, it may actually increase register pressure to fold it
2768/// into the load. For example, consider this code:
2769///
2770/// X = ...
2771/// Y = X+1
2772/// use(Y) -> nonload/store
2773/// Z = Y+1
2774/// load Z
2775///
2776/// In this case, Y has multiple uses, and can be folded into the load of Z
2777/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2778/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2779/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2780/// number of computations either.
2781///
2782/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2783/// X was live across 'load Z' for other reasons, we actually *would* want to
2784/// fold the addressing mode in the Z case. This would make Y die earlier.
2785bool AddressingModeMatcher::
2786IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2787 ExtAddrMode &AMAfter) {
2788 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002789
Chandler Carruthc8925912013-01-05 02:09:22 +00002790 // AMBefore is the addressing mode before this instruction was folded into it,
2791 // and AMAfter is the addressing mode after the instruction was folded. Get
2792 // the set of registers referenced by AMAfter and subtract out those
2793 // referenced by AMBefore: this is the set of values which folding in this
2794 // address extends the lifetime of.
2795 //
2796 // Note that there are only two potential values being referenced here,
2797 // BaseReg and ScaleReg (global addresses are always available, as are any
2798 // folded immediates).
2799 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002800
Chandler Carruthc8925912013-01-05 02:09:22 +00002801 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2802 // lifetime wasn't extended by adding this instruction.
2803 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002804 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002805 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002806 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002807
2808 // If folding this instruction (and it's subexprs) didn't extend any live
2809 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002810 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002811 return true;
2812
2813 // If all uses of this instruction are ultimately load/store/inlineasm's,
2814 // check to see if their addressing modes will include this instruction. If
2815 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2816 // uses.
2817 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2818 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2819 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2820 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002821
Chandler Carruthc8925912013-01-05 02:09:22 +00002822 // Now that we know that all uses of this instruction are part of a chain of
2823 // computation involving only operations that could theoretically be folded
2824 // into a memory use, loop over each of these uses and see if they could
2825 // *actually* fold the instruction.
2826 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2827 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2828 Instruction *User = MemoryUses[i].first;
2829 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002830
Chandler Carruthc8925912013-01-05 02:09:22 +00002831 // Get the access type of this use. If the use isn't a pointer, we don't
2832 // know what it accesses.
2833 Value *Address = User->getOperand(OpNo);
2834 if (!Address->getType()->isPointerTy())
2835 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002836 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002837
Chandler Carruthc8925912013-01-05 02:09:22 +00002838 // Do a match against the root of this address, ignoring profitability. This
2839 // will tell us if the addressing mode for the memory operation will
2840 // *actually* cover the shared instruction.
2841 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002842 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2843 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002844 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002845 MemoryInst, Result, InsertedTruncs,
2846 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002847 Matcher.IgnoreProfitability = true;
2848 bool Success = Matcher.MatchAddr(Address, 0);
2849 (void)Success; assert(Success && "Couldn't select *anything*?");
2850
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002851 // The match was to check the profitability, the changes made are not
2852 // part of the original matcher. Therefore, they should be dropped
2853 // otherwise the original matcher will not present the right state.
2854 TPT.rollback(LastKnownGood);
2855
Chandler Carruthc8925912013-01-05 02:09:22 +00002856 // If the match didn't cover I, then it won't be shared by it.
2857 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2858 I) == MatchedAddrModeInsts.end())
2859 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002860
Chandler Carruthc8925912013-01-05 02:09:22 +00002861 MatchedAddrModeInsts.clear();
2862 }
Stephen Lin837bba12013-07-15 17:55:02 +00002863
Chandler Carruthc8925912013-01-05 02:09:22 +00002864 return true;
2865}
2866
2867} // end anonymous namespace
2868
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002869/// IsNonLocalValue - Return true if the specified values are defined in a
2870/// different basic block than BB.
2871static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2872 if (Instruction *I = dyn_cast<Instruction>(V))
2873 return I->getParent() != BB;
2874 return false;
2875}
2876
Bob Wilson53bdae32009-12-03 21:47:07 +00002877/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002878/// addressing modes that can do significant amounts of computation. As such,
2879/// instruction selection will try to get the load or store to do as much
2880/// computation as possible for the program. The problem is that isel can only
2881/// see within a single block. As such, we sink as much legal addressing mode
2882/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002883///
2884/// This method is used to optimize both load/store and inline asms with memory
2885/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002886bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002887 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002888 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002889
2890 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002891 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002892 SmallVector<Value*, 8> worklist;
2893 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002894 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002895
Owen Anderson8ba5f392010-11-27 08:15:55 +00002896 // Use a worklist to iteratively look through PHI nodes, and ensure that
2897 // the addressing mode obtained from the non-PHI roots of the graph
2898 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00002899 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002900 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002901 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002902 SmallVector<Instruction*, 16> AddrModeInsts;
2903 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002904 TypePromotionTransaction TPT;
2905 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2906 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002907 while (!worklist.empty()) {
2908 Value *V = worklist.back();
2909 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002910
Owen Anderson8ba5f392010-11-27 08:15:55 +00002911 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00002912 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00002913 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002914 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002915 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002916
Owen Anderson8ba5f392010-11-27 08:15:55 +00002917 // For a PHI node, push all of its incoming values.
2918 if (PHINode *P = dyn_cast<PHINode>(V)) {
2919 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2920 worklist.push_back(P->getIncomingValue(i));
2921 continue;
2922 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002923
Owen Anderson8ba5f392010-11-27 08:15:55 +00002924 // For non-PHIs, determine the addressing mode being computed.
2925 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002926 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2927 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2928 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002929
2930 // This check is broken into two cases with very similar code to avoid using
2931 // getNumUses() as much as possible. Some values have a lot of uses, so
2932 // calling getNumUses() unconditionally caused a significant compile-time
2933 // regression.
2934 if (!Consensus) {
2935 Consensus = V;
2936 AddrMode = NewAddrMode;
2937 AddrModeInsts = NewAddrModeInsts;
2938 continue;
2939 } else if (NewAddrMode == AddrMode) {
2940 if (!IsNumUsesConsensusValid) {
2941 NumUsesConsensus = Consensus->getNumUses();
2942 IsNumUsesConsensusValid = true;
2943 }
2944
2945 // Ensure that the obtained addressing mode is equivalent to that obtained
2946 // for all other roots of the PHI traversal. Also, when choosing one
2947 // such root as representative, select the one with the most uses in order
2948 // to keep the cost modeling heuristics in AddressingModeMatcher
2949 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002950 unsigned NumUses = V->getNumUses();
2951 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002952 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002953 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002954 AddrModeInsts = NewAddrModeInsts;
2955 }
2956 continue;
2957 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002958
Craig Topperc0196b12014-04-14 00:51:57 +00002959 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002960 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002961 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002962
Owen Anderson8ba5f392010-11-27 08:15:55 +00002963 // If the addressing mode couldn't be determined, or if multiple different
2964 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002965 if (!Consensus) {
2966 TPT.rollback(LastKnownGood);
2967 return false;
2968 }
2969 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002970
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002971 // Check to see if any of the instructions supersumed by this addr mode are
2972 // non-local to I's BB.
2973 bool AnyNonLocal = false;
2974 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002975 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002976 AnyNonLocal = true;
2977 break;
2978 }
2979 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002980
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002981 // If all the instructions matched are already in this BB, don't do anything.
2982 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002983 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002984 return false;
2985 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002986
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002987 // Insert this computation right after this user. Since our caller is
2988 // scanning from the top of the BB to the bottom, reuse of the expr are
2989 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002990 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002991
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002992 // Now that we determined the addressing expression we want to use and know
2993 // that we have to sink it into this block. Check to see if we have already
2994 // done this for some other load/store instr in this block. If so, reuse the
2995 // computation.
2996 Value *&SunkAddr = SunkAddrs[Addr];
2997 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002998 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002999 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003000 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003001 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00003002 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
3003 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
3004 // By default, we use the GEP-based method when AA is used later. This
3005 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3006 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003007 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00003008 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003009 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003010
3011 // First, find the pointer.
3012 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3013 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003014 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003015 }
3016
3017 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3018 // We can't add more than one pointer together, nor can we scale a
3019 // pointer (both of which seem meaningless).
3020 if (ResultPtr || AddrMode.Scale != 1)
3021 return false;
3022
3023 ResultPtr = AddrMode.ScaledReg;
3024 AddrMode.Scale = 0;
3025 }
3026
3027 if (AddrMode.BaseGV) {
3028 if (ResultPtr)
3029 return false;
3030
3031 ResultPtr = AddrMode.BaseGV;
3032 }
3033
3034 // If the real base value actually came from an inttoptr, then the matcher
3035 // will look through it and provide only the integer value. In that case,
3036 // use it here.
3037 if (!ResultPtr && AddrMode.BaseReg) {
3038 ResultPtr =
3039 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003040 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003041 } else if (!ResultPtr && AddrMode.Scale == 1) {
3042 ResultPtr =
3043 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3044 AddrMode.Scale = 0;
3045 }
3046
3047 if (!ResultPtr &&
3048 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3049 SunkAddr = Constant::getNullValue(Addr->getType());
3050 } else if (!ResultPtr) {
3051 return false;
3052 } else {
3053 Type *I8PtrTy =
3054 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3055
3056 // Start with the base register. Do this first so that subsequent address
3057 // matching finds it last, which will prevent it from trying to match it
3058 // as the scaled value in case it happens to be a mul. That would be
3059 // problematic if we've sunk a different mul for the scale, because then
3060 // we'd end up sinking both muls.
3061 if (AddrMode.BaseReg) {
3062 Value *V = AddrMode.BaseReg;
3063 if (V->getType() != IntPtrTy)
3064 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3065
3066 ResultIndex = V;
3067 }
3068
3069 // Add the scale value.
3070 if (AddrMode.Scale) {
3071 Value *V = AddrMode.ScaledReg;
3072 if (V->getType() == IntPtrTy) {
3073 // done.
3074 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3075 cast<IntegerType>(V->getType())->getBitWidth()) {
3076 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3077 } else {
3078 // It is only safe to sign extend the BaseReg if we know that the math
3079 // required to create it did not overflow before we extend it. Since
3080 // the original IR value was tossed in favor of a constant back when
3081 // the AddrMode was created we need to bail out gracefully if widths
3082 // do not match instead of extending it.
3083 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3084 if (I && (ResultIndex != AddrMode.BaseReg))
3085 I->eraseFromParent();
3086 return false;
3087 }
3088
3089 if (AddrMode.Scale != 1)
3090 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3091 "sunkaddr");
3092 if (ResultIndex)
3093 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3094 else
3095 ResultIndex = V;
3096 }
3097
3098 // Add in the Base Offset if present.
3099 if (AddrMode.BaseOffs) {
3100 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3101 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003102 // We need to add this separately from the scale above to help with
3103 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003104 if (ResultPtr->getType() != I8PtrTy)
3105 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3106 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3107 }
3108
3109 ResultIndex = V;
3110 }
3111
3112 if (!ResultIndex) {
3113 SunkAddr = ResultPtr;
3114 } else {
3115 if (ResultPtr->getType() != I8PtrTy)
3116 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3117 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3118 }
3119
3120 if (SunkAddr->getType() != Addr->getType())
3121 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3122 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003123 } else {
David Greene74e2d492010-01-05 01:27:11 +00003124 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003125 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00003126 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003127 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003128
3129 // Start with the base register. Do this first so that subsequent address
3130 // matching finds it last, which will prevent it from trying to match it
3131 // as the scaled value in case it happens to be a mul. That would be
3132 // problematic if we've sunk a different mul for the scale, because then
3133 // we'd end up sinking both muls.
3134 if (AddrMode.BaseReg) {
3135 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003136 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003137 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003138 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003139 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003140 Result = V;
3141 }
3142
3143 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003144 if (AddrMode.Scale) {
3145 Value *V = AddrMode.ScaledReg;
3146 if (V->getType() == IntPtrTy) {
3147 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003148 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003149 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003150 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3151 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003152 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003153 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003154 // It is only safe to sign extend the BaseReg if we know that the math
3155 // required to create it did not overflow before we extend it. Since
3156 // the original IR value was tossed in favor of a constant back when
3157 // the AddrMode was created we need to bail out gracefully if widths
3158 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003159 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003160 if (I && (Result != AddrMode.BaseReg))
3161 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003162 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003163 }
3164 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003165 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3166 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003167 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003168 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003169 else
3170 Result = V;
3171 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003172
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003173 // Add in the BaseGV if present.
3174 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003175 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003176 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003177 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003178 else
3179 Result = V;
3180 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003181
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003182 // Add in the Base Offset if present.
3183 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003184 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003185 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003186 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003187 else
3188 Result = V;
3189 }
3190
Craig Topperc0196b12014-04-14 00:51:57 +00003191 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003192 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003193 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003194 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003195 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003196
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003197 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003198
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003199 // If we have no uses, recursively delete the value and all dead instructions
3200 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003201 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003202 // This can cause recursive deletion, which can invalidate our iterator.
3203 // Use a WeakVH to hold onto it in case this happens.
3204 WeakVH IterHandle(CurInstIterator);
3205 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003206
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003207 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003208
3209 if (IterHandle != CurInstIterator) {
3210 // If the iterator instruction was recursively deleted, start over at the
3211 // start of the block.
3212 CurInstIterator = BB->begin();
3213 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003214 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003215 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003216 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003217 return true;
3218}
3219
Evan Cheng1da25002008-02-26 02:42:37 +00003220/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00003221/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00003222/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00003223bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003224 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003225
Nadav Rotem465834c2012-07-24 10:51:42 +00003226 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00003227 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003228 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003229 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3230 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003231
Evan Cheng1da25002008-02-26 02:42:37 +00003232 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003233 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003234
Eli Friedman666bbe32008-02-26 18:37:49 +00003235 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3236 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003237 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00003238 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003239 } else if (OpInfo.Type == InlineAsm::isInput)
3240 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003241 }
3242
3243 return MadeChange;
3244}
3245
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003246/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3247/// sign extensions.
3248static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3249 assert(!Inst->use_empty() && "Input must have at least one use");
3250 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3251 bool IsSExt = isa<SExtInst>(FirstUser);
3252 Type *ExtTy = FirstUser->getType();
3253 for (const User *U : Inst->users()) {
3254 const Instruction *UI = cast<Instruction>(U);
3255 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3256 return false;
3257 Type *CurTy = UI->getType();
3258 // Same input and output types: Same instruction after CSE.
3259 if (CurTy == ExtTy)
3260 continue;
3261
3262 // If IsSExt is true, we are in this situation:
3263 // a = Inst
3264 // b = sext ty1 a to ty2
3265 // c = sext ty1 a to ty3
3266 // Assuming ty2 is shorter than ty3, this could be turned into:
3267 // a = Inst
3268 // b = sext ty1 a to ty2
3269 // c = sext ty2 b to ty3
3270 // However, the last sext is not free.
3271 if (IsSExt)
3272 return false;
3273
3274 // This is a ZExt, maybe this is free to extend from one type to another.
3275 // In that case, we would not account for a different use.
3276 Type *NarrowTy;
3277 Type *LargeTy;
3278 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3279 CurTy->getScalarType()->getIntegerBitWidth()) {
3280 NarrowTy = CurTy;
3281 LargeTy = ExtTy;
3282 } else {
3283 NarrowTy = ExtTy;
3284 LargeTy = CurTy;
3285 }
3286
3287 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3288 return false;
3289 }
3290 // All uses are the same or can be derived from one another for free.
3291 return true;
3292}
3293
3294/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3295/// load instruction.
3296/// If an ext(load) can be formed, it is returned via \p LI for the load
3297/// and \p Inst for the extension.
3298/// Otherwise LI == nullptr and Inst == nullptr.
3299/// When some promotion happened, \p TPT contains the proper state to
3300/// revert them.
3301///
3302/// \return true when promoting was necessary to expose the ext(load)
3303/// opportunity, false otherwise.
3304///
3305/// Example:
3306/// \code
3307/// %ld = load i32* %addr
3308/// %add = add nuw i32 %ld, 4
3309/// %zext = zext i32 %add to i64
3310/// \endcode
3311/// =>
3312/// \code
3313/// %ld = load i32* %addr
3314/// %zext = zext i32 %ld to i64
3315/// %add = add nuw i64 %zext, 4
3316/// \encode
3317/// Thanks to the promotion, we can match zext(load i32*) to i64.
3318bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3319 LoadInst *&LI, Instruction *&Inst,
3320 const SmallVectorImpl<Instruction *> &Exts,
3321 unsigned CreatedInsts = 0) {
3322 // Iterate over all the extensions to see if one form an ext(load).
3323 for (auto I : Exts) {
3324 // Check if we directly have ext(load).
3325 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3326 Inst = I;
3327 // No promotion happened here.
3328 return false;
3329 }
3330 // Check whether or not we want to do any promotion.
3331 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3332 continue;
3333 // Get the action to perform the promotion.
3334 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3335 I, InsertedTruncsSet, *TLI, PromotedInsts);
3336 // Check if we can promote.
3337 if (!TPH)
3338 continue;
3339 // Save the current state.
3340 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3341 TPT.getRestorationPoint();
3342 SmallVector<Instruction *, 4> NewExts;
3343 unsigned NewCreatedInsts = 0;
3344 // Promote.
3345 Value *PromotedVal =
3346 TPH(I, TPT, PromotedInsts, NewCreatedInsts, &NewExts, nullptr);
3347 assert(PromotedVal &&
3348 "TypePromotionHelper should have filtered out those cases");
3349
3350 // We would be able to merge only one extension in a load.
3351 // Therefore, if we have more than 1 new extension we heuristically
3352 // cut this search path, because it means we degrade the code quality.
3353 // With exactly 2, the transformation is neutral, because we will merge
3354 // one extension but leave one. However, we optimistically keep going,
3355 // because the new extension may be removed too.
3356 unsigned TotalCreatedInsts = CreatedInsts + NewCreatedInsts;
3357 if (!StressExtLdPromotion &&
3358 (TotalCreatedInsts > 1 ||
3359 !isPromotedInstructionLegal(*TLI, PromotedVal))) {
3360 // The promotion is not profitable, rollback to the previous state.
3361 TPT.rollback(LastKnownGood);
3362 continue;
3363 }
3364 // The promotion is profitable.
3365 // Check if it exposes an ext(load).
3366 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInsts);
3367 if (LI && (StressExtLdPromotion || NewCreatedInsts == 0 ||
3368 // If we have created a new extension, i.e., now we have two
3369 // extensions. We must make sure one of them is merged with
3370 // the load, otherwise we may degrade the code quality.
3371 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3372 // Promotion happened.
3373 return true;
3374 // If this does not help to expose an ext(load) then, rollback.
3375 TPT.rollback(LastKnownGood);
3376 }
3377 // None of the extension can form an ext(load).
3378 LI = nullptr;
3379 Inst = nullptr;
3380 return false;
3381}
3382
Dan Gohman99429a02009-10-16 20:59:35 +00003383/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3384/// basic block as the load, unless conditions are unfavorable. This allows
3385/// SelectionDAG to fold the extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003386/// \p I[in/out] the extension may be modified during the process if some
3387/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003388///
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003389bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3390 // Try to promote a chain of computation if it allows to form
3391 // an extended load.
3392 TypePromotionTransaction TPT;
3393 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3394 TPT.getRestorationPoint();
3395 SmallVector<Instruction *, 1> Exts;
3396 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003397 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003398 LoadInst *LI = nullptr;
3399 Instruction *OldExt = I;
3400 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3401 if (!LI || !I) {
3402 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3403 "the code must remain the same");
3404 I = OldExt;
3405 return false;
3406 }
Dan Gohman99429a02009-10-16 20:59:35 +00003407
3408 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003409 // Make the cheap checks first if we did not promote.
3410 // If we promoted, we need to check if it is indeed profitable.
3411 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003412 return false;
3413
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003414 EVT VT = TLI->getValueType(I->getType());
3415 EVT LoadVT = TLI->getValueType(LI->getType());
3416
Dan Gohman99429a02009-10-16 20:59:35 +00003417 // If the load has other users and the truncate is not free, this probably
3418 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003419 if (!LI->hasOneUse() && TLI &&
3420 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003421 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3422 I = OldExt;
3423 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003424 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003425 }
Dan Gohman99429a02009-10-16 20:59:35 +00003426
3427 // Check whether the target supports casts folded into loads.
3428 unsigned LType;
3429 if (isa<ZExtInst>(I))
3430 LType = ISD::ZEXTLOAD;
3431 else {
3432 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3433 LType = ISD::SEXTLOAD;
3434 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003435 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003436 I = OldExt;
3437 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003438 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003439 }
Dan Gohman99429a02009-10-16 20:59:35 +00003440
3441 // Move the extend into the same block as the load, so that SelectionDAG
3442 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003443 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003444 I->removeFromParent();
3445 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003446 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003447 return true;
3448}
3449
Evan Chengd3d80172007-12-05 23:58:20 +00003450bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3451 BasicBlock *DefBB = I->getParent();
3452
Bob Wilsonff714f92010-09-21 21:44:14 +00003453 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003454 // other uses of the source with result of extension.
3455 Value *Src = I->getOperand(0);
3456 if (Src->hasOneUse())
3457 return false;
3458
Evan Cheng2011df42007-12-13 07:50:36 +00003459 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003460 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003461 return false;
3462
Evan Cheng7bc89422007-12-12 00:51:06 +00003463 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003464 // this block.
3465 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003466 return false;
3467
Evan Chengd3d80172007-12-05 23:58:20 +00003468 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003469 for (User *U : I->users()) {
3470 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003471
3472 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003473 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003474 if (UserBB == DefBB) continue;
3475 DefIsLiveOut = true;
3476 break;
3477 }
3478 if (!DefIsLiveOut)
3479 return false;
3480
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003481 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003482 for (User *U : Src->users()) {
3483 Instruction *UI = cast<Instruction>(U);
3484 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003485 if (UserBB == DefBB) continue;
3486 // Be conservative. We don't want this xform to end up introducing
3487 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003488 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003489 return false;
3490 }
3491
Evan Chengd3d80172007-12-05 23:58:20 +00003492 // InsertedTruncs - Only insert one trunc in each block once.
3493 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3494
3495 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003496 for (Use &U : Src->uses()) {
3497 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003498
3499 // Figure out which BB this ext is used in.
3500 BasicBlock *UserBB = User->getParent();
3501 if (UserBB == DefBB) continue;
3502
3503 // Both src and def are live in this block. Rewrite the use.
3504 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3505
3506 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003507 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003508 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003509 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003510 }
3511
3512 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003513 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003514 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003515 MadeChange = true;
3516 }
3517
3518 return MadeChange;
3519}
3520
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003521/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3522/// turned into an explicit branch.
3523static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3524 // FIXME: This should use the same heuristics as IfConversion to determine
3525 // whether a select is better represented as a branch. This requires that
3526 // branch probability metadata is preserved for the select, which is not the
3527 // case currently.
3528
3529 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3530
3531 // If the branch is predicted right, an out of order CPU can avoid blocking on
3532 // the compare. Emit cmovs on compares with a memory operand as branches to
3533 // avoid stalls on the load from memory. If the compare has more than one use
3534 // there's probably another cmov or setcc around so it's not worth emitting a
3535 // branch.
3536 if (!Cmp)
3537 return false;
3538
3539 Value *CmpOp0 = Cmp->getOperand(0);
3540 Value *CmpOp1 = Cmp->getOperand(1);
3541
3542 // We check that the memory operand has one use to avoid uses of the loaded
3543 // value directly after the compare, making branches unprofitable.
3544 return Cmp->hasOneUse() &&
3545 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3546 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3547}
3548
3549
Nadav Rotem9d832022012-09-02 12:10:19 +00003550/// If we have a SelectInst that will likely profit from branch prediction,
3551/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003552bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003553 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3554
3555 // Can we convert the 'select' to CF ?
3556 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003557 return false;
3558
Nadav Rotem9d832022012-09-02 12:10:19 +00003559 TargetLowering::SelectSupportKind SelectKind;
3560 if (VectorCond)
3561 SelectKind = TargetLowering::VectorMaskSelect;
3562 else if (SI->getType()->isVectorTy())
3563 SelectKind = TargetLowering::ScalarCondVectorVal;
3564 else
3565 SelectKind = TargetLowering::ScalarValSelect;
3566
3567 // Do we have efficient codegen support for this kind of 'selects' ?
3568 if (TLI->isSelectSupported(SelectKind)) {
3569 // We have efficient codegen support for the select instruction.
3570 // Check if it is profitable to keep this 'select'.
3571 if (!TLI->isPredictableSelectExpensive() ||
3572 !isFormingBranchFromSelectProfitable(SI))
3573 return false;
3574 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003575
3576 ModifiedDT = true;
3577
3578 // First, we split the block containing the select into 2 blocks.
3579 BasicBlock *StartBlock = SI->getParent();
3580 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3581 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3582
3583 // Create a new block serving as the landing pad for the branch.
3584 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3585 NextBlock->getParent(), NextBlock);
3586
3587 // Move the unconditional branch from the block with the select in it into our
3588 // landing pad block.
3589 StartBlock->getTerminator()->eraseFromParent();
3590 BranchInst::Create(NextBlock, SmallBlock);
3591
3592 // Insert the real conditional branch based on the original condition.
3593 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3594
3595 // The select itself is replaced with a PHI Node.
3596 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3597 PN->takeName(SI);
3598 PN->addIncoming(SI->getTrueValue(), StartBlock);
3599 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3600 SI->replaceAllUsesWith(PN);
3601 SI->eraseFromParent();
3602
3603 // Instruct OptimizeBlock to skip to the next block.
3604 CurInstIterator = StartBlock->end();
3605 ++NumSelectsExpanded;
3606 return true;
3607}
3608
Benjamin Kramer573ff362014-03-01 17:24:40 +00003609static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003610 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3611 int SplatElem = -1;
3612 for (unsigned i = 0; i < Mask.size(); ++i) {
3613 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3614 return false;
3615 SplatElem = Mask[i];
3616 }
3617
3618 return true;
3619}
3620
3621/// Some targets have expensive vector shifts if the lanes aren't all the same
3622/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3623/// it's often worth sinking a shufflevector splat down to its use so that
3624/// codegen can spot all lanes are identical.
3625bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3626 BasicBlock *DefBB = SVI->getParent();
3627
3628 // Only do this xform if variable vector shifts are particularly expensive.
3629 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3630 return false;
3631
3632 // We only expect better codegen by sinking a shuffle if we can recognise a
3633 // constant splat.
3634 if (!isBroadcastShuffle(SVI))
3635 return false;
3636
3637 // InsertedShuffles - Only insert a shuffle in each block once.
3638 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3639
3640 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003641 for (User *U : SVI->users()) {
3642 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003643
3644 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003645 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003646 if (UserBB == DefBB) continue;
3647
3648 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003649 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003650
3651 // Everything checks out, sink the shuffle if the user's block doesn't
3652 // already have a copy.
3653 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3654
3655 if (!InsertedShuffle) {
3656 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3657 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3658 SVI->getOperand(1),
3659 SVI->getOperand(2), "", InsertPt);
3660 }
3661
Chandler Carruthcdf47882014-03-09 03:16:01 +00003662 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003663 MadeChange = true;
3664 }
3665
3666 // If we removed all uses, nuke the shuffle.
3667 if (SVI->use_empty()) {
3668 SVI->eraseFromParent();
3669 MadeChange = true;
3670 }
3671
3672 return MadeChange;
3673}
3674
Quentin Colombetc32615d2014-10-31 17:52:53 +00003675namespace {
3676/// \brief Helper class to promote a scalar operation to a vector one.
3677/// This class is used to move downward extractelement transition.
3678/// E.g.,
3679/// a = vector_op <2 x i32>
3680/// b = extractelement <2 x i32> a, i32 0
3681/// c = scalar_op b
3682/// store c
3683///
3684/// =>
3685/// a = vector_op <2 x i32>
3686/// c = vector_op a (equivalent to scalar_op on the related lane)
3687/// * d = extractelement <2 x i32> c, i32 0
3688/// * store d
3689/// Assuming both extractelement and store can be combine, we get rid of the
3690/// transition.
3691class VectorPromoteHelper {
3692 /// Used to perform some checks on the legality of vector operations.
3693 const TargetLowering &TLI;
3694
3695 /// Used to estimated the cost of the promoted chain.
3696 const TargetTransformInfo &TTI;
3697
3698 /// The transition being moved downwards.
3699 Instruction *Transition;
3700 /// The sequence of instructions to be promoted.
3701 SmallVector<Instruction *, 4> InstsToBePromoted;
3702 /// Cost of combining a store and an extract.
3703 unsigned StoreExtractCombineCost;
3704 /// Instruction that will be combined with the transition.
3705 Instruction *CombineInst;
3706
3707 /// \brief The instruction that represents the current end of the transition.
3708 /// Since we are faking the promotion until we reach the end of the chain
3709 /// of computation, we need a way to get the current end of the transition.
3710 Instruction *getEndOfTransition() const {
3711 if (InstsToBePromoted.empty())
3712 return Transition;
3713 return InstsToBePromoted.back();
3714 }
3715
3716 /// \brief Return the index of the original value in the transition.
3717 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3718 /// c, is at index 0.
3719 unsigned getTransitionOriginalValueIdx() const {
3720 assert(isa<ExtractElementInst>(Transition) &&
3721 "Other kind of transitions are not supported yet");
3722 return 0;
3723 }
3724
3725 /// \brief Return the index of the index in the transition.
3726 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3727 /// is at index 1.
3728 unsigned getTransitionIdx() const {
3729 assert(isa<ExtractElementInst>(Transition) &&
3730 "Other kind of transitions are not supported yet");
3731 return 1;
3732 }
3733
3734 /// \brief Get the type of the transition.
3735 /// This is the type of the original value.
3736 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3737 /// transition is <2 x i32>.
3738 Type *getTransitionType() const {
3739 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3740 }
3741
3742 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3743 /// I.e., we have the following sequence:
3744 /// Def = Transition <ty1> a to <ty2>
3745 /// b = ToBePromoted <ty2> Def, ...
3746 /// =>
3747 /// b = ToBePromoted <ty1> a, ...
3748 /// Def = Transition <ty1> ToBePromoted to <ty2>
3749 void promoteImpl(Instruction *ToBePromoted);
3750
3751 /// \brief Check whether or not it is profitable to promote all the
3752 /// instructions enqueued to be promoted.
3753 bool isProfitableToPromote() {
3754 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3755 unsigned Index = isa<ConstantInt>(ValIdx)
3756 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3757 : -1;
3758 Type *PromotedType = getTransitionType();
3759
3760 StoreInst *ST = cast<StoreInst>(CombineInst);
3761 unsigned AS = ST->getPointerAddressSpace();
3762 unsigned Align = ST->getAlignment();
3763 // Check if this store is supported.
3764 if (!TLI.allowsMisalignedMemoryAccesses(
Ahmed Bougacha026600d2014-11-12 23:05:03 +00003765 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00003766 // If this is not supported, there is no way we can combine
3767 // the extract with the store.
3768 return false;
3769 }
3770
3771 // The scalar chain of computation has to pay for the transition
3772 // scalar to vector.
3773 // The vector chain has to account for the combining cost.
3774 uint64_t ScalarCost =
3775 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3776 uint64_t VectorCost = StoreExtractCombineCost;
3777 for (const auto &Inst : InstsToBePromoted) {
3778 // Compute the cost.
3779 // By construction, all instructions being promoted are arithmetic ones.
3780 // Moreover, one argument is a constant that can be viewed as a splat
3781 // constant.
3782 Value *Arg0 = Inst->getOperand(0);
3783 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3784 isa<ConstantFP>(Arg0);
3785 TargetTransformInfo::OperandValueKind Arg0OVK =
3786 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3787 : TargetTransformInfo::OK_AnyValue;
3788 TargetTransformInfo::OperandValueKind Arg1OVK =
3789 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3790 : TargetTransformInfo::OK_AnyValue;
3791 ScalarCost += TTI.getArithmeticInstrCost(
3792 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3793 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3794 Arg0OVK, Arg1OVK);
3795 }
3796 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3797 << ScalarCost << "\nVector: " << VectorCost << '\n');
3798 return ScalarCost > VectorCost;
3799 }
3800
3801 /// \brief Generate a constant vector with \p Val with the same
3802 /// number of elements as the transition.
3803 /// \p UseSplat defines whether or not \p Val should be replicated
3804 /// accross the whole vector.
3805 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3806 /// otherwise we generate a vector with as many undef as possible:
3807 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3808 /// used at the index of the extract.
3809 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3810 unsigned ExtractIdx = UINT_MAX;
3811 if (!UseSplat) {
3812 // If we cannot determine where the constant must be, we have to
3813 // use a splat constant.
3814 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3815 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3816 ExtractIdx = CstVal->getSExtValue();
3817 else
3818 UseSplat = true;
3819 }
3820
3821 unsigned End = getTransitionType()->getVectorNumElements();
3822 if (UseSplat)
3823 return ConstantVector::getSplat(End, Val);
3824
3825 SmallVector<Constant *, 4> ConstVec;
3826 UndefValue *UndefVal = UndefValue::get(Val->getType());
3827 for (unsigned Idx = 0; Idx != End; ++Idx) {
3828 if (Idx == ExtractIdx)
3829 ConstVec.push_back(Val);
3830 else
3831 ConstVec.push_back(UndefVal);
3832 }
3833 return ConstantVector::get(ConstVec);
3834 }
3835
3836 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3837 /// in \p Use can trigger undefined behavior.
3838 static bool canCauseUndefinedBehavior(const Instruction *Use,
3839 unsigned OperandIdx) {
3840 // This is not safe to introduce undef when the operand is on
3841 // the right hand side of a division-like instruction.
3842 if (OperandIdx != 1)
3843 return false;
3844 switch (Use->getOpcode()) {
3845 default:
3846 return false;
3847 case Instruction::SDiv:
3848 case Instruction::UDiv:
3849 case Instruction::SRem:
3850 case Instruction::URem:
3851 return true;
3852 case Instruction::FDiv:
3853 case Instruction::FRem:
3854 return !Use->hasNoNaNs();
3855 }
3856 llvm_unreachable(nullptr);
3857 }
3858
3859public:
3860 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3861 Instruction *Transition, unsigned CombineCost)
3862 : TLI(TLI), TTI(TTI), Transition(Transition),
3863 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3864 assert(Transition && "Do not know how to promote null");
3865 }
3866
3867 /// \brief Check if we can promote \p ToBePromoted to \p Type.
3868 bool canPromote(const Instruction *ToBePromoted) const {
3869 // We could support CastInst too.
3870 return isa<BinaryOperator>(ToBePromoted);
3871 }
3872
3873 /// \brief Check if it is profitable to promote \p ToBePromoted
3874 /// by moving downward the transition through.
3875 bool shouldPromote(const Instruction *ToBePromoted) const {
3876 // Promote only if all the operands can be statically expanded.
3877 // Indeed, we do not want to introduce any new kind of transitions.
3878 for (const Use &U : ToBePromoted->operands()) {
3879 const Value *Val = U.get();
3880 if (Val == getEndOfTransition()) {
3881 // If the use is a division and the transition is on the rhs,
3882 // we cannot promote the operation, otherwise we may create a
3883 // division by zero.
3884 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3885 return false;
3886 continue;
3887 }
3888 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3889 !isa<ConstantFP>(Val))
3890 return false;
3891 }
3892 // Check that the resulting operation is legal.
3893 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3894 if (!ISDOpcode)
3895 return false;
3896 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00003897 TLI.isOperationLegalOrCustom(
3898 ISDOpcode, TLI.getValueType(getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00003899 }
3900
3901 /// \brief Check whether or not \p Use can be combined
3902 /// with the transition.
3903 /// I.e., is it possible to do Use(Transition) => AnotherUse?
3904 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3905
3906 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3907 void enqueueForPromotion(Instruction *ToBePromoted) {
3908 InstsToBePromoted.push_back(ToBePromoted);
3909 }
3910
3911 /// \brief Set the instruction that will be combined with the transition.
3912 void recordCombineInstruction(Instruction *ToBeCombined) {
3913 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3914 CombineInst = ToBeCombined;
3915 }
3916
3917 /// \brief Promote all the instructions enqueued for promotion if it is
3918 /// is profitable.
3919 /// \return True if the promotion happened, false otherwise.
3920 bool promote() {
3921 // Check if there is something to promote.
3922 // Right now, if we do not have anything to combine with,
3923 // we assume the promotion is not profitable.
3924 if (InstsToBePromoted.empty() || !CombineInst)
3925 return false;
3926
3927 // Check cost.
3928 if (!StressStoreExtract && !isProfitableToPromote())
3929 return false;
3930
3931 // Promote.
3932 for (auto &ToBePromoted : InstsToBePromoted)
3933 promoteImpl(ToBePromoted);
3934 InstsToBePromoted.clear();
3935 return true;
3936 }
3937};
3938} // End of anonymous namespace.
3939
3940void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3941 // At this point, we know that all the operands of ToBePromoted but Def
3942 // can be statically promoted.
3943 // For Def, we need to use its parameter in ToBePromoted:
3944 // b = ToBePromoted ty1 a
3945 // Def = Transition ty1 b to ty2
3946 // Move the transition down.
3947 // 1. Replace all uses of the promoted operation by the transition.
3948 // = ... b => = ... Def.
3949 assert(ToBePromoted->getType() == Transition->getType() &&
3950 "The type of the result of the transition does not match "
3951 "the final type");
3952 ToBePromoted->replaceAllUsesWith(Transition);
3953 // 2. Update the type of the uses.
3954 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3955 Type *TransitionTy = getTransitionType();
3956 ToBePromoted->mutateType(TransitionTy);
3957 // 3. Update all the operands of the promoted operation with promoted
3958 // operands.
3959 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3960 for (Use &U : ToBePromoted->operands()) {
3961 Value *Val = U.get();
3962 Value *NewVal = nullptr;
3963 if (Val == Transition)
3964 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3965 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3966 isa<ConstantFP>(Val)) {
3967 // Use a splat constant if it is not safe to use undef.
3968 NewVal = getConstantVector(
3969 cast<Constant>(Val),
3970 isa<UndefValue>(Val) ||
3971 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3972 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00003973 llvm_unreachable("Did you modified shouldPromote and forgot to update "
3974 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00003975 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3976 }
3977 Transition->removeFromParent();
3978 Transition->insertAfter(ToBePromoted);
3979 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3980}
3981
Andrea Di Biagio22ee3f62014-12-28 11:07:35 +00003982// See if we can speculate calls to intrinsic cttz/ctlz.
3983//
3984// Example:
3985// entry:
3986// ...
3987// %cmp = icmp eq i64 %val, 0
3988// br i1 %cmp, label %end.bb, label %then.bb
3989//
3990// then.bb:
3991// %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 true)
3992// br label %EndBB
3993//
3994// end.bb:
3995// %cond = phi i64 [ %c, %then.bb ], [ 64, %entry ]
3996//
3997// ==>
3998//
3999// entry:
4000// ...
4001// %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 false)
4002//
4003static bool OptimizeBranchInst(BranchInst *BrInst, const TargetLowering &TLI) {
4004 assert(BrInst->isConditional() && "Expected a conditional branch!");
4005 BasicBlock *ThenBB = BrInst->getSuccessor(1);
4006 BasicBlock *EndBB = BrInst->getSuccessor(0);
4007
4008 // See if ThenBB contains only one instruction (excluding the
4009 // terminator and DbgInfoIntrinsic calls).
4010 IntrinsicInst *II = nullptr;
Andrea Di Biagiof807a6f2015-01-06 17:41:18 +00004011 CastInst *CI = nullptr;
Andrea Di Biagio22ee3f62014-12-28 11:07:35 +00004012 for (BasicBlock::iterator I = ThenBB->begin(),
4013 E = std::prev(ThenBB->end()); I != E; ++I) {
4014 // Skip debug info.
4015 if (isa<DbgInfoIntrinsic>(I))
4016 continue;
4017
Andrea Di Biagiof807a6f2015-01-06 17:41:18 +00004018 // Check if this is a zero extension or a truncate of a previously
4019 // matched call to intrinsic cttz/ctlz.
4020 if (II) {
4021 // Early exit if we already found a "free" zero extend/truncate.
4022 if (CI)
4023 return false;
4024
4025 Type *SrcTy = II->getType();
4026 Type *DestTy = I->getType();
4027 Value *V;
4028
4029 if (match(cast<Instruction>(I), m_ZExt(m_Value(V))) && V == II) {
4030 // Speculate this zero extend only if it is "free" for the target.
4031 if (TLI.isZExtFree(SrcTy, DestTy)) {
4032 CI = cast<CastInst>(I);
4033 continue;
4034 }
4035 } else if (match(cast<Instruction>(I), m_Trunc(m_Value(V))) && V == II) {
4036 // Speculate this truncate only if it is "free" for the target.
4037 if (TLI.isTruncateFree(SrcTy, DestTy)) {
4038 CI = cast<CastInst>(I);
4039 continue;
4040 }
4041 } else {
4042 // Avoid speculating more than one instruction.
4043 return false;
4044 }
4045 }
Andrea Di Biagio22ee3f62014-12-28 11:07:35 +00004046
4047 // See if this is a call to intrinsic cttz/ctlz.
4048 if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::cttz>())) {
4049 // Avoid speculating expensive intrinsic calls.
4050 if (!TLI.isCheapToSpeculateCttz())
4051 return false;
4052 }
4053 else if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::ctlz>())) {
4054 // Avoid speculating expensive intrinsic calls.
4055 if (!TLI.isCheapToSpeculateCtlz())
4056 return false;
4057 } else
4058 return false;
4059
4060 II = cast<IntrinsicInst>(I);
4061 }
4062
4063 // Look for PHI nodes with 'II' as the incoming value from 'ThenBB'.
4064 BasicBlock *EntryBB = BrInst->getParent();
4065 for (BasicBlock::iterator I = EndBB->begin();
4066 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
4067 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
4068 Value *OrigV = PN->getIncomingValueForBlock(EntryBB);
4069
Andrea Di Biagiof807a6f2015-01-06 17:41:18 +00004070 if (!OrigV)
Andrea Di Biagio22ee3f62014-12-28 11:07:35 +00004071 return false;
4072
Andrea Di Biagiof807a6f2015-01-06 17:41:18 +00004073 if (ThenV != II && (!CI || ThenV != CI))
4074 return false;
4075
Andrea Di Biagio22ee3f62014-12-28 11:07:35 +00004076 if (ConstantInt *CInt = dyn_cast<ConstantInt>(OrigV)) {
Andrea Di Biagiof807a6f2015-01-06 17:41:18 +00004077 unsigned BitWidth = II->getType()->getIntegerBitWidth();
Andrea Di Biagio22ee3f62014-12-28 11:07:35 +00004078
4079 // Don't try to simplify this phi node if 'ThenV' is a cttz/ctlz
4080 // intrinsic call, but 'OrigV' is not equal to the 'size-of' in bits
4081 // of the value in input to the cttz/ctlz.
4082 if (CInt->getValue() != BitWidth)
4083 return false;
4084
4085 // Hoist the call to cttz/ctlz from ThenBB into EntryBB.
4086 EntryBB->getInstList().splice(BrInst, ThenBB->getInstList(),
4087 ThenBB->begin(), std::prev(ThenBB->end()));
4088
4089 // Update PN setting ThenV as the incoming value from both 'EntryBB'
4090 // and 'ThenBB'. Eventually, method 'OptimizeInst' will fold this
4091 // phi node if all the incoming values are the same.
4092 PN->setIncomingValue(PN->getBasicBlockIndex(EntryBB), ThenV);
4093 PN->setIncomingValue(PN->getBasicBlockIndex(ThenBB), ThenV);
4094
4095 // Clear the 'undef on zero' flag of the cttz/ctlz intrinsic call.
4096 if (cast<ConstantInt>(II->getArgOperand(1))->isOne()) {
4097 Type *Ty = II->getArgOperand(0)->getType();
4098 Value *Args[] = { II->getArgOperand(0),
4099 ConstantInt::getFalse(II->getContext()) };
4100 Module *M = EntryBB->getParent()->getParent();
4101 Value *IF = Intrinsic::getDeclaration(M, II->getIntrinsicID(), Ty);
Andrea Di Biagiof807a6f2015-01-06 17:41:18 +00004102 IRBuilder<> Builder(II);
Andrea Di Biagio22ee3f62014-12-28 11:07:35 +00004103 Instruction *NewI = Builder.CreateCall(IF, Args);
4104
4105 // Replace the old call to cttz/ctlz.
4106 II->replaceAllUsesWith(NewI);
4107 II->eraseFromParent();
4108 }
4109
4110 // Update BrInst condition so that the branch to EndBB is always taken.
4111 // Later on, method 'ConstantFoldTerminator' will simplify this branch
4112 // replacing it with a direct branch to 'EndBB'.
4113 // As a side effect, CodeGenPrepare will attempt to simplify the control
4114 // flow graph by deleting basic block 'ThenBB' and merging 'EntryBB' into
4115 // 'EndBB' (calling method 'EliminateFallThrough').
4116 BrInst->setCondition(ConstantInt::getTrue(BrInst->getContext()));
4117 return true;
4118 }
4119 }
4120
4121 return false;
4122}
4123
Quentin Colombetc32615d2014-10-31 17:52:53 +00004124/// Some targets can do store(extractelement) with one instruction.
4125/// Try to push the extractelement towards the stores when the target
4126/// has this feature and this is profitable.
4127bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4128 unsigned CombineCost = UINT_MAX;
4129 if (DisableStoreExtract || !TLI ||
4130 (!StressStoreExtract &&
4131 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4132 Inst->getOperand(1), CombineCost)))
4133 return false;
4134
4135 // At this point we know that Inst is a vector to scalar transition.
4136 // Try to move it down the def-use chain, until:
4137 // - We can combine the transition with its single use
4138 // => we got rid of the transition.
4139 // - We escape the current basic block
4140 // => we would need to check that we are moving it at a cheaper place and
4141 // we do not do that for now.
4142 BasicBlock *Parent = Inst->getParent();
4143 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4144 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
4145 // If the transition has more than one use, assume this is not going to be
4146 // beneficial.
4147 while (Inst->hasOneUse()) {
4148 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4149 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4150
4151 if (ToBePromoted->getParent() != Parent) {
4152 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4153 << ToBePromoted->getParent()->getName()
4154 << ") than the transition (" << Parent->getName() << ").\n");
4155 return false;
4156 }
4157
4158 if (VPH.canCombine(ToBePromoted)) {
4159 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4160 << "will be combined with: " << *ToBePromoted << '\n');
4161 VPH.recordCombineInstruction(ToBePromoted);
4162 bool Changed = VPH.promote();
4163 NumStoreExtractExposed += Changed;
4164 return Changed;
4165 }
4166
4167 DEBUG(dbgs() << "Try promoting.\n");
4168 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4169 return false;
4170
4171 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4172
4173 VPH.enqueueForPromotion(ToBePromoted);
4174 Inst = ToBePromoted;
4175 }
4176 return false;
4177}
4178
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004179bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004180 if (PHINode *P = dyn_cast<PHINode>(I)) {
4181 // It is possible for very late stage optimizations (such as SimplifyCFG)
4182 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4183 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00004184 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00004185 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004186 P->replaceAllUsesWith(V);
4187 P->eraseFromParent();
4188 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004189 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004190 }
Chris Lattneree588de2011-01-15 07:29:01 +00004191 return false;
4192 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004193
Chris Lattneree588de2011-01-15 07:29:01 +00004194 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004195 // If the source of the cast is a constant, then this should have
4196 // already been constant folded. The only reason NOT to constant fold
4197 // it is if something (e.g. LSR) was careful to place the constant
4198 // evaluation in a block other than then one that uses it (e.g. to hoist
4199 // the address of globals out of a loop). If this is the case, we don't
4200 // want to forward-subst the cast.
4201 if (isa<Constant>(CI->getOperand(0)))
4202 return false;
4203
Chris Lattneree588de2011-01-15 07:29:01 +00004204 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
4205 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004206
Chris Lattneree588de2011-01-15 07:29:01 +00004207 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004208 /// Sink a zext or sext into its user blocks if the target type doesn't
4209 /// fit in one register
4210 if (TLI && TLI->getTypeAction(CI->getContext(),
4211 TLI->getValueType(CI->getType())) ==
4212 TargetLowering::TypeExpandInteger) {
4213 return SinkCast(CI);
4214 } else {
4215 bool MadeChange = MoveExtToFormExtLoad(I);
4216 return MadeChange | OptimizeExtUses(I);
4217 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004218 }
Chris Lattneree588de2011-01-15 07:29:01 +00004219 return false;
4220 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004221
Chris Lattneree588de2011-01-15 07:29:01 +00004222 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004223 if (!TLI || !TLI->hasMultipleConditionRegisters())
4224 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004225
Chris Lattneree588de2011-01-15 07:29:01 +00004226 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004227 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00004228 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
4229 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004230 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004231
Chris Lattneree588de2011-01-15 07:29:01 +00004232 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004233 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00004234 return OptimizeMemoryInst(I, SI->getOperand(1),
4235 SI->getOperand(0)->getType());
4236 return false;
4237 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004238
Yi Jiangd069f632014-04-21 19:34:27 +00004239 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4240
4241 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4242 BinOp->getOpcode() == Instruction::LShr)) {
4243 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4244 if (TLI && CI && TLI->hasExtractBitsInsn())
4245 return OptimizeExtractBits(BinOp, CI, *TLI);
4246
4247 return false;
4248 }
4249
Chris Lattneree588de2011-01-15 07:29:01 +00004250 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004251 if (GEPI->hasAllZeroIndices()) {
4252 /// The GEP operand must be a pointer, so must its result -> BitCast
4253 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4254 GEPI->getName(), GEPI);
4255 GEPI->replaceAllUsesWith(NC);
4256 GEPI->eraseFromParent();
4257 ++NumGEPsElim;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004258 OptimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004259 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004260 }
Chris Lattneree588de2011-01-15 07:29:01 +00004261 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004262 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004263
Chris Lattneree588de2011-01-15 07:29:01 +00004264 if (CallInst *CI = dyn_cast<CallInst>(I))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004265 return OptimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004266
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004267 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4268 return OptimizeSelectInst(SI);
4269
Tim Northoveraeb8e062014-02-19 10:02:43 +00004270 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4271 return OptimizeShuffleVectorInst(SVI);
4272
Quentin Colombetc32615d2014-10-31 17:52:53 +00004273 if (isa<ExtractElementInst>(I))
4274 return OptimizeExtractElementInst(I);
4275
Andrea Di Biagio22ee3f62014-12-28 11:07:35 +00004276 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
4277 if (TLI && BI->isConditional() && BI->getCondition()->hasOneUse()) {
4278 // Check if the branch condition compares a value agaist zero.
4279 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
4280 if (ICI->getPredicate() == ICmpInst::ICMP_EQ &&
4281 match(ICI->getOperand(1), m_Zero())) {
4282 BasicBlock *ThenBB = BI->getSuccessor(1);
4283 BasicBlock *EndBB = BI->getSuccessor(0);
4284
4285 // Check if ThenBB is only reachable from this basic block; also,
4286 // check if EndBB has more than one predecessor.
4287 if (ThenBB->getSinglePredecessor() &&
4288 !EndBB->getSinglePredecessor()) {
4289 TerminatorInst *TI = ThenBB->getTerminator();
4290
4291 if (TI->getNumSuccessors() == 1 && TI->getSuccessor(0) == EndBB &&
4292 // Try to speculate calls to intrinsic cttz/ctlz from 'ThenBB'.
4293 OptimizeBranchInst(BI, *TLI)) {
4294 ModifiedDT = true;
4295 return true;
4296 }
4297 }
4298 }
4299 }
4300 }
4301 return false;
4302 }
4303
Chris Lattneree588de2011-01-15 07:29:01 +00004304 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004305}
4306
Chris Lattnerf2836d12007-03-31 04:06:36 +00004307// In this pass we look for GEP and cast instructions that are used
4308// across basic blocks and rewrite them to improve basic-block-at-a-time
4309// selection.
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004310bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004311 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004312 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004313
Chris Lattner7a277142011-01-15 07:14:54 +00004314 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004315 while (CurInstIterator != BB.end()) {
4316 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4317 if (ModifiedDT)
4318 return true;
4319 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00004320 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4321
Chris Lattnerf2836d12007-03-31 04:06:36 +00004322 return MadeChange;
4323}
Devang Patel53771ba2011-08-18 00:50:51 +00004324
4325// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004326// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004327// find a node corresponding to the value.
4328bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4329 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004330 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004331 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004332 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Devang Patel53771ba2011-08-18 00:50:51 +00004333 Instruction *Insn = BI; ++BI;
4334 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004335 // Leave dbg.values that refer to an alloca alone. These
4336 // instrinsics describe the address of a variable (= the alloca)
4337 // being taken. They should not be moved next to the alloca
4338 // (and to the beginning of the scope), but rather stay close to
4339 // where said address is used.
4340 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004341 PrevNonDbgInst = Insn;
4342 continue;
4343 }
4344
4345 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4346 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4347 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4348 DVI->removeFromParent();
4349 if (isa<PHINode>(VI))
4350 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4351 else
4352 DVI->insertAfter(VI);
4353 MadeChange = true;
4354 ++NumDbgValueMoved;
4355 }
4356 }
4357 }
4358 return MadeChange;
4359}
Tim Northovercea0abb2014-03-29 08:22:29 +00004360
4361// If there is a sequence that branches based on comparing a single bit
4362// against zero that can be combined into a single instruction, and the
4363// target supports folding these into a single instruction, sink the
4364// mask and compare into the branch uses. Do this before OptimizeBlock ->
4365// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4366// searched for.
4367bool CodeGenPrepare::sinkAndCmp(Function &F) {
4368 if (!EnableAndCmpSinking)
4369 return false;
4370 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4371 return false;
4372 bool MadeChange = false;
4373 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4374 BasicBlock *BB = I++;
4375
4376 // Does this BB end with the following?
4377 // %andVal = and %val, #single-bit-set
4378 // %icmpVal = icmp %andResult, 0
4379 // br i1 %cmpVal label %dest1, label %dest2"
4380 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4381 if (!Brcc || !Brcc->isConditional())
4382 continue;
4383 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4384 if (!Cmp || Cmp->getParent() != BB)
4385 continue;
4386 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4387 if (!Zero || !Zero->isZero())
4388 continue;
4389 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4390 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4391 continue;
4392 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4393 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4394 continue;
4395 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4396
4397 // Push the "and; icmp" for any users that are conditional branches.
4398 // Since there can only be one branch use per BB, we don't need to keep
4399 // track of which BBs we insert into.
4400 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4401 UI != E; ) {
4402 Use &TheUse = *UI;
4403 // Find brcc use.
4404 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4405 ++UI;
4406 if (!BrccUser || !BrccUser->isConditional())
4407 continue;
4408 BasicBlock *UserBB = BrccUser->getParent();
4409 if (UserBB == BB) continue;
4410 DEBUG(dbgs() << "found Brcc use\n");
4411
4412 // Sink the "and; icmp" to use.
4413 MadeChange = true;
4414 BinaryOperator *NewAnd =
4415 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4416 BrccUser);
4417 CmpInst *NewCmp =
4418 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4419 "", BrccUser);
4420 TheUse = NewCmp;
4421 ++NumAndCmpsMoved;
4422 DEBUG(BrccUser->getParent()->dump());
4423 }
4424 }
4425 return MadeChange;
4426}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004427
Juergen Ributzka194350a2014-12-09 17:32:12 +00004428/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4429/// success, or returns false if no or invalid metadata was found.
4430static bool extractBranchMetadata(BranchInst *BI,
4431 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4432 assert(BI->isConditional() &&
4433 "Looking for probabilities on unconditional branch?");
4434 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4435 if (!ProfileData || ProfileData->getNumOperands() != 3)
4436 return false;
4437
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004438 const auto *CITrue =
4439 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4440 const auto *CIFalse =
4441 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004442 if (!CITrue || !CIFalse)
4443 return false;
4444
4445 ProbTrue = CITrue->getValue().getZExtValue();
4446 ProbFalse = CIFalse->getValue().getZExtValue();
4447
4448 return true;
4449}
4450
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004451/// \brief Scale down both weights to fit into uint32_t.
4452static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4453 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4454 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4455 NewTrue = NewTrue / Scale;
4456 NewFalse = NewFalse / Scale;
4457}
4458
4459/// \brief Some targets prefer to split a conditional branch like:
4460/// \code
4461/// %0 = icmp ne i32 %a, 0
4462/// %1 = icmp ne i32 %b, 0
4463/// %or.cond = or i1 %0, %1
4464/// br i1 %or.cond, label %TrueBB, label %FalseBB
4465/// \endcode
4466/// into multiple branch instructions like:
4467/// \code
4468/// bb1:
4469/// %0 = icmp ne i32 %a, 0
4470/// br i1 %0, label %TrueBB, label %bb2
4471/// bb2:
4472/// %1 = icmp ne i32 %b, 0
4473/// br i1 %1, label %TrueBB, label %FalseBB
4474/// \endcode
4475/// This usually allows instruction selection to do even further optimizations
4476/// and combine the compare with the branch instruction. Currently this is
4477/// applied for targets which have "cheap" jump instructions.
4478///
4479/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4480///
4481bool CodeGenPrepare::splitBranchCondition(Function &F) {
4482 if (!TM || TM->Options.EnableFastISel != true ||
4483 !TLI || TLI->isJumpExpensive())
4484 return false;
4485
4486 bool MadeChange = false;
4487 for (auto &BB : F) {
4488 // Does this BB end with the following?
4489 // %cond1 = icmp|fcmp|binary instruction ...
4490 // %cond2 = icmp|fcmp|binary instruction ...
4491 // %cond.or = or|and i1 %cond1, cond2
4492 // br i1 %cond.or label %dest1, label %dest2"
4493 BinaryOperator *LogicOp;
4494 BasicBlock *TBB, *FBB;
4495 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4496 continue;
4497
4498 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004499 Value *Cond1, *Cond2;
4500 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4501 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004502 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004503 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4504 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004505 Opc = Instruction::Or;
4506 else
4507 continue;
4508
4509 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4510 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4511 continue;
4512
4513 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4514
4515 // Create a new BB.
4516 auto *InsertBefore = std::next(Function::iterator(BB))
4517 .getNodePtrUnchecked();
4518 auto TmpBB = BasicBlock::Create(BB.getContext(),
4519 BB.getName() + ".cond.split",
4520 BB.getParent(), InsertBefore);
4521
4522 // Update original basic block by using the first condition directly by the
4523 // branch instruction and removing the no longer needed and/or instruction.
4524 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4525 Br1->setCondition(Cond1);
4526 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004527
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004528 // Depending on the conditon we have to either replace the true or the false
4529 // successor of the original branch instruction.
4530 if (Opc == Instruction::And)
4531 Br1->setSuccessor(0, TmpBB);
4532 else
4533 Br1->setSuccessor(1, TmpBB);
4534
4535 // Fill in the new basic block.
4536 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004537 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4538 I->removeFromParent();
4539 I->insertBefore(Br2);
4540 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004541
4542 // Update PHI nodes in both successors. The original BB needs to be
4543 // replaced in one succesor's PHI nodes, because the branch comes now from
4544 // the newly generated BB (NewBB). In the other successor we need to add one
4545 // incoming edge to the PHI nodes, because both branch instructions target
4546 // now the same successor. Depending on the original branch condition
4547 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4548 // we perfrom the correct update for the PHI nodes.
4549 // This doesn't change the successor order of the just created branch
4550 // instruction (or any other instruction).
4551 if (Opc == Instruction::Or)
4552 std::swap(TBB, FBB);
4553
4554 // Replace the old BB with the new BB.
4555 for (auto &I : *TBB) {
4556 PHINode *PN = dyn_cast<PHINode>(&I);
4557 if (!PN)
4558 break;
4559 int i;
4560 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4561 PN->setIncomingBlock(i, TmpBB);
4562 }
4563
4564 // Add another incoming edge form the new BB.
4565 for (auto &I : *FBB) {
4566 PHINode *PN = dyn_cast<PHINode>(&I);
4567 if (!PN)
4568 break;
4569 auto *Val = PN->getIncomingValueForBlock(&BB);
4570 PN->addIncoming(Val, TmpBB);
4571 }
4572
4573 // Update the branch weights (from SelectionDAGBuilder::
4574 // FindMergedConditions).
4575 if (Opc == Instruction::Or) {
4576 // Codegen X | Y as:
4577 // BB1:
4578 // jmp_if_X TBB
4579 // jmp TmpBB
4580 // TmpBB:
4581 // jmp_if_Y TBB
4582 // jmp FBB
4583 //
4584
4585 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4586 // The requirement is that
4587 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4588 // = TrueProb for orignal BB.
4589 // Assuming the orignal weights are A and B, one choice is to set BB1's
4590 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4591 // assumes that
4592 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4593 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4594 // TmpBB, but the math is more complicated.
4595 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004596 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004597 uint64_t NewTrueWeight = TrueWeight;
4598 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4599 scaleWeights(NewTrueWeight, NewFalseWeight);
4600 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4601 .createBranchWeights(TrueWeight, FalseWeight));
4602
4603 NewTrueWeight = TrueWeight;
4604 NewFalseWeight = 2 * FalseWeight;
4605 scaleWeights(NewTrueWeight, NewFalseWeight);
4606 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4607 .createBranchWeights(TrueWeight, FalseWeight));
4608 }
4609 } else {
4610 // Codegen X & Y as:
4611 // BB1:
4612 // jmp_if_X TmpBB
4613 // jmp FBB
4614 // TmpBB:
4615 // jmp_if_Y TBB
4616 // jmp FBB
4617 //
4618 // This requires creation of TmpBB after CurBB.
4619
4620 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4621 // The requirement is that
4622 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4623 // = FalseProb for orignal BB.
4624 // Assuming the orignal weights are A and B, one choice is to set BB1's
4625 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4626 // assumes that
4627 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4628 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004629 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004630 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4631 uint64_t NewFalseWeight = FalseWeight;
4632 scaleWeights(NewTrueWeight, NewFalseWeight);
4633 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4634 .createBranchWeights(TrueWeight, FalseWeight));
4635
4636 NewTrueWeight = 2 * TrueWeight;
4637 NewFalseWeight = FalseWeight;
4638 scaleWeights(NewTrueWeight, NewFalseWeight);
4639 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4640 .createBranchWeights(TrueWeight, FalseWeight));
4641 }
4642 }
4643
4644 // Request DOM Tree update.
4645 // Note: No point in getting fancy here, since the DT info is never
4646 // available to CodeGenPrepare and the existing update code is broken
4647 // anyways.
4648 ModifiedDT = true;
4649
4650 MadeChange = true;
4651
4652 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4653 TmpBB->dump());
4654 }
4655 return MadeChange;
4656}