blob: 8b92cf2e9f4f327cf7cec7dda937a7afec282a16 [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
Eric Christopherc1ea1492008-09-24 05:32:41 +000094namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000095typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Quentin Colombetf5485bb2014-11-13 01:44:51 +000096struct TypeIsSExt {
97 Type *Ty;
98 bool IsSExt;
99 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
100};
101typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000102
Chris Lattner2dd09db2009-09-02 06:11:42 +0000103 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000104 /// TLI - Keep a pointer of a TargetLowering to consult for determining
105 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000106 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000107 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000108 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000109 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +0000110 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +0000111
Chris Lattner7a277142011-01-15 07:14:54 +0000112 /// CurInstIterator - As we scan instructions optimizing them, this is the
113 /// next instruction to optimize. Xforms that can invalidate this should
114 /// update it.
115 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000116
Evan Cheng0663f232011-03-21 01:19:09 +0000117 /// Keeps track of non-local addresses that have been sunk into a block.
118 /// This allows us to avoid inserting duplicate code for blocks with
119 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000120 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000121
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000122 /// Keeps track of all truncates inserted for the current function.
123 SetOfInstrs InsertedTruncsSet;
124 /// Keeps track of the type of the related instruction before their
125 /// promotion for the current function.
126 InstrToOrigTy PromotedInsts;
127
Devang Patel8f606d72011-03-24 15:35:25 +0000128 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000129 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000130 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000131
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000132 /// OptSize - True if optimizing for size.
133 bool OptSize;
134
Chris Lattnerf2836d12007-03-31 04:06:36 +0000135 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000136 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000137 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Quentin Colombetc32615d2014-10-31 17:52:53 +0000138 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000139 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
140 }
Craig Topper4584cd52014-03-07 09:26:03 +0000141 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000142
Craig Topper4584cd52014-03-07 09:26:03 +0000143 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000144
Craig Topper4584cd52014-03-07 09:26:03 +0000145 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000146 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000147 AU.addRequired<TargetLibraryInfo>();
Quentin Colombetc32615d2014-10-31 17:52:53 +0000148 AU.addRequired<TargetTransformInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000149 }
150
Chris Lattnerf2836d12007-03-31 04:06:36 +0000151 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000152 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000153 bool EliminateMostlyEmptyBlocks(Function &F);
154 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
155 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000156 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000157 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000158 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000159 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000160 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000161 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000162 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000163 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000164 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000165 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000166 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000167 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000168 bool sinkAndCmp(Function &F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000169 bool splitBranchCondition(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000170 };
171}
Devang Patel09f162c2007-05-01 21:15:47 +0000172
Devang Patel8c78a0b2007-05-03 01:11:54 +0000173char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000174INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
175 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000176
Bill Wendling7a639ea2013-06-19 21:07:11 +0000177FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
178 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000179}
180
Chris Lattnerf2836d12007-03-31 04:06:36 +0000181bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000182 if (skipOptnoneFunction(F))
183 return false;
184
Chris Lattnerf2836d12007-03-31 04:06:36 +0000185 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000186 // Clear per function information.
187 InsertedTruncsSet.clear();
188 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000189
Devang Patel8f606d72011-03-24 15:35:25 +0000190 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000191 if (TM)
192 TLI = TM->getSubtargetImpl()->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000193 TLInfo = &getAnalysis<TargetLibraryInfo>();
Quentin Colombetc32615d2014-10-31 17:52:53 +0000194 TTI = &getAnalysis<TargetTransformInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000195 DominatorTreeWrapperPass *DTWP =
196 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000197 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Bill Wendling698e84f2012-12-30 10:32:01 +0000198 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
199 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000200
Preston Gurdcdf540d2012-09-04 18:22:17 +0000201 /// This optimization identifies DIV instructions that can be
202 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000203 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000204 const DenseMap<unsigned int, unsigned int> &BypassWidths =
205 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000206 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000207 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000208 }
209
210 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000211 // unconditional branch.
212 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000213
Devang Patel53771ba2011-08-18 00:50:51 +0000214 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000215 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000216 // find a node corresponding to the value.
217 EverMadeChange |= PlaceDbgValues(F);
218
Tim Northovercea0abb2014-03-29 08:22:29 +0000219 // If there is a mask, compare against zero, and branch that can be combined
220 // into a single target instruction, push the mask and compare into branch
221 // users. Do this before OptimizeBlock -> OptimizeInst ->
222 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000223 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000224 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000225 EverMadeChange |= splitBranchCondition(F);
226 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000227
Chris Lattnerc3748562007-04-02 01:35:34 +0000228 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000229 while (MadeChange) {
230 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000231 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000232 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000233 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000234 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000235 EverMadeChange |= MadeChange;
236 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000237
238 SunkAddrs.clear();
239
Cameron Zwarich338d3622011-03-11 21:52:04 +0000240 if (!DisableBranchOpts) {
241 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000242 SmallPtrSet<BasicBlock*, 8> WorkList;
243 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
244 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000245 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000246 if (!MadeChange) continue;
247
248 for (SmallVectorImpl<BasicBlock*>::iterator
249 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
250 if (pred_begin(*II) == pred_end(*II))
251 WorkList.insert(*II);
252 }
253
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000254 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000255 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000256 while (!WorkList.empty()) {
257 BasicBlock *BB = *WorkList.begin();
258 WorkList.erase(BB);
259 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
260
261 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000262
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000263 for (SmallVectorImpl<BasicBlock*>::iterator
264 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
265 if (pred_begin(*II) == pred_end(*II))
266 WorkList.insert(*II);
267 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000268
Nadav Rotem70409992012-08-14 05:19:07 +0000269 // Merge pairs of basic blocks with unconditional branches, connected by
270 // a single edge.
271 if (EverMadeChange || MadeChange)
272 MadeChange |= EliminateFallThrough(F);
273
Evan Cheng0663f232011-03-21 01:19:09 +0000274 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000275 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000276 EverMadeChange |= MadeChange;
277 }
278
Devang Patel8f606d72011-03-24 15:35:25 +0000279 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000280 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000281
Chris Lattnerf2836d12007-03-31 04:06:36 +0000282 return EverMadeChange;
283}
284
Nadav Rotem70409992012-08-14 05:19:07 +0000285/// EliminateFallThrough - Merge basic blocks which are connected
286/// by a single edge, where one of the basic blocks has a single successor
287/// pointing to the other basic block, which has a single predecessor.
288bool CodeGenPrepare::EliminateFallThrough(Function &F) {
289 bool Changed = false;
290 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000291 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000292 BasicBlock *BB = I++;
293 // If the destination block has a single pred, then this is a trivial
294 // edge, just collapse it.
295 BasicBlock *SinglePred = BB->getSinglePredecessor();
296
Evan Cheng64a223a2012-09-28 23:58:57 +0000297 // Don't merge if BB's address is taken.
298 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000299
300 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
301 if (Term && !Term->isConditional()) {
302 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000303 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000304 // Remember if SinglePred was the entry block of the function.
305 // If so, we will need to move BB back to the entry position.
306 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
307 MergeBasicBlockIntoOnlyPred(BB, this);
308
309 if (isEntry && BB != &BB->getParent()->getEntryBlock())
310 BB->moveBefore(&BB->getParent()->getEntryBlock());
311
312 // We have erased a block. Update the iterator.
313 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000314 }
315 }
316 return Changed;
317}
318
Dale Johannesen4026b042009-03-27 01:13:37 +0000319/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
320/// debug info directives, and an unconditional branch. Passes before isel
321/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
322/// isel. Start by eliminating these blocks so we can split them the way we
323/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000324bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
325 bool MadeChange = false;
326 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000327 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000328 BasicBlock *BB = I++;
329
330 // If this block doesn't end with an uncond branch, ignore it.
331 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
332 if (!BI || !BI->isUnconditional())
333 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000334
Dale Johannesen4026b042009-03-27 01:13:37 +0000335 // If the instruction before the branch (skipping debug info) isn't a phi
336 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000337 BasicBlock::iterator BBI = BI;
338 if (BBI != BB->begin()) {
339 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000340 while (isa<DbgInfoIntrinsic>(BBI)) {
341 if (BBI == BB->begin())
342 break;
343 --BBI;
344 }
345 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
346 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000347 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000348
Chris Lattnerc3748562007-04-02 01:35:34 +0000349 // Do not break infinite loops.
350 BasicBlock *DestBB = BI->getSuccessor(0);
351 if (DestBB == BB)
352 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000353
Chris Lattnerc3748562007-04-02 01:35:34 +0000354 if (!CanMergeBlocks(BB, DestBB))
355 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000356
Chris Lattnerc3748562007-04-02 01:35:34 +0000357 EliminateMostlyEmptyBlock(BB);
358 MadeChange = true;
359 }
360 return MadeChange;
361}
362
363/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
364/// single uncond branch between them, and BB contains no other non-phi
365/// instructions.
366bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
367 const BasicBlock *DestBB) const {
368 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
369 // the successor. If there are more complex condition (e.g. preheaders),
370 // don't mess around with them.
371 BasicBlock::const_iterator BBI = BB->begin();
372 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000373 for (const User *U : PN->users()) {
374 const Instruction *UI = cast<Instruction>(U);
375 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000376 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000377 // If User is inside DestBB block and it is a PHINode then check
378 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000379 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000380 if (UI->getParent() == DestBB) {
381 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000382 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
383 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
384 if (Insn && Insn->getParent() == BB &&
385 Insn->getParent() != UPN->getIncomingBlock(I))
386 return false;
387 }
388 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000389 }
390 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000391
Chris Lattnerc3748562007-04-02 01:35:34 +0000392 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
393 // and DestBB may have conflicting incoming values for the block. If so, we
394 // can't merge the block.
395 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
396 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000397
Chris Lattnerc3748562007-04-02 01:35:34 +0000398 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000399 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000400 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
401 // It is faster to get preds from a PHI than with pred_iterator.
402 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
403 BBPreds.insert(BBPN->getIncomingBlock(i));
404 } else {
405 BBPreds.insert(pred_begin(BB), pred_end(BB));
406 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000407
Chris Lattnerc3748562007-04-02 01:35:34 +0000408 // Walk the preds of DestBB.
409 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
410 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
411 if (BBPreds.count(Pred)) { // Common predecessor?
412 BBI = DestBB->begin();
413 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
414 const Value *V1 = PN->getIncomingValueForBlock(Pred);
415 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000416
Chris Lattnerc3748562007-04-02 01:35:34 +0000417 // If V2 is a phi node in BB, look up what the mapped value will be.
418 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
419 if (V2PN->getParent() == BB)
420 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000421
Chris Lattnerc3748562007-04-02 01:35:34 +0000422 // If there is a conflict, bail out.
423 if (V1 != V2) return false;
424 }
425 }
426 }
427
428 return true;
429}
430
431
432/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
433/// an unconditional branch in it.
434void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
435 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
436 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000437
David Greene74e2d492010-01-05 01:27:11 +0000438 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000439
Chris Lattnerc3748562007-04-02 01:35:34 +0000440 // If the destination block has a single pred, then this is a trivial edge,
441 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000442 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000443 if (SinglePred != DestBB) {
444 // Remember if SinglePred was the entry block of the function. If so, we
445 // will need to move BB back to the entry position.
446 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000447 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000448
Chris Lattner8a172da2008-11-28 19:54:49 +0000449 if (isEntry && BB != &BB->getParent()->getEntryBlock())
450 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000451
David Greene74e2d492010-01-05 01:27:11 +0000452 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000453 return;
454 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000455 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000456
Chris Lattnerc3748562007-04-02 01:35:34 +0000457 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
458 // to handle the new incoming edges it is about to have.
459 PHINode *PN;
460 for (BasicBlock::iterator BBI = DestBB->begin();
461 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
462 // Remove the incoming value for BB, and remember it.
463 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000464
Chris Lattnerc3748562007-04-02 01:35:34 +0000465 // Two options: either the InVal is a phi node defined in BB or it is some
466 // value that dominates BB.
467 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
468 if (InValPhi && InValPhi->getParent() == BB) {
469 // Add all of the input values of the input PHI as inputs of this phi.
470 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
471 PN->addIncoming(InValPhi->getIncomingValue(i),
472 InValPhi->getIncomingBlock(i));
473 } else {
474 // Otherwise, add one instance of the dominating value for each edge that
475 // we will be adding.
476 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
477 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
478 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
479 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000480 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
481 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000482 }
483 }
484 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000485
Chris Lattnerc3748562007-04-02 01:35:34 +0000486 // The PHIs are now updated, change everything that refers to BB to use
487 // DestBB and remove BB.
488 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000489 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000490 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
491 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
492 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
493 DT->changeImmediateDominator(DestBB, NewIDom);
494 DT->eraseNode(BB);
495 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000496 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000497 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000498
David Greene74e2d492010-01-05 01:27:11 +0000499 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000500}
501
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000502/// SinkCast - Sink the specified cast instruction into its user blocks
503static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000504 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000505
Chris Lattnerf2836d12007-03-31 04:06:36 +0000506 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000507 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000508
Chris Lattnerf2836d12007-03-31 04:06:36 +0000509 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000510 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000511 UI != E; ) {
512 Use &TheUse = UI.getUse();
513 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000514
Chris Lattnerf2836d12007-03-31 04:06:36 +0000515 // Figure out which BB this cast is used in. For PHI's this is the
516 // appropriate predecessor block.
517 BasicBlock *UserBB = User->getParent();
518 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000519 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000520 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000521
Chris Lattnerf2836d12007-03-31 04:06:36 +0000522 // Preincrement use iterator so we don't invalidate it.
523 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000524
Chris Lattnerf2836d12007-03-31 04:06:36 +0000525 // If this user is in the same block as the cast, don't change the cast.
526 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000527
Chris Lattnerf2836d12007-03-31 04:06:36 +0000528 // If we have already inserted a cast into this block, use it.
529 CastInst *&InsertedCast = InsertedCasts[UserBB];
530
531 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000532 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000533 InsertedCast =
534 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000535 InsertPt);
536 MadeChange = true;
537 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000538
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000539 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000540 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000541 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000542 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000543
Chris Lattnerf2836d12007-03-31 04:06:36 +0000544 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000545 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000546 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000547 MadeChange = true;
548 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000549
Chris Lattnerf2836d12007-03-31 04:06:36 +0000550 return MadeChange;
551}
552
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000553/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
554/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
555/// sink it into user blocks to reduce the number of virtual
556/// registers that must be created and coalesced.
557///
558/// Return true if any changes are made.
559///
560static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
561 // If this is a noop copy,
562 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
563 EVT DstVT = TLI.getValueType(CI->getType());
564
565 // This is an fp<->int conversion?
566 if (SrcVT.isInteger() != DstVT.isInteger())
567 return false;
568
569 // If this is an extension, it will be a zero or sign extension, which
570 // isn't a noop.
571 if (SrcVT.bitsLT(DstVT)) return false;
572
573 // If these values will be promoted, find out what they will be promoted
574 // to. This helps us consider truncates on PPC as noop copies when they
575 // are.
576 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
577 TargetLowering::TypePromoteInteger)
578 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
579 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
580 TargetLowering::TypePromoteInteger)
581 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
582
583 // If, after promotion, these are the same types, this is a noop copy.
584 if (SrcVT != DstVT)
585 return false;
586
587 return SinkCast(CI);
588}
589
Eric Christopherc1ea1492008-09-24 05:32:41 +0000590/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000591/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000592/// a clear win except on targets with multiple condition code registers
593/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000594///
595/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000596static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000597 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000598
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000599 /// InsertedCmp - Only insert a cmp in each block once.
600 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000601
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000602 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000603 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000604 UI != E; ) {
605 Use &TheUse = UI.getUse();
606 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000607
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000608 // Preincrement use iterator so we don't invalidate it.
609 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000610
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000611 // Don't bother for PHI nodes.
612 if (isa<PHINode>(User))
613 continue;
614
615 // Figure out which BB this cmp is used in.
616 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000617
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000618 // If this user is in the same block as the cmp, don't change the cmp.
619 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000620
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000621 // If we have already inserted a cmp into this block, use it.
622 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
623
624 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000625 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000626 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000627 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000628 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000629 CI->getOperand(1), "", InsertPt);
630 MadeChange = true;
631 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000632
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000633 // Replace a use of the cmp with a use of the new cmp.
634 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000635 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000636 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000637
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000638 // If we removed all uses, nuke the cmp.
639 if (CI->use_empty())
640 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000641
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000642 return MadeChange;
643}
644
Yi Jiangd069f632014-04-21 19:34:27 +0000645/// isExtractBitsCandidateUse - Check if the candidates could
646/// be combined with shift instruction, which includes:
647/// 1. Truncate instruction
648/// 2. And instruction and the imm is a mask of the low bits:
649/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000650static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000651 if (!isa<TruncInst>(User)) {
652 if (User->getOpcode() != Instruction::And ||
653 !isa<ConstantInt>(User->getOperand(1)))
654 return false;
655
Quentin Colombetd4f44692014-04-22 01:20:34 +0000656 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000657
Quentin Colombetd4f44692014-04-22 01:20:34 +0000658 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000659 return false;
660 }
661 return true;
662}
663
664/// SinkShiftAndTruncate - sink both shift and truncate instruction
665/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000666static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000667SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
668 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
669 const TargetLowering &TLI) {
670 BasicBlock *UserBB = User->getParent();
671 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
672 TruncInst *TruncI = dyn_cast<TruncInst>(User);
673 bool MadeChange = false;
674
675 for (Value::user_iterator TruncUI = TruncI->user_begin(),
676 TruncE = TruncI->user_end();
677 TruncUI != TruncE;) {
678
679 Use &TruncTheUse = TruncUI.getUse();
680 Instruction *TruncUser = cast<Instruction>(*TruncUI);
681 // Preincrement use iterator so we don't invalidate it.
682
683 ++TruncUI;
684
685 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
686 if (!ISDOpcode)
687 continue;
688
Tim Northovere2239ff2014-07-29 10:20:22 +0000689 // If the use is actually a legal node, there will not be an
690 // implicit truncate.
691 // FIXME: always querying the result type is just an
692 // approximation; some nodes' legality is determined by the
693 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000694 if (TLI.isOperationLegalOrCustom(
695 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000696 continue;
697
698 // Don't bother for PHI nodes.
699 if (isa<PHINode>(TruncUser))
700 continue;
701
702 BasicBlock *TruncUserBB = TruncUser->getParent();
703
704 if (UserBB == TruncUserBB)
705 continue;
706
707 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
708 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
709
710 if (!InsertedShift && !InsertedTrunc) {
711 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
712 // Sink the shift
713 if (ShiftI->getOpcode() == Instruction::AShr)
714 InsertedShift =
715 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
716 else
717 InsertedShift =
718 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
719
720 // Sink the trunc
721 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
722 TruncInsertPt++;
723
724 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
725 TruncI->getType(), "", TruncInsertPt);
726
727 MadeChange = true;
728
729 TruncTheUse = InsertedTrunc;
730 }
731 }
732 return MadeChange;
733}
734
735/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
736/// the uses could potentially be combined with this shift instruction and
737/// generate BitExtract instruction. It will only be applied if the architecture
738/// supports BitExtract instruction. Here is an example:
739/// BB1:
740/// %x.extract.shift = lshr i64 %arg1, 32
741/// BB2:
742/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
743/// ==>
744///
745/// BB2:
746/// %x.extract.shift.1 = lshr i64 %arg1, 32
747/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
748///
749/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
750/// instruction.
751/// Return true if any changes are made.
752static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
753 const TargetLowering &TLI) {
754 BasicBlock *DefBB = ShiftI->getParent();
755
756 /// Only insert instructions in each block once.
757 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
758
759 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
760
761 bool MadeChange = false;
762 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
763 UI != E;) {
764 Use &TheUse = UI.getUse();
765 Instruction *User = cast<Instruction>(*UI);
766 // Preincrement use iterator so we don't invalidate it.
767 ++UI;
768
769 // Don't bother for PHI nodes.
770 if (isa<PHINode>(User))
771 continue;
772
773 if (!isExtractBitsCandidateUse(User))
774 continue;
775
776 BasicBlock *UserBB = User->getParent();
777
778 if (UserBB == DefBB) {
779 // If the shift and truncate instruction are in the same BB. The use of
780 // the truncate(TruncUse) may still introduce another truncate if not
781 // legal. In this case, we would like to sink both shift and truncate
782 // instruction to the BB of TruncUse.
783 // for example:
784 // BB1:
785 // i64 shift.result = lshr i64 opnd, imm
786 // trunc.result = trunc shift.result to i16
787 //
788 // BB2:
789 // ----> We will have an implicit truncate here if the architecture does
790 // not have i16 compare.
791 // cmp i16 trunc.result, opnd2
792 //
793 if (isa<TruncInst>(User) && shiftIsLegal
794 // If the type of the truncate is legal, no trucate will be
795 // introduced in other basic blocks.
796 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
797 MadeChange =
798 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
799
800 continue;
801 }
802 // If we have already inserted a shift into this block, use it.
803 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
804
805 if (!InsertedShift) {
806 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
807
808 if (ShiftI->getOpcode() == Instruction::AShr)
809 InsertedShift =
810 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
811 else
812 InsertedShift =
813 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
814
815 MadeChange = true;
816 }
817
818 // Replace a use of the shift with a use of the new shift.
819 TheUse = InsertedShift;
820 }
821
822 // If we removed all uses, nuke the shift.
823 if (ShiftI->use_empty())
824 ShiftI->eraseFromParent();
825
826 return MadeChange;
827}
828
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000829namespace {
830class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
831protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000832 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000833 CI->replaceAllUsesWith(With);
834 CI->eraseFromParent();
835 }
Craig Topper4584cd52014-03-07 09:26:03 +0000836 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000837 if (ConstantInt *SizeCI =
838 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
839 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000840 return false;
841 }
842};
843} // end anonymous namespace
844
Eric Christopher4b7948e2010-03-11 02:41:03 +0000845bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000846 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000847
Chris Lattner7a277142011-01-15 07:14:54 +0000848 // Lower inline assembly if we can.
849 // If we found an inline asm expession, and if the target knows how to
850 // lower it to normal LLVM code, do so now.
851 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
852 if (TLI->ExpandInlineAsm(CI)) {
853 // Avoid invalidating the iterator.
854 CurInstIterator = BB->begin();
855 // Avoid processing instructions out of order, which could cause
856 // reuse before a value is defined.
857 SunkAddrs.clear();
858 return true;
859 }
860 // Sink address computing for memory operands into the block.
861 if (OptimizeInlineAsmInst(CI))
862 return true;
863 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000864
Eric Christopher4b7948e2010-03-11 02:41:03 +0000865 // Lower all uses of llvm.objectsize.*
866 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
867 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000868 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000869 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000870 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
871
Chris Lattner1b93be52011-01-15 07:25:29 +0000872 // Substituting this can cause recursive simplifications, which can
873 // invalidate our iterator. Use a WeakVH to hold onto it in case this
874 // happens.
875 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000876
Craig Topperc0196b12014-04-14 00:51:57 +0000877 replaceAndRecursivelySimplify(CI, RetVal,
878 TLI ? TLI->getDataLayout() : nullptr,
879 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000880
881 // If the iterator instruction was recursively deleted, start over at the
882 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000883 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000884 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000885 SunkAddrs.clear();
886 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000887 return true;
888 }
889
Pete Cooper615fd892012-03-13 20:59:56 +0000890 if (II && TLI) {
891 SmallVector<Value*, 2> PtrOps;
892 Type *AccessTy;
893 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
894 while (!PtrOps.empty())
895 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
896 return true;
897 }
898
Eric Christopher4b7948e2010-03-11 02:41:03 +0000899 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +0000900 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000901
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000902 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +0000903 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000904 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000905
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000906 // Lower all default uses of _chk calls. This is very similar
907 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000908 // that have the default "don't know" as the objectsize. Anything else
909 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000910 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000911 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000912}
Chris Lattner1b93be52011-01-15 07:25:29 +0000913
Evan Cheng0663f232011-03-21 01:19:09 +0000914/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
915/// instructions to the predecessor to enable tail call optimizations. The
916/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000917/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000918/// bb0:
919/// %tmp0 = tail call i32 @f0()
920/// br label %return
921/// bb1:
922/// %tmp1 = tail call i32 @f1()
923/// br label %return
924/// bb2:
925/// %tmp2 = tail call i32 @f2()
926/// br label %return
927/// return:
928/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
929/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000930/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000931///
932/// =>
933///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000934/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000935/// bb0:
936/// %tmp0 = tail call i32 @f0()
937/// ret i32 %tmp0
938/// bb1:
939/// %tmp1 = tail call i32 @f1()
940/// ret i32 %tmp1
941/// bb2:
942/// %tmp2 = tail call i32 @f2()
943/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000944/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000945bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000946 if (!TLI)
947 return false;
948
Benjamin Kramer455fa352012-11-23 19:17:06 +0000949 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
950 if (!RI)
951 return false;
952
Craig Topperc0196b12014-04-14 00:51:57 +0000953 PHINode *PN = nullptr;
954 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +0000955 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000956 if (V) {
957 BCI = dyn_cast<BitCastInst>(V);
958 if (BCI)
959 V = BCI->getOperand(0);
960
961 PN = dyn_cast<PHINode>(V);
962 if (!PN)
963 return false;
964 }
Evan Cheng0663f232011-03-21 01:19:09 +0000965
Cameron Zwarich4649f172011-03-24 04:52:10 +0000966 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000967 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000968
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000969 // It's not safe to eliminate the sign / zero extension of the return value.
970 // See llvm::isInTailCallPosition().
971 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000972 AttributeSet CallerAttrs = F->getAttributes();
973 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
974 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000975 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000976
Cameron Zwarich4649f172011-03-24 04:52:10 +0000977 // Make sure there are no instructions between the PHI and return, or that the
978 // return is the first instruction in the block.
979 if (PN) {
980 BasicBlock::iterator BI = BB->begin();
981 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000982 if (&*BI == BCI)
983 // Also skip over the bitcast.
984 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000985 if (&*BI != RI)
986 return false;
987 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000988 BasicBlock::iterator BI = BB->begin();
989 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
990 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000991 return false;
992 }
Evan Cheng0663f232011-03-21 01:19:09 +0000993
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000994 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
995 /// call.
996 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000997 if (PN) {
998 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
999 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1000 // Make sure the phi value is indeed produced by the tail call.
1001 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1002 TLI->mayBeEmittedAsTailCall(CI))
1003 TailCalls.push_back(CI);
1004 }
1005 } else {
1006 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001007 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001008 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001009 continue;
1010
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001011 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001012 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1013 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001014 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1015 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001016 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001017
Cameron Zwarich4649f172011-03-24 04:52:10 +00001018 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001019 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001020 TailCalls.push_back(CI);
1021 }
Evan Cheng0663f232011-03-21 01:19:09 +00001022 }
1023
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001024 bool Changed = false;
1025 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1026 CallInst *CI = TailCalls[i];
1027 CallSite CS(CI);
1028
1029 // Conservatively require the attributes of the call to match those of the
1030 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001031 AttributeSet CalleeAttrs = CS.getAttributes();
1032 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001033 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001034 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001035 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001036 continue;
1037
1038 // Make sure the call instruction is followed by an unconditional branch to
1039 // the return block.
1040 BasicBlock *CallBB = CI->getParent();
1041 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1042 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1043 continue;
1044
1045 // Duplicate the return into CallBB.
1046 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001047 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001048 ++NumRetsDup;
1049 }
1050
1051 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001052 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001053 BB->eraseFromParent();
1054
1055 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001056}
1057
Chris Lattner728f9022008-11-25 07:09:13 +00001058//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001059// Memory Optimization
1060//===----------------------------------------------------------------------===//
1061
Chandler Carruthc8925912013-01-05 02:09:22 +00001062namespace {
1063
1064/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1065/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001066struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001067 Value *BaseReg;
1068 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001069 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001070 void print(raw_ostream &OS) const;
1071 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001072
Chandler Carruthc8925912013-01-05 02:09:22 +00001073 bool operator==(const ExtAddrMode& O) const {
1074 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1075 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1076 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1077 }
1078};
1079
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001080#ifndef NDEBUG
1081static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1082 AM.print(OS);
1083 return OS;
1084}
1085#endif
1086
Chandler Carruthc8925912013-01-05 02:09:22 +00001087void ExtAddrMode::print(raw_ostream &OS) const {
1088 bool NeedPlus = false;
1089 OS << "[";
1090 if (BaseGV) {
1091 OS << (NeedPlus ? " + " : "")
1092 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001093 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001094 NeedPlus = true;
1095 }
1096
Richard Trieuc0f91212014-05-30 03:15:17 +00001097 if (BaseOffs) {
1098 OS << (NeedPlus ? " + " : "")
1099 << BaseOffs;
1100 NeedPlus = true;
1101 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001102
1103 if (BaseReg) {
1104 OS << (NeedPlus ? " + " : "")
1105 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001106 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001107 NeedPlus = true;
1108 }
1109 if (Scale) {
1110 OS << (NeedPlus ? " + " : "")
1111 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001112 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001113 }
1114
1115 OS << ']';
1116}
1117
1118#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1119void ExtAddrMode::dump() const {
1120 print(dbgs());
1121 dbgs() << '\n';
1122}
1123#endif
1124
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001125/// \brief This class provides transaction based operation on the IR.
1126/// Every change made through this class is recorded in the internal state and
1127/// can be undone (rollback) until commit is called.
1128class TypePromotionTransaction {
1129
1130 /// \brief This represents the common interface of the individual transaction.
1131 /// Each class implements the logic for doing one specific modification on
1132 /// the IR via the TypePromotionTransaction.
1133 class TypePromotionAction {
1134 protected:
1135 /// The Instruction modified.
1136 Instruction *Inst;
1137
1138 public:
1139 /// \brief Constructor of the action.
1140 /// The constructor performs the related action on the IR.
1141 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1142
1143 virtual ~TypePromotionAction() {}
1144
1145 /// \brief Undo the modification done by this action.
1146 /// When this method is called, the IR must be in the same state as it was
1147 /// before this action was applied.
1148 /// \pre Undoing the action works if and only if the IR is in the exact same
1149 /// state as it was directly after this action was applied.
1150 virtual void undo() = 0;
1151
1152 /// \brief Advocate every change made by this action.
1153 /// When the results on the IR of the action are to be kept, it is important
1154 /// to call this function, otherwise hidden information may be kept forever.
1155 virtual void commit() {
1156 // Nothing to be done, this action is not doing anything.
1157 }
1158 };
1159
1160 /// \brief Utility to remember the position of an instruction.
1161 class InsertionHandler {
1162 /// Position of an instruction.
1163 /// Either an instruction:
1164 /// - Is the first in a basic block: BB is used.
1165 /// - Has a previous instructon: PrevInst is used.
1166 union {
1167 Instruction *PrevInst;
1168 BasicBlock *BB;
1169 } Point;
1170 /// Remember whether or not the instruction had a previous instruction.
1171 bool HasPrevInstruction;
1172
1173 public:
1174 /// \brief Record the position of \p Inst.
1175 InsertionHandler(Instruction *Inst) {
1176 BasicBlock::iterator It = Inst;
1177 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1178 if (HasPrevInstruction)
1179 Point.PrevInst = --It;
1180 else
1181 Point.BB = Inst->getParent();
1182 }
1183
1184 /// \brief Insert \p Inst at the recorded position.
1185 void insert(Instruction *Inst) {
1186 if (HasPrevInstruction) {
1187 if (Inst->getParent())
1188 Inst->removeFromParent();
1189 Inst->insertAfter(Point.PrevInst);
1190 } else {
1191 Instruction *Position = Point.BB->getFirstInsertionPt();
1192 if (Inst->getParent())
1193 Inst->moveBefore(Position);
1194 else
1195 Inst->insertBefore(Position);
1196 }
1197 }
1198 };
1199
1200 /// \brief Move an instruction before another.
1201 class InstructionMoveBefore : public TypePromotionAction {
1202 /// Original position of the instruction.
1203 InsertionHandler Position;
1204
1205 public:
1206 /// \brief Move \p Inst before \p Before.
1207 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1208 : TypePromotionAction(Inst), Position(Inst) {
1209 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1210 Inst->moveBefore(Before);
1211 }
1212
1213 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001214 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001215 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1216 Position.insert(Inst);
1217 }
1218 };
1219
1220 /// \brief Set the operand of an instruction with a new value.
1221 class OperandSetter : public TypePromotionAction {
1222 /// Original operand of the instruction.
1223 Value *Origin;
1224 /// Index of the modified instruction.
1225 unsigned Idx;
1226
1227 public:
1228 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1229 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1230 : TypePromotionAction(Inst), Idx(Idx) {
1231 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1232 << "for:" << *Inst << "\n"
1233 << "with:" << *NewVal << "\n");
1234 Origin = Inst->getOperand(Idx);
1235 Inst->setOperand(Idx, NewVal);
1236 }
1237
1238 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001239 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001240 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1241 << "for: " << *Inst << "\n"
1242 << "with: " << *Origin << "\n");
1243 Inst->setOperand(Idx, Origin);
1244 }
1245 };
1246
1247 /// \brief Hide the operands of an instruction.
1248 /// Do as if this instruction was not using any of its operands.
1249 class OperandsHider : public TypePromotionAction {
1250 /// The list of original operands.
1251 SmallVector<Value *, 4> OriginalValues;
1252
1253 public:
1254 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1255 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1256 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1257 unsigned NumOpnds = Inst->getNumOperands();
1258 OriginalValues.reserve(NumOpnds);
1259 for (unsigned It = 0; It < NumOpnds; ++It) {
1260 // Save the current operand.
1261 Value *Val = Inst->getOperand(It);
1262 OriginalValues.push_back(Val);
1263 // Set a dummy one.
1264 // We could use OperandSetter here, but that would implied an overhead
1265 // that we are not willing to pay.
1266 Inst->setOperand(It, UndefValue::get(Val->getType()));
1267 }
1268 }
1269
1270 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001271 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001272 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1273 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1274 Inst->setOperand(It, OriginalValues[It]);
1275 }
1276 };
1277
1278 /// \brief Build a truncate instruction.
1279 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001280 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001281 public:
1282 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1283 /// result.
1284 /// trunc Opnd to Ty.
1285 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1286 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001287 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1288 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001289 }
1290
Quentin Colombetac55b152014-09-16 22:36:07 +00001291 /// \brief Get the built value.
1292 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001293
1294 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001295 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001296 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1297 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1298 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001299 }
1300 };
1301
1302 /// \brief Build a sign extension instruction.
1303 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001304 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001305 public:
1306 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1307 /// result.
1308 /// sext Opnd to Ty.
1309 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001310 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001311 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001312 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1313 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001314 }
1315
Quentin Colombetac55b152014-09-16 22:36:07 +00001316 /// \brief Get the built value.
1317 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001318
1319 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001320 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001321 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1322 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1323 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001324 }
1325 };
1326
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001327 /// \brief Build a zero extension instruction.
1328 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001329 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001330 public:
1331 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1332 /// result.
1333 /// zext Opnd to Ty.
1334 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001335 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001336 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001337 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1338 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001339 }
1340
Quentin Colombetac55b152014-09-16 22:36:07 +00001341 /// \brief Get the built value.
1342 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001343
1344 /// \brief Remove the built instruction.
1345 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001346 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1347 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1348 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001349 }
1350 };
1351
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001352 /// \brief Mutate an instruction to another type.
1353 class TypeMutator : public TypePromotionAction {
1354 /// Record the original type.
1355 Type *OrigTy;
1356
1357 public:
1358 /// \brief Mutate the type of \p Inst into \p NewTy.
1359 TypeMutator(Instruction *Inst, Type *NewTy)
1360 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1361 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1362 << "\n");
1363 Inst->mutateType(NewTy);
1364 }
1365
1366 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001367 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001368 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1369 << "\n");
1370 Inst->mutateType(OrigTy);
1371 }
1372 };
1373
1374 /// \brief Replace the uses of an instruction by another instruction.
1375 class UsesReplacer : public TypePromotionAction {
1376 /// Helper structure to keep track of the replaced uses.
1377 struct InstructionAndIdx {
1378 /// The instruction using the instruction.
1379 Instruction *Inst;
1380 /// The index where this instruction is used for Inst.
1381 unsigned Idx;
1382 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1383 : Inst(Inst), Idx(Idx) {}
1384 };
1385
1386 /// Keep track of the original uses (pair Instruction, Index).
1387 SmallVector<InstructionAndIdx, 4> OriginalUses;
1388 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1389
1390 public:
1391 /// \brief Replace all the use of \p Inst by \p New.
1392 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1393 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1394 << "\n");
1395 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001396 for (Use &U : Inst->uses()) {
1397 Instruction *UserI = cast<Instruction>(U.getUser());
1398 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001399 }
1400 // Now, we can replace the uses.
1401 Inst->replaceAllUsesWith(New);
1402 }
1403
1404 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001405 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001406 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1407 for (use_iterator UseIt = OriginalUses.begin(),
1408 EndIt = OriginalUses.end();
1409 UseIt != EndIt; ++UseIt) {
1410 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1411 }
1412 }
1413 };
1414
1415 /// \brief Remove an instruction from the IR.
1416 class InstructionRemover : public TypePromotionAction {
1417 /// Original position of the instruction.
1418 InsertionHandler Inserter;
1419 /// Helper structure to hide all the link to the instruction. In other
1420 /// words, this helps to do as if the instruction was removed.
1421 OperandsHider Hider;
1422 /// Keep track of the uses replaced, if any.
1423 UsesReplacer *Replacer;
1424
1425 public:
1426 /// \brief Remove all reference of \p Inst and optinally replace all its
1427 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001428 /// \pre If !Inst->use_empty(), then New != nullptr
1429 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001430 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001431 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001432 if (New)
1433 Replacer = new UsesReplacer(Inst, New);
1434 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1435 Inst->removeFromParent();
1436 }
1437
1438 ~InstructionRemover() { delete Replacer; }
1439
1440 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001441 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001442
1443 /// \brief Resurrect the instruction and reassign it to the proper uses if
1444 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001445 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001446 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1447 Inserter.insert(Inst);
1448 if (Replacer)
1449 Replacer->undo();
1450 Hider.undo();
1451 }
1452 };
1453
1454public:
1455 /// Restoration point.
1456 /// The restoration point is a pointer to an action instead of an iterator
1457 /// because the iterator may be invalidated but not the pointer.
1458 typedef const TypePromotionAction *ConstRestorationPt;
1459 /// Advocate every changes made in that transaction.
1460 void commit();
1461 /// Undo all the changes made after the given point.
1462 void rollback(ConstRestorationPt Point);
1463 /// Get the current restoration point.
1464 ConstRestorationPt getRestorationPoint() const;
1465
1466 /// \name API for IR modification with state keeping to support rollback.
1467 /// @{
1468 /// Same as Instruction::setOperand.
1469 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1470 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001471 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001472 /// Same as Value::replaceAllUsesWith.
1473 void replaceAllUsesWith(Instruction *Inst, Value *New);
1474 /// Same as Value::mutateType.
1475 void mutateType(Instruction *Inst, Type *NewTy);
1476 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00001477 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001478 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001479 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001480 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001481 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001482 /// Same as Instruction::moveBefore.
1483 void moveBefore(Instruction *Inst, Instruction *Before);
1484 /// @}
1485
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001486private:
1487 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001488 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1489 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001490};
1491
1492void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1493 Value *NewVal) {
1494 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001495 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001496}
1497
1498void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1499 Value *NewVal) {
1500 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001501 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001502}
1503
1504void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1505 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001506 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001507}
1508
1509void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001510 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001511}
1512
Quentin Colombetac55b152014-09-16 22:36:07 +00001513Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1514 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001515 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001516 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001517 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001518 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001519}
1520
Quentin Colombetac55b152014-09-16 22:36:07 +00001521Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1522 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001523 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001524 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001525 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001526 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001527}
1528
Quentin Colombetac55b152014-09-16 22:36:07 +00001529Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1530 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001531 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001532 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001533 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001534 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001535}
1536
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001537void TypePromotionTransaction::moveBefore(Instruction *Inst,
1538 Instruction *Before) {
1539 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001540 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001541}
1542
1543TypePromotionTransaction::ConstRestorationPt
1544TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00001545 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001546}
1547
1548void TypePromotionTransaction::commit() {
1549 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00001550 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001551 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001552 Actions.clear();
1553}
1554
1555void TypePromotionTransaction::rollback(
1556 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00001557 while (!Actions.empty() && Point != Actions.back().get()) {
1558 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001559 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001560 }
1561}
1562
Chandler Carruthc8925912013-01-05 02:09:22 +00001563/// \brief A helper class for matching addressing modes.
1564///
1565/// This encapsulates the logic for matching the target-legal addressing modes.
1566class AddressingModeMatcher {
1567 SmallVectorImpl<Instruction*> &AddrModeInsts;
1568 const TargetLowering &TLI;
1569
1570 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1571 /// the memory instruction that we're computing this address for.
1572 Type *AccessTy;
1573 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001574
Chandler Carruthc8925912013-01-05 02:09:22 +00001575 /// AddrMode - This is the addressing mode that we're building up. This is
1576 /// part of the return value of this addressing mode matching stuff.
1577 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001578
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001579 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1580 const SetOfInstrs &InsertedTruncs;
1581 /// A map from the instructions to their type before promotion.
1582 InstrToOrigTy &PromotedInsts;
1583 /// The ongoing transaction where every action should be registered.
1584 TypePromotionTransaction &TPT;
1585
Chandler Carruthc8925912013-01-05 02:09:22 +00001586 /// IgnoreProfitability - This is set to true when we should not do
1587 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1588 /// always returns true.
1589 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001590
Chandler Carruthc8925912013-01-05 02:09:22 +00001591 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1592 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001593 Instruction *MI, ExtAddrMode &AM,
1594 const SetOfInstrs &InsertedTruncs,
1595 InstrToOrigTy &PromotedInsts,
1596 TypePromotionTransaction &TPT)
1597 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1598 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001599 IgnoreProfitability = false;
1600 }
1601public:
Stephen Lin837bba12013-07-15 17:55:02 +00001602
Chandler Carruthc8925912013-01-05 02:09:22 +00001603 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1604 /// give an access type of AccessTy. This returns a list of involved
1605 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001606 /// \p InsertedTruncs The truncate instruction inserted by other
1607 /// CodeGenPrepare
1608 /// optimizations.
1609 /// \p PromotedInsts maps the instructions to their type before promotion.
1610 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001611 static ExtAddrMode Match(Value *V, Type *AccessTy,
1612 Instruction *MemoryInst,
1613 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001614 const TargetLowering &TLI,
1615 const SetOfInstrs &InsertedTruncs,
1616 InstrToOrigTy &PromotedInsts,
1617 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001618 ExtAddrMode Result;
1619
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001620 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1621 MemoryInst, Result, InsertedTruncs,
1622 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001623 (void)Success; assert(Success && "Couldn't select *anything*?");
1624 return Result;
1625 }
1626private:
1627 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1628 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001629 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00001630 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00001631 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1632 ExtAddrMode &AMBefore,
1633 ExtAddrMode &AMAfter);
1634 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001635 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1636 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001637};
1638
1639/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1640/// Return true and update AddrMode if this addr mode is legal for the target,
1641/// false if not.
1642bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1643 unsigned Depth) {
1644 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1645 // mode. Just process that directly.
1646 if (Scale == 1)
1647 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001648
Chandler Carruthc8925912013-01-05 02:09:22 +00001649 // If the scale is 0, it takes nothing to add this.
1650 if (Scale == 0)
1651 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001652
Chandler Carruthc8925912013-01-05 02:09:22 +00001653 // If we already have a scale of this value, we can add to it, otherwise, we
1654 // need an available scale field.
1655 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1656 return false;
1657
1658 ExtAddrMode TestAddrMode = AddrMode;
1659
1660 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1661 // [A+B + A*7] -> [B+A*8].
1662 TestAddrMode.Scale += Scale;
1663 TestAddrMode.ScaledReg = ScaleReg;
1664
1665 // If the new address isn't legal, bail out.
1666 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1667 return false;
1668
1669 // It was legal, so commit it.
1670 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001671
Chandler Carruthc8925912013-01-05 02:09:22 +00001672 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1673 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1674 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00001675 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00001676 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1677 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1678 TestAddrMode.ScaledReg = AddLHS;
1679 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001680
Chandler Carruthc8925912013-01-05 02:09:22 +00001681 // If this addressing mode is legal, commit it and remember that we folded
1682 // this instruction.
1683 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1684 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1685 AddrMode = TestAddrMode;
1686 return true;
1687 }
1688 }
1689
1690 // Otherwise, not (x+c)*scale, just return what we have.
1691 return true;
1692}
1693
1694/// MightBeFoldableInst - This is a little filter, which returns true if an
1695/// addressing computation involving I might be folded into a load/store
1696/// accessing it. This doesn't need to be perfect, but needs to accept at least
1697/// the set of instructions that MatchOperationAddr can.
1698static bool MightBeFoldableInst(Instruction *I) {
1699 switch (I->getOpcode()) {
1700 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00001701 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00001702 // Don't touch identity bitcasts.
1703 if (I->getType() == I->getOperand(0)->getType())
1704 return false;
1705 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1706 case Instruction::PtrToInt:
1707 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1708 return true;
1709 case Instruction::IntToPtr:
1710 // We know the input is intptr_t, so this is foldable.
1711 return true;
1712 case Instruction::Add:
1713 return true;
1714 case Instruction::Mul:
1715 case Instruction::Shl:
1716 // Can only handle X*C and X << C.
1717 return isa<ConstantInt>(I->getOperand(1));
1718 case Instruction::GetElementPtr:
1719 return true;
1720 default:
1721 return false;
1722 }
1723}
1724
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001725/// \brief Hepler class to perform type promotion.
1726class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001727 /// \brief Utility function to check whether or not a sign or zero extension
1728 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1729 /// either using the operands of \p Inst or promoting \p Inst.
1730 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001731 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001732 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001733 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001734 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001735 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001736 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001737 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001738 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
1739 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001740
1741 /// \brief Utility function to determine if \p OpIdx should be promoted when
1742 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001743 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001744 if (isa<SelectInst>(Inst) && OpIdx == 0)
1745 return false;
1746 return true;
1747 }
1748
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001749 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001750 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001751 /// \p PromotedInsts maps the instructions to their type before promotion.
1752 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001753 /// created to promote the operand of Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001754 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001755 /// \return The promoted value which is used instead of Ext.
1756 static Value *promoteOperandForTruncAndAnyExt(Instruction *Ext,
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001757 TypePromotionTransaction &TPT,
1758 InstrToOrigTy &PromotedInsts,
1759 unsigned &CreatedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001760
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001761 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001762 /// operand is promotable and is not a supported trunc or sext.
1763 /// \p PromotedInsts maps the instructions to their type before promotion.
1764 /// \p CreatedInsts[out] contains how many non-free instructions have been
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001765 /// created to promote the operand of Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001766 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001767 /// \return The promoted value which is used instead of Ext.
1768 static Value *promoteOperandForOther(Instruction *Ext,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001769 TypePromotionTransaction &TPT,
1770 InstrToOrigTy &PromotedInsts,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001771 unsigned &CreatedInsts, bool IsSExt);
1772
1773 /// \see promoteOperandForOther.
1774 static Value *signExtendOperandForOther(Instruction *Ext,
1775 TypePromotionTransaction &TPT,
1776 InstrToOrigTy &PromotedInsts,
1777 unsigned &CreatedInsts) {
1778 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, true);
1779 }
1780
1781 /// \see promoteOperandForOther.
1782 static Value *zeroExtendOperandForOther(Instruction *Ext,
1783 TypePromotionTransaction &TPT,
1784 InstrToOrigTy &PromotedInsts,
1785 unsigned &CreatedInsts) {
1786 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, false);
1787 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001788
1789public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001790 /// Type for the utility function that promotes the operand of Ext.
1791 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001792 InstrToOrigTy &PromotedInsts,
1793 unsigned &CreatedInsts);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001794 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
1795 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001796 /// \return NULL if no promotable action is possible with the current
1797 /// sign extension.
1798 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1799 /// the others CodeGenPrepare optimizations. This information is important
1800 /// because we do not want to promote these instructions as CodeGenPrepare
1801 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1802 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001803 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001804 const TargetLowering &TLI,
1805 const InstrToOrigTy &PromotedInsts);
1806};
1807
1808bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001809 Type *ConsideredExtType,
1810 const InstrToOrigTy &PromotedInsts,
1811 bool IsSExt) {
1812 // We can always get through zext.
1813 if (isa<ZExtInst>(Inst))
1814 return true;
1815
1816 // sext(sext) is ok too.
1817 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001818 return true;
1819
1820 // We can get through binary operator, if it is legal. In other words, the
1821 // binary operator must have a nuw or nsw flag.
1822 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1823 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001824 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
1825 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001826 return true;
1827
1828 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001829 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001830 if (!isa<TruncInst>(Inst))
1831 return false;
1832
1833 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001834 // Check if we can use this operand in the extension.
1835 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001836 // we cannot.
1837 if (OpndVal->getType()->getIntegerBitWidth() >
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001838 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001839 return false;
1840
1841 // If the operand of the truncate is not an instruction, we will not have
1842 // any information on the dropped bits.
1843 // (Actually we could for constant but it is not worth the extra logic).
1844 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1845 if (!Opnd)
1846 return false;
1847
1848 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001849 // I.e., check that trunc just drops extended bits of the same kind of
1850 // the extension.
1851 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001852 const Type *OpndType;
1853 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001854 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
1855 OpndType = It->second.Ty;
1856 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
1857 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001858 else
1859 return false;
1860
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001861 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001862 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1863 return true;
1864
1865 return false;
1866}
1867
1868TypePromotionHelper::Action TypePromotionHelper::getAction(
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001869 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001870 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001871 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
1872 "Unexpected instruction type");
1873 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
1874 Type *ExtTy = Ext->getType();
1875 bool IsSExt = isa<SExtInst>(Ext);
1876 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001877 // get through.
1878 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001879 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00001880 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001881
1882 // Do not promote if the operand has been added by codegenprepare.
1883 // Otherwise, it means we are undoing an optimization that is likely to be
1884 // redone, thus causing potential infinite loop.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001885 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00001886 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001887
1888 // SExt or Trunc instructions.
1889 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001890 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
1891 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001892 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001893
1894 // Regular instruction.
1895 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001896 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00001897 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001898 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001899}
1900
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001901Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001902 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1903 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1904 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1905 // get through it and this method should not be called.
1906 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00001907 Value *ExtVal = SExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001908 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001909 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001910 // => zext(opnd).
Quentin Colombetac55b152014-09-16 22:36:07 +00001911 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001912 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1913 TPT.replaceAllUsesWith(SExt, ZExt);
1914 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001915 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001916 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001917 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
1918 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001919 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1920 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001921 CreatedInsts = 0;
1922
1923 // Remove dead code.
1924 if (SExtOpnd->use_empty())
1925 TPT.eraseInstruction(SExtOpnd);
1926
Quentin Colombet9dcb7242014-09-15 18:26:58 +00001927 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00001928 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1929 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
1930 return ExtVal;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001931
Quentin Colombet9dcb7242014-09-15 18:26:58 +00001932 // At this point we have: ext ty opnd to ty.
1933 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1934 Value *NextVal = ExtInst->getOperand(0);
1935 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001936 return NextVal;
1937}
1938
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001939Value *TypePromotionHelper::promoteOperandForOther(
1940 Instruction *Ext, TypePromotionTransaction &TPT,
1941 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts, bool IsSExt) {
1942 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001943 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001944 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001945 CreatedInsts = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001946 if (!ExtOpnd->hasOneUse()) {
1947 // ExtOpnd will be promoted.
1948 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001949 // promoted version.
1950 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001951 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00001952 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
1953 ITrunc->removeFromParent();
1954 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001955 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001956 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001957
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001958 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
1959 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001960 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001961 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001962 }
1963
1964 // Get through the Instruction:
1965 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001966 // 2. Replace the uses of Ext by Inst.
1967 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001968
1969 // Remember the original type of the instruction before promotion.
1970 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001971 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
1972 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001973 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001974 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001975 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001976 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001977 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001978 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001979
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001980 DEBUG(dbgs() << "Propagate Ext to operands\n");
1981 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001982 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001983 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
1984 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
1985 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001986 DEBUG(dbgs() << "No need to propagate\n");
1987 continue;
1988 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001989 // Check if we can statically extend the operand.
1990 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001991 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00001992 DEBUG(dbgs() << "Statically extend\n");
1993 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
1994 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
1995 : Cst->getValue().zext(BitWidth);
1996 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001997 continue;
1998 }
1999 // UndefValue are typed, so we have to statically sign extend them.
2000 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002001 DEBUG(dbgs() << "Statically extend\n");
2002 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002003 continue;
2004 }
2005
2006 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002007 // Check if Ext was reused to extend an operand.
2008 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002009 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002010 DEBUG(dbgs() << "More operands to ext\n");
2011 ExtForOpnd =
2012 cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2013 : TPT.createZExt(Ext, Opnd, Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002014 ++CreatedInsts;
2015 }
2016
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002017 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002018
2019 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002020 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2021 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002022 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002023 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002024 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002025 if (ExtForOpnd == Ext) {
2026 DEBUG(dbgs() << "Extension is useless now\n");
2027 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002028 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002029 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002030}
2031
Quentin Colombet867c5502014-02-14 22:23:22 +00002032/// IsPromotionProfitable - Check whether or not promoting an instruction
2033/// to a wider type was profitable.
2034/// \p MatchedSize gives the number of instructions that have been matched
2035/// in the addressing mode after the promotion was applied.
2036/// \p SizeWithPromotion gives the number of created instructions for
2037/// the promotion plus the number of instructions that have been
2038/// matched in the addressing mode before the promotion.
2039/// \p PromotedOperand is the value that has been promoted.
2040/// \return True if the promotion is profitable, false otherwise.
2041bool
2042AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2043 unsigned SizeWithPromotion,
2044 Value *PromotedOperand) const {
2045 // We folded less instructions than what we created to promote the operand.
2046 // This is not profitable.
2047 if (MatchedSize < SizeWithPromotion)
2048 return false;
2049 if (MatchedSize > SizeWithPromotion)
2050 return true;
2051 // The promotion is neutral but it may help folding the sign extension in
2052 // loads for instance.
2053 // Check that we did not create an illegal instruction.
2054 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2055 if (!PromotedInst)
2056 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00002057 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2058 // If the ISDOpcode is undefined, it was undefined before the promotion.
2059 if (!ISDOpcode)
2060 return true;
2061 // Otherwise, check if the promoted instruction is legal or not.
Ahmed Bougacha026600d2014-11-12 23:05:03 +00002062 return TLI.isOperationLegalOrCustom(
2063 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
Quentin Colombet867c5502014-02-14 22:23:22 +00002064}
2065
Chandler Carruthc8925912013-01-05 02:09:22 +00002066/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2067/// fold the operation into the addressing mode. If so, update the addressing
2068/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002069/// If \p MovedAway is not NULL, it contains the information of whether or
2070/// not AddrInst has to be folded into the addressing mode on success.
2071/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2072/// because it has been moved away.
2073/// Thus AddrInst must not be added in the matched instructions.
2074/// This state can happen when AddrInst is a sext, since it may be moved away.
2075/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2076/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002077bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002078 unsigned Depth,
2079 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002080 // Avoid exponential behavior on extremely deep expression trees.
2081 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002082
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002083 // By default, all matched instructions stay in place.
2084 if (MovedAway)
2085 *MovedAway = false;
2086
Chandler Carruthc8925912013-01-05 02:09:22 +00002087 switch (Opcode) {
2088 case Instruction::PtrToInt:
2089 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2090 return MatchAddr(AddrInst->getOperand(0), Depth);
2091 case Instruction::IntToPtr:
2092 // This inttoptr is a no-op if the integer type is pointer sized.
2093 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002094 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002095 return MatchAddr(AddrInst->getOperand(0), Depth);
2096 return false;
2097 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002098 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002099 // BitCast is always a noop, and we can handle it as long as it is
2100 // int->int or pointer->pointer (we don't want int<->fp or something).
2101 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2102 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2103 // Don't touch identity bitcasts. These were probably put here by LSR,
2104 // and we don't want to mess around with them. Assume it knows what it
2105 // is doing.
2106 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2107 return MatchAddr(AddrInst->getOperand(0), Depth);
2108 return false;
2109 case Instruction::Add: {
2110 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2111 ExtAddrMode BackupAddrMode = AddrMode;
2112 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002113 // Start a transaction at this point.
2114 // The LHS may match but not the RHS.
2115 // Therefore, we need a higher level restoration point to undo partially
2116 // matched operation.
2117 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2118 TPT.getRestorationPoint();
2119
Chandler Carruthc8925912013-01-05 02:09:22 +00002120 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2121 MatchAddr(AddrInst->getOperand(0), Depth+1))
2122 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002123
Chandler Carruthc8925912013-01-05 02:09:22 +00002124 // Restore the old addr mode info.
2125 AddrMode = BackupAddrMode;
2126 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002127 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002128
Chandler Carruthc8925912013-01-05 02:09:22 +00002129 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2130 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2131 MatchAddr(AddrInst->getOperand(1), Depth+1))
2132 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002133
Chandler Carruthc8925912013-01-05 02:09:22 +00002134 // Otherwise we definitely can't merge the ADD in.
2135 AddrMode = BackupAddrMode;
2136 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002137 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002138 break;
2139 }
2140 //case Instruction::Or:
2141 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2142 //break;
2143 case Instruction::Mul:
2144 case Instruction::Shl: {
2145 // Can only handle X*C and X << C.
2146 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002147 if (!RHS)
2148 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002149 int64_t Scale = RHS->getSExtValue();
2150 if (Opcode == Instruction::Shl)
2151 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002152
Chandler Carruthc8925912013-01-05 02:09:22 +00002153 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2154 }
2155 case Instruction::GetElementPtr: {
2156 // Scan the GEP. We check it if it contains constant offsets and at most
2157 // one variable offset.
2158 int VariableOperand = -1;
2159 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002160
Chandler Carruthc8925912013-01-05 02:09:22 +00002161 int64_t ConstantOffset = 0;
2162 const DataLayout *TD = TLI.getDataLayout();
2163 gep_type_iterator GTI = gep_type_begin(AddrInst);
2164 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2165 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2166 const StructLayout *SL = TD->getStructLayout(STy);
2167 unsigned Idx =
2168 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2169 ConstantOffset += SL->getElementOffset(Idx);
2170 } else {
2171 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2172 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2173 ConstantOffset += CI->getSExtValue()*TypeSize;
2174 } else if (TypeSize) { // Scales of zero don't do anything.
2175 // We only allow one variable index at the moment.
2176 if (VariableOperand != -1)
2177 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002178
Chandler Carruthc8925912013-01-05 02:09:22 +00002179 // Remember the variable index.
2180 VariableOperand = i;
2181 VariableScale = TypeSize;
2182 }
2183 }
2184 }
Stephen Lin837bba12013-07-15 17:55:02 +00002185
Chandler Carruthc8925912013-01-05 02:09:22 +00002186 // A common case is for the GEP to only do a constant offset. In this case,
2187 // just add it to the disp field and check validity.
2188 if (VariableOperand == -1) {
2189 AddrMode.BaseOffs += ConstantOffset;
2190 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2191 // Check to see if we can fold the base pointer in too.
2192 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2193 return true;
2194 }
2195 AddrMode.BaseOffs -= ConstantOffset;
2196 return false;
2197 }
2198
2199 // Save the valid addressing mode in case we can't match.
2200 ExtAddrMode BackupAddrMode = AddrMode;
2201 unsigned OldSize = AddrModeInsts.size();
2202
2203 // See if the scale and offset amount is valid for this target.
2204 AddrMode.BaseOffs += ConstantOffset;
2205
2206 // Match the base operand of the GEP.
2207 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2208 // If it couldn't be matched, just stuff the value in a register.
2209 if (AddrMode.HasBaseReg) {
2210 AddrMode = BackupAddrMode;
2211 AddrModeInsts.resize(OldSize);
2212 return false;
2213 }
2214 AddrMode.HasBaseReg = true;
2215 AddrMode.BaseReg = AddrInst->getOperand(0);
2216 }
2217
2218 // Match the remaining variable portion of the GEP.
2219 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2220 Depth)) {
2221 // If it couldn't be matched, try stuffing the base into a register
2222 // instead of matching it, and retrying the match of the scale.
2223 AddrMode = BackupAddrMode;
2224 AddrModeInsts.resize(OldSize);
2225 if (AddrMode.HasBaseReg)
2226 return false;
2227 AddrMode.HasBaseReg = true;
2228 AddrMode.BaseReg = AddrInst->getOperand(0);
2229 AddrMode.BaseOffs += ConstantOffset;
2230 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2231 VariableScale, Depth)) {
2232 // If even that didn't work, bail.
2233 AddrMode = BackupAddrMode;
2234 AddrModeInsts.resize(OldSize);
2235 return false;
2236 }
2237 }
2238
2239 return true;
2240 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002241 case Instruction::SExt:
2242 case Instruction::ZExt: {
2243 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2244 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002245 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002246
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002247 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002248 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002249 TypePromotionHelper::Action TPH =
2250 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002251 if (!TPH)
2252 return false;
2253
2254 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2255 TPT.getRestorationPoint();
2256 unsigned CreatedInsts = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002257 Value *PromotedOperand = TPH(Ext, TPT, PromotedInsts, CreatedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002258 // SExt has been moved away.
2259 // Thus either it will be rematched later in the recursive calls or it is
2260 // gone. Anyway, we must not fold it into the addressing mode at this point.
2261 // E.g.,
2262 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002263 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002264 // addr = gep base, idx
2265 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002266 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002267 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2268 // addr = gep base, op <- match
2269 if (MovedAway)
2270 *MovedAway = true;
2271
2272 assert(PromotedOperand &&
2273 "TypePromotionHelper should have filtered out those cases");
2274
2275 ExtAddrMode BackupAddrMode = AddrMode;
2276 unsigned OldSize = AddrModeInsts.size();
2277
2278 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002279 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2280 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002281 AddrMode = BackupAddrMode;
2282 AddrModeInsts.resize(OldSize);
2283 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2284 TPT.rollback(LastKnownGood);
2285 return false;
2286 }
2287 return true;
2288 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002289 }
2290 return false;
2291}
2292
2293/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2294/// addressing mode. If Addr can't be added to AddrMode this returns false and
2295/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2296/// or intptr_t for the target.
2297///
2298bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002299 // Start a transaction at this point that we will rollback if the matching
2300 // fails.
2301 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2302 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002303 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2304 // Fold in immediates if legal for the target.
2305 AddrMode.BaseOffs += CI->getSExtValue();
2306 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2307 return true;
2308 AddrMode.BaseOffs -= CI->getSExtValue();
2309 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2310 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002311 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002312 AddrMode.BaseGV = GV;
2313 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2314 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002315 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002316 }
2317 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2318 ExtAddrMode BackupAddrMode = AddrMode;
2319 unsigned OldSize = AddrModeInsts.size();
2320
2321 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322 bool MovedAway = false;
2323 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2324 // This instruction may have been move away. If so, there is nothing
2325 // to check here.
2326 if (MovedAway)
2327 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002328 // Okay, it's possible to fold this. Check to see if it is actually
2329 // *profitable* to do so. We use a simple cost model to avoid increasing
2330 // register pressure too much.
2331 if (I->hasOneUse() ||
2332 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2333 AddrModeInsts.push_back(I);
2334 return true;
2335 }
Stephen Lin837bba12013-07-15 17:55:02 +00002336
Chandler Carruthc8925912013-01-05 02:09:22 +00002337 // It isn't profitable to do this, roll back.
2338 //cerr << "NOT FOLDING: " << *I;
2339 AddrMode = BackupAddrMode;
2340 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002341 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002342 }
2343 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2344 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2345 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002346 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002347 } else if (isa<ConstantPointerNull>(Addr)) {
2348 // Null pointer gets folded without affecting the addressing mode.
2349 return true;
2350 }
2351
2352 // Worse case, the target should support [reg] addressing modes. :)
2353 if (!AddrMode.HasBaseReg) {
2354 AddrMode.HasBaseReg = true;
2355 AddrMode.BaseReg = Addr;
2356 // Still check for legality in case the target supports [imm] but not [i+r].
2357 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2358 return true;
2359 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002360 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002361 }
2362
2363 // If the base register is already taken, see if we can do [r+r].
2364 if (AddrMode.Scale == 0) {
2365 AddrMode.Scale = 1;
2366 AddrMode.ScaledReg = Addr;
2367 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2368 return true;
2369 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002370 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002371 }
2372 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002373 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002374 return false;
2375}
2376
2377/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2378/// inline asm call are due to memory operands. If so, return true, otherwise
2379/// return false.
2380static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2381 const TargetLowering &TLI) {
2382 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2383 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2384 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002385
Chandler Carruthc8925912013-01-05 02:09:22 +00002386 // Compute the constraint code and ConstraintType to use.
2387 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2388
2389 // If this asm operand is our Value*, and if it isn't an indirect memory
2390 // operand, we can't fold it!
2391 if (OpInfo.CallOperandVal == OpVal &&
2392 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2393 !OpInfo.isIndirect))
2394 return false;
2395 }
2396
2397 return true;
2398}
2399
2400/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2401/// memory use. If we find an obviously non-foldable instruction, return true.
2402/// Add the ultimately found memory instructions to MemoryUses.
2403static bool FindAllMemoryUses(Instruction *I,
2404 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Craig Topper71b7b682014-08-21 05:55:13 +00002405 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
Chandler Carruthc8925912013-01-05 02:09:22 +00002406 const TargetLowering &TLI) {
2407 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00002408 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00002409 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002410
Chandler Carruthc8925912013-01-05 02:09:22 +00002411 // If this is an obviously unfoldable instruction, bail out.
2412 if (!MightBeFoldableInst(I))
2413 return true;
2414
2415 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002416 for (Use &U : I->uses()) {
2417 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002418
Chandler Carruthcdf47882014-03-09 03:16:01 +00002419 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2420 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002421 continue;
2422 }
Stephen Lin837bba12013-07-15 17:55:02 +00002423
Chandler Carruthcdf47882014-03-09 03:16:01 +00002424 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2425 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002426 if (opNo == 0) return true; // Storing addr, not into addr.
2427 MemoryUses.push_back(std::make_pair(SI, opNo));
2428 continue;
2429 }
Stephen Lin837bba12013-07-15 17:55:02 +00002430
Chandler Carruthcdf47882014-03-09 03:16:01 +00002431 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002432 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2433 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002434
Chandler Carruthc8925912013-01-05 02:09:22 +00002435 // If this is a memory operand, we're cool, otherwise bail out.
2436 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2437 return true;
2438 continue;
2439 }
Stephen Lin837bba12013-07-15 17:55:02 +00002440
Chandler Carruthcdf47882014-03-09 03:16:01 +00002441 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002442 return true;
2443 }
2444
2445 return false;
2446}
2447
2448/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2449/// the use site that we're folding it into. If so, there is no cost to
2450/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2451/// that we know are live at the instruction already.
2452bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2453 Value *KnownLive2) {
2454 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002455 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002456 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002457
Chandler Carruthc8925912013-01-05 02:09:22 +00002458 // All values other than instructions and arguments (e.g. constants) are live.
2459 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002460
Chandler Carruthc8925912013-01-05 02:09:22 +00002461 // If Val is a constant sized alloca in the entry block, it is live, this is
2462 // true because it is just a reference to the stack/frame pointer, which is
2463 // live for the whole function.
2464 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2465 if (AI->isStaticAlloca())
2466 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002467
Chandler Carruthc8925912013-01-05 02:09:22 +00002468 // Check to see if this value is already used in the memory instruction's
2469 // block. If so, it's already live into the block at the very least, so we
2470 // can reasonably fold it.
2471 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2472}
2473
2474/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2475/// mode of the machine to fold the specified instruction into a load or store
2476/// that ultimately uses it. However, the specified instruction has multiple
2477/// uses. Given this, it may actually increase register pressure to fold it
2478/// into the load. For example, consider this code:
2479///
2480/// X = ...
2481/// Y = X+1
2482/// use(Y) -> nonload/store
2483/// Z = Y+1
2484/// load Z
2485///
2486/// In this case, Y has multiple uses, and can be folded into the load of Z
2487/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2488/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2489/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2490/// number of computations either.
2491///
2492/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2493/// X was live across 'load Z' for other reasons, we actually *would* want to
2494/// fold the addressing mode in the Z case. This would make Y die earlier.
2495bool AddressingModeMatcher::
2496IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2497 ExtAddrMode &AMAfter) {
2498 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002499
Chandler Carruthc8925912013-01-05 02:09:22 +00002500 // AMBefore is the addressing mode before this instruction was folded into it,
2501 // and AMAfter is the addressing mode after the instruction was folded. Get
2502 // the set of registers referenced by AMAfter and subtract out those
2503 // referenced by AMBefore: this is the set of values which folding in this
2504 // address extends the lifetime of.
2505 //
2506 // Note that there are only two potential values being referenced here,
2507 // BaseReg and ScaleReg (global addresses are always available, as are any
2508 // folded immediates).
2509 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002510
Chandler Carruthc8925912013-01-05 02:09:22 +00002511 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2512 // lifetime wasn't extended by adding this instruction.
2513 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002514 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002515 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002516 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002517
2518 // If folding this instruction (and it's subexprs) didn't extend any live
2519 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002520 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002521 return true;
2522
2523 // If all uses of this instruction are ultimately load/store/inlineasm's,
2524 // check to see if their addressing modes will include this instruction. If
2525 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2526 // uses.
2527 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2528 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2529 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2530 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002531
Chandler Carruthc8925912013-01-05 02:09:22 +00002532 // Now that we know that all uses of this instruction are part of a chain of
2533 // computation involving only operations that could theoretically be folded
2534 // into a memory use, loop over each of these uses and see if they could
2535 // *actually* fold the instruction.
2536 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2537 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2538 Instruction *User = MemoryUses[i].first;
2539 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002540
Chandler Carruthc8925912013-01-05 02:09:22 +00002541 // Get the access type of this use. If the use isn't a pointer, we don't
2542 // know what it accesses.
2543 Value *Address = User->getOperand(OpNo);
2544 if (!Address->getType()->isPointerTy())
2545 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002546 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002547
Chandler Carruthc8925912013-01-05 02:09:22 +00002548 // Do a match against the root of this address, ignoring profitability. This
2549 // will tell us if the addressing mode for the memory operation will
2550 // *actually* cover the shared instruction.
2551 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002552 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2553 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002554 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002555 MemoryInst, Result, InsertedTruncs,
2556 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002557 Matcher.IgnoreProfitability = true;
2558 bool Success = Matcher.MatchAddr(Address, 0);
2559 (void)Success; assert(Success && "Couldn't select *anything*?");
2560
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002561 // The match was to check the profitability, the changes made are not
2562 // part of the original matcher. Therefore, they should be dropped
2563 // otherwise the original matcher will not present the right state.
2564 TPT.rollback(LastKnownGood);
2565
Chandler Carruthc8925912013-01-05 02:09:22 +00002566 // If the match didn't cover I, then it won't be shared by it.
2567 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2568 I) == MatchedAddrModeInsts.end())
2569 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002570
Chandler Carruthc8925912013-01-05 02:09:22 +00002571 MatchedAddrModeInsts.clear();
2572 }
Stephen Lin837bba12013-07-15 17:55:02 +00002573
Chandler Carruthc8925912013-01-05 02:09:22 +00002574 return true;
2575}
2576
2577} // end anonymous namespace
2578
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002579/// IsNonLocalValue - Return true if the specified values are defined in a
2580/// different basic block than BB.
2581static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2582 if (Instruction *I = dyn_cast<Instruction>(V))
2583 return I->getParent() != BB;
2584 return false;
2585}
2586
Bob Wilson53bdae32009-12-03 21:47:07 +00002587/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002588/// addressing modes that can do significant amounts of computation. As such,
2589/// instruction selection will try to get the load or store to do as much
2590/// computation as possible for the program. The problem is that isel can only
2591/// see within a single block. As such, we sink as much legal addressing mode
2592/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002593///
2594/// This method is used to optimize both load/store and inline asms with memory
2595/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002596bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002597 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002598 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002599
2600 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002601 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002602 SmallVector<Value*, 8> worklist;
2603 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002604 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002605
Owen Anderson8ba5f392010-11-27 08:15:55 +00002606 // Use a worklist to iteratively look through PHI nodes, and ensure that
2607 // the addressing mode obtained from the non-PHI roots of the graph
2608 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00002609 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002610 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002611 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002612 SmallVector<Instruction*, 16> AddrModeInsts;
2613 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002614 TypePromotionTransaction TPT;
2615 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2616 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002617 while (!worklist.empty()) {
2618 Value *V = worklist.back();
2619 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002620
Owen Anderson8ba5f392010-11-27 08:15:55 +00002621 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00002622 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00002623 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002624 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002625 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002626
Owen Anderson8ba5f392010-11-27 08:15:55 +00002627 // For a PHI node, push all of its incoming values.
2628 if (PHINode *P = dyn_cast<PHINode>(V)) {
2629 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2630 worklist.push_back(P->getIncomingValue(i));
2631 continue;
2632 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002633
Owen Anderson8ba5f392010-11-27 08:15:55 +00002634 // For non-PHIs, determine the addressing mode being computed.
2635 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002636 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2637 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2638 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002639
2640 // This check is broken into two cases with very similar code to avoid using
2641 // getNumUses() as much as possible. Some values have a lot of uses, so
2642 // calling getNumUses() unconditionally caused a significant compile-time
2643 // regression.
2644 if (!Consensus) {
2645 Consensus = V;
2646 AddrMode = NewAddrMode;
2647 AddrModeInsts = NewAddrModeInsts;
2648 continue;
2649 } else if (NewAddrMode == AddrMode) {
2650 if (!IsNumUsesConsensusValid) {
2651 NumUsesConsensus = Consensus->getNumUses();
2652 IsNumUsesConsensusValid = true;
2653 }
2654
2655 // Ensure that the obtained addressing mode is equivalent to that obtained
2656 // for all other roots of the PHI traversal. Also, when choosing one
2657 // such root as representative, select the one with the most uses in order
2658 // to keep the cost modeling heuristics in AddressingModeMatcher
2659 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002660 unsigned NumUses = V->getNumUses();
2661 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002662 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002663 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002664 AddrModeInsts = NewAddrModeInsts;
2665 }
2666 continue;
2667 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002668
Craig Topperc0196b12014-04-14 00:51:57 +00002669 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002670 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002671 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002672
Owen Anderson8ba5f392010-11-27 08:15:55 +00002673 // If the addressing mode couldn't be determined, or if multiple different
2674 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002675 if (!Consensus) {
2676 TPT.rollback(LastKnownGood);
2677 return false;
2678 }
2679 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002680
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002681 // Check to see if any of the instructions supersumed by this addr mode are
2682 // non-local to I's BB.
2683 bool AnyNonLocal = false;
2684 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002685 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002686 AnyNonLocal = true;
2687 break;
2688 }
2689 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002690
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002691 // If all the instructions matched are already in this BB, don't do anything.
2692 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002693 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002694 return false;
2695 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002696
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002697 // Insert this computation right after this user. Since our caller is
2698 // scanning from the top of the BB to the bottom, reuse of the expr are
2699 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002700 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002701
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002702 // Now that we determined the addressing expression we want to use and know
2703 // that we have to sink it into this block. Check to see if we have already
2704 // done this for some other load/store instr in this block. If so, reuse the
2705 // computation.
2706 Value *&SunkAddr = SunkAddrs[Addr];
2707 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002708 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002709 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002710 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002711 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00002712 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2713 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2714 // By default, we use the GEP-based method when AA is used later. This
2715 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2716 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002717 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00002718 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002719 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002720
2721 // First, find the pointer.
2722 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2723 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002724 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002725 }
2726
2727 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2728 // We can't add more than one pointer together, nor can we scale a
2729 // pointer (both of which seem meaningless).
2730 if (ResultPtr || AddrMode.Scale != 1)
2731 return false;
2732
2733 ResultPtr = AddrMode.ScaledReg;
2734 AddrMode.Scale = 0;
2735 }
2736
2737 if (AddrMode.BaseGV) {
2738 if (ResultPtr)
2739 return false;
2740
2741 ResultPtr = AddrMode.BaseGV;
2742 }
2743
2744 // If the real base value actually came from an inttoptr, then the matcher
2745 // will look through it and provide only the integer value. In that case,
2746 // use it here.
2747 if (!ResultPtr && AddrMode.BaseReg) {
2748 ResultPtr =
2749 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00002750 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002751 } else if (!ResultPtr && AddrMode.Scale == 1) {
2752 ResultPtr =
2753 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2754 AddrMode.Scale = 0;
2755 }
2756
2757 if (!ResultPtr &&
2758 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2759 SunkAddr = Constant::getNullValue(Addr->getType());
2760 } else if (!ResultPtr) {
2761 return false;
2762 } else {
2763 Type *I8PtrTy =
2764 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2765
2766 // Start with the base register. Do this first so that subsequent address
2767 // matching finds it last, which will prevent it from trying to match it
2768 // as the scaled value in case it happens to be a mul. That would be
2769 // problematic if we've sunk a different mul for the scale, because then
2770 // we'd end up sinking both muls.
2771 if (AddrMode.BaseReg) {
2772 Value *V = AddrMode.BaseReg;
2773 if (V->getType() != IntPtrTy)
2774 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2775
2776 ResultIndex = V;
2777 }
2778
2779 // Add the scale value.
2780 if (AddrMode.Scale) {
2781 Value *V = AddrMode.ScaledReg;
2782 if (V->getType() == IntPtrTy) {
2783 // done.
2784 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2785 cast<IntegerType>(V->getType())->getBitWidth()) {
2786 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2787 } else {
2788 // It is only safe to sign extend the BaseReg if we know that the math
2789 // required to create it did not overflow before we extend it. Since
2790 // the original IR value was tossed in favor of a constant back when
2791 // the AddrMode was created we need to bail out gracefully if widths
2792 // do not match instead of extending it.
2793 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2794 if (I && (ResultIndex != AddrMode.BaseReg))
2795 I->eraseFromParent();
2796 return false;
2797 }
2798
2799 if (AddrMode.Scale != 1)
2800 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2801 "sunkaddr");
2802 if (ResultIndex)
2803 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2804 else
2805 ResultIndex = V;
2806 }
2807
2808 // Add in the Base Offset if present.
2809 if (AddrMode.BaseOffs) {
2810 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2811 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002812 // We need to add this separately from the scale above to help with
2813 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00002814 if (ResultPtr->getType() != I8PtrTy)
2815 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2816 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2817 }
2818
2819 ResultIndex = V;
2820 }
2821
2822 if (!ResultIndex) {
2823 SunkAddr = ResultPtr;
2824 } else {
2825 if (ResultPtr->getType() != I8PtrTy)
2826 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2827 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2828 }
2829
2830 if (SunkAddr->getType() != Addr->getType())
2831 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2832 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002833 } else {
David Greene74e2d492010-01-05 01:27:11 +00002834 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002835 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002836 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002837 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00002838
2839 // Start with the base register. Do this first so that subsequent address
2840 // matching finds it last, which will prevent it from trying to match it
2841 // as the scaled value in case it happens to be a mul. That would be
2842 // problematic if we've sunk a different mul for the scale, because then
2843 // we'd end up sinking both muls.
2844 if (AddrMode.BaseReg) {
2845 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002846 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002847 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002848 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002849 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002850 Result = V;
2851 }
2852
2853 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002854 if (AddrMode.Scale) {
2855 Value *V = AddrMode.ScaledReg;
2856 if (V->getType() == IntPtrTy) {
2857 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002858 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002859 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002860 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2861 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002862 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002863 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002864 // It is only safe to sign extend the BaseReg if we know that the math
2865 // required to create it did not overflow before we extend it. Since
2866 // the original IR value was tossed in favor of a constant back when
2867 // the AddrMode was created we need to bail out gracefully if widths
2868 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00002869 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00002870 if (I && (Result != AddrMode.BaseReg))
2871 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002872 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002873 }
2874 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002875 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2876 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002877 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002878 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002879 else
2880 Result = V;
2881 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002882
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002883 // Add in the BaseGV if present.
2884 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002885 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002886 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002887 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002888 else
2889 Result = V;
2890 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002891
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002892 // Add in the Base Offset if present.
2893 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002894 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002895 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002896 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002897 else
2898 Result = V;
2899 }
2900
Craig Topperc0196b12014-04-14 00:51:57 +00002901 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002902 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002903 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002904 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002905 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002906
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002907 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002908
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002909 // If we have no uses, recursively delete the value and all dead instructions
2910 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002911 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002912 // This can cause recursive deletion, which can invalidate our iterator.
2913 // Use a WeakVH to hold onto it in case this happens.
2914 WeakVH IterHandle(CurInstIterator);
2915 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002916
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002917 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002918
2919 if (IterHandle != CurInstIterator) {
2920 // If the iterator instruction was recursively deleted, start over at the
2921 // start of the block.
2922 CurInstIterator = BB->begin();
2923 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002924 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002925 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002926 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002927 return true;
2928}
2929
Evan Cheng1da25002008-02-26 02:42:37 +00002930/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002931/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002932/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002933bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002934 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002935
Nadav Rotem465834c2012-07-24 10:51:42 +00002936 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002937 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002938 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002939 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2940 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002941
Evan Cheng1da25002008-02-26 02:42:37 +00002942 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002943 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002944
Eli Friedman666bbe32008-02-26 18:37:49 +00002945 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2946 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002947 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002948 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002949 } else if (OpInfo.Type == InlineAsm::isInput)
2950 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002951 }
2952
2953 return MadeChange;
2954}
2955
Dan Gohman99429a02009-10-16 20:59:35 +00002956/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2957/// basic block as the load, unless conditions are unfavorable. This allows
2958/// SelectionDAG to fold the extend into the load.
2959///
2960bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2961 // Look for a load being extended.
2962 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2963 if (!LI) return false;
2964
2965 // If they're already in the same block, there's nothing to do.
2966 if (LI->getParent() == I->getParent())
2967 return false;
2968
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00002969 EVT VT = TLI->getValueType(I->getType());
2970 EVT LoadVT = TLI->getValueType(LI->getType());
2971
Dan Gohman99429a02009-10-16 20:59:35 +00002972 // If the load has other users and the truncate is not free, this probably
2973 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00002974 if (!LI->hasOneUse() && TLI &&
2975 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002976 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002977 return false;
2978
2979 // Check whether the target supports casts folded into loads.
2980 unsigned LType;
2981 if (isa<ZExtInst>(I))
2982 LType = ISD::ZEXTLOAD;
2983 else {
2984 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2985 LType = ISD::SEXTLOAD;
2986 }
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00002987 if (TLI && !TLI->isLoadExtLegal(LType, LoadVT))
Dan Gohman99429a02009-10-16 20:59:35 +00002988 return false;
2989
2990 // Move the extend into the same block as the load, so that SelectionDAG
2991 // can fold it.
2992 I->removeFromParent();
2993 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002994 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002995 return true;
2996}
2997
Evan Chengd3d80172007-12-05 23:58:20 +00002998bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2999 BasicBlock *DefBB = I->getParent();
3000
Bob Wilsonff714f92010-09-21 21:44:14 +00003001 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003002 // other uses of the source with result of extension.
3003 Value *Src = I->getOperand(0);
3004 if (Src->hasOneUse())
3005 return false;
3006
Evan Cheng2011df42007-12-13 07:50:36 +00003007 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003008 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003009 return false;
3010
Evan Cheng7bc89422007-12-12 00:51:06 +00003011 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003012 // this block.
3013 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003014 return false;
3015
Evan Chengd3d80172007-12-05 23:58:20 +00003016 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003017 for (User *U : I->users()) {
3018 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003019
3020 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003021 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003022 if (UserBB == DefBB) continue;
3023 DefIsLiveOut = true;
3024 break;
3025 }
3026 if (!DefIsLiveOut)
3027 return false;
3028
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003029 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003030 for (User *U : Src->users()) {
3031 Instruction *UI = cast<Instruction>(U);
3032 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003033 if (UserBB == DefBB) continue;
3034 // Be conservative. We don't want this xform to end up introducing
3035 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003036 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003037 return false;
3038 }
3039
Evan Chengd3d80172007-12-05 23:58:20 +00003040 // InsertedTruncs - Only insert one trunc in each block once.
3041 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3042
3043 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003044 for (Use &U : Src->uses()) {
3045 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003046
3047 // Figure out which BB this ext is used in.
3048 BasicBlock *UserBB = User->getParent();
3049 if (UserBB == DefBB) continue;
3050
3051 // Both src and def are live in this block. Rewrite the use.
3052 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3053
3054 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003055 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003056 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003057 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003058 }
3059
3060 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003061 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003062 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003063 MadeChange = true;
3064 }
3065
3066 return MadeChange;
3067}
3068
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003069/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3070/// turned into an explicit branch.
3071static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3072 // FIXME: This should use the same heuristics as IfConversion to determine
3073 // whether a select is better represented as a branch. This requires that
3074 // branch probability metadata is preserved for the select, which is not the
3075 // case currently.
3076
3077 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3078
3079 // If the branch is predicted right, an out of order CPU can avoid blocking on
3080 // the compare. Emit cmovs on compares with a memory operand as branches to
3081 // avoid stalls on the load from memory. If the compare has more than one use
3082 // there's probably another cmov or setcc around so it's not worth emitting a
3083 // branch.
3084 if (!Cmp)
3085 return false;
3086
3087 Value *CmpOp0 = Cmp->getOperand(0);
3088 Value *CmpOp1 = Cmp->getOperand(1);
3089
3090 // We check that the memory operand has one use to avoid uses of the loaded
3091 // value directly after the compare, making branches unprofitable.
3092 return Cmp->hasOneUse() &&
3093 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3094 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3095}
3096
3097
Nadav Rotem9d832022012-09-02 12:10:19 +00003098/// If we have a SelectInst that will likely profit from branch prediction,
3099/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003100bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003101 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3102
3103 // Can we convert the 'select' to CF ?
3104 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003105 return false;
3106
Nadav Rotem9d832022012-09-02 12:10:19 +00003107 TargetLowering::SelectSupportKind SelectKind;
3108 if (VectorCond)
3109 SelectKind = TargetLowering::VectorMaskSelect;
3110 else if (SI->getType()->isVectorTy())
3111 SelectKind = TargetLowering::ScalarCondVectorVal;
3112 else
3113 SelectKind = TargetLowering::ScalarValSelect;
3114
3115 // Do we have efficient codegen support for this kind of 'selects' ?
3116 if (TLI->isSelectSupported(SelectKind)) {
3117 // We have efficient codegen support for the select instruction.
3118 // Check if it is profitable to keep this 'select'.
3119 if (!TLI->isPredictableSelectExpensive() ||
3120 !isFormingBranchFromSelectProfitable(SI))
3121 return false;
3122 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003123
3124 ModifiedDT = true;
3125
3126 // First, we split the block containing the select into 2 blocks.
3127 BasicBlock *StartBlock = SI->getParent();
3128 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3129 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3130
3131 // Create a new block serving as the landing pad for the branch.
3132 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3133 NextBlock->getParent(), NextBlock);
3134
3135 // Move the unconditional branch from the block with the select in it into our
3136 // landing pad block.
3137 StartBlock->getTerminator()->eraseFromParent();
3138 BranchInst::Create(NextBlock, SmallBlock);
3139
3140 // Insert the real conditional branch based on the original condition.
3141 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3142
3143 // The select itself is replaced with a PHI Node.
3144 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3145 PN->takeName(SI);
3146 PN->addIncoming(SI->getTrueValue(), StartBlock);
3147 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3148 SI->replaceAllUsesWith(PN);
3149 SI->eraseFromParent();
3150
3151 // Instruct OptimizeBlock to skip to the next block.
3152 CurInstIterator = StartBlock->end();
3153 ++NumSelectsExpanded;
3154 return true;
3155}
3156
Benjamin Kramer573ff362014-03-01 17:24:40 +00003157static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003158 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3159 int SplatElem = -1;
3160 for (unsigned i = 0; i < Mask.size(); ++i) {
3161 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3162 return false;
3163 SplatElem = Mask[i];
3164 }
3165
3166 return true;
3167}
3168
3169/// Some targets have expensive vector shifts if the lanes aren't all the same
3170/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3171/// it's often worth sinking a shufflevector splat down to its use so that
3172/// codegen can spot all lanes are identical.
3173bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3174 BasicBlock *DefBB = SVI->getParent();
3175
3176 // Only do this xform if variable vector shifts are particularly expensive.
3177 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3178 return false;
3179
3180 // We only expect better codegen by sinking a shuffle if we can recognise a
3181 // constant splat.
3182 if (!isBroadcastShuffle(SVI))
3183 return false;
3184
3185 // InsertedShuffles - Only insert a shuffle in each block once.
3186 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3187
3188 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003189 for (User *U : SVI->users()) {
3190 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003191
3192 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003193 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003194 if (UserBB == DefBB) continue;
3195
3196 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003197 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003198
3199 // Everything checks out, sink the shuffle if the user's block doesn't
3200 // already have a copy.
3201 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3202
3203 if (!InsertedShuffle) {
3204 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3205 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3206 SVI->getOperand(1),
3207 SVI->getOperand(2), "", InsertPt);
3208 }
3209
Chandler Carruthcdf47882014-03-09 03:16:01 +00003210 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003211 MadeChange = true;
3212 }
3213
3214 // If we removed all uses, nuke the shuffle.
3215 if (SVI->use_empty()) {
3216 SVI->eraseFromParent();
3217 MadeChange = true;
3218 }
3219
3220 return MadeChange;
3221}
3222
Quentin Colombetc32615d2014-10-31 17:52:53 +00003223namespace {
3224/// \brief Helper class to promote a scalar operation to a vector one.
3225/// This class is used to move downward extractelement transition.
3226/// E.g.,
3227/// a = vector_op <2 x i32>
3228/// b = extractelement <2 x i32> a, i32 0
3229/// c = scalar_op b
3230/// store c
3231///
3232/// =>
3233/// a = vector_op <2 x i32>
3234/// c = vector_op a (equivalent to scalar_op on the related lane)
3235/// * d = extractelement <2 x i32> c, i32 0
3236/// * store d
3237/// Assuming both extractelement and store can be combine, we get rid of the
3238/// transition.
3239class VectorPromoteHelper {
3240 /// Used to perform some checks on the legality of vector operations.
3241 const TargetLowering &TLI;
3242
3243 /// Used to estimated the cost of the promoted chain.
3244 const TargetTransformInfo &TTI;
3245
3246 /// The transition being moved downwards.
3247 Instruction *Transition;
3248 /// The sequence of instructions to be promoted.
3249 SmallVector<Instruction *, 4> InstsToBePromoted;
3250 /// Cost of combining a store and an extract.
3251 unsigned StoreExtractCombineCost;
3252 /// Instruction that will be combined with the transition.
3253 Instruction *CombineInst;
3254
3255 /// \brief The instruction that represents the current end of the transition.
3256 /// Since we are faking the promotion until we reach the end of the chain
3257 /// of computation, we need a way to get the current end of the transition.
3258 Instruction *getEndOfTransition() const {
3259 if (InstsToBePromoted.empty())
3260 return Transition;
3261 return InstsToBePromoted.back();
3262 }
3263
3264 /// \brief Return the index of the original value in the transition.
3265 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3266 /// c, is at index 0.
3267 unsigned getTransitionOriginalValueIdx() const {
3268 assert(isa<ExtractElementInst>(Transition) &&
3269 "Other kind of transitions are not supported yet");
3270 return 0;
3271 }
3272
3273 /// \brief Return the index of the index in the transition.
3274 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3275 /// is at index 1.
3276 unsigned getTransitionIdx() const {
3277 assert(isa<ExtractElementInst>(Transition) &&
3278 "Other kind of transitions are not supported yet");
3279 return 1;
3280 }
3281
3282 /// \brief Get the type of the transition.
3283 /// This is the type of the original value.
3284 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3285 /// transition is <2 x i32>.
3286 Type *getTransitionType() const {
3287 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3288 }
3289
3290 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3291 /// I.e., we have the following sequence:
3292 /// Def = Transition <ty1> a to <ty2>
3293 /// b = ToBePromoted <ty2> Def, ...
3294 /// =>
3295 /// b = ToBePromoted <ty1> a, ...
3296 /// Def = Transition <ty1> ToBePromoted to <ty2>
3297 void promoteImpl(Instruction *ToBePromoted);
3298
3299 /// \brief Check whether or not it is profitable to promote all the
3300 /// instructions enqueued to be promoted.
3301 bool isProfitableToPromote() {
3302 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3303 unsigned Index = isa<ConstantInt>(ValIdx)
3304 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3305 : -1;
3306 Type *PromotedType = getTransitionType();
3307
3308 StoreInst *ST = cast<StoreInst>(CombineInst);
3309 unsigned AS = ST->getPointerAddressSpace();
3310 unsigned Align = ST->getAlignment();
3311 // Check if this store is supported.
3312 if (!TLI.allowsMisalignedMemoryAccesses(
Ahmed Bougacha026600d2014-11-12 23:05:03 +00003313 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00003314 // If this is not supported, there is no way we can combine
3315 // the extract with the store.
3316 return false;
3317 }
3318
3319 // The scalar chain of computation has to pay for the transition
3320 // scalar to vector.
3321 // The vector chain has to account for the combining cost.
3322 uint64_t ScalarCost =
3323 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3324 uint64_t VectorCost = StoreExtractCombineCost;
3325 for (const auto &Inst : InstsToBePromoted) {
3326 // Compute the cost.
3327 // By construction, all instructions being promoted are arithmetic ones.
3328 // Moreover, one argument is a constant that can be viewed as a splat
3329 // constant.
3330 Value *Arg0 = Inst->getOperand(0);
3331 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3332 isa<ConstantFP>(Arg0);
3333 TargetTransformInfo::OperandValueKind Arg0OVK =
3334 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3335 : TargetTransformInfo::OK_AnyValue;
3336 TargetTransformInfo::OperandValueKind Arg1OVK =
3337 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3338 : TargetTransformInfo::OK_AnyValue;
3339 ScalarCost += TTI.getArithmeticInstrCost(
3340 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3341 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3342 Arg0OVK, Arg1OVK);
3343 }
3344 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3345 << ScalarCost << "\nVector: " << VectorCost << '\n');
3346 return ScalarCost > VectorCost;
3347 }
3348
3349 /// \brief Generate a constant vector with \p Val with the same
3350 /// number of elements as the transition.
3351 /// \p UseSplat defines whether or not \p Val should be replicated
3352 /// accross the whole vector.
3353 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3354 /// otherwise we generate a vector with as many undef as possible:
3355 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3356 /// used at the index of the extract.
3357 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3358 unsigned ExtractIdx = UINT_MAX;
3359 if (!UseSplat) {
3360 // If we cannot determine where the constant must be, we have to
3361 // use a splat constant.
3362 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3363 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3364 ExtractIdx = CstVal->getSExtValue();
3365 else
3366 UseSplat = true;
3367 }
3368
3369 unsigned End = getTransitionType()->getVectorNumElements();
3370 if (UseSplat)
3371 return ConstantVector::getSplat(End, Val);
3372
3373 SmallVector<Constant *, 4> ConstVec;
3374 UndefValue *UndefVal = UndefValue::get(Val->getType());
3375 for (unsigned Idx = 0; Idx != End; ++Idx) {
3376 if (Idx == ExtractIdx)
3377 ConstVec.push_back(Val);
3378 else
3379 ConstVec.push_back(UndefVal);
3380 }
3381 return ConstantVector::get(ConstVec);
3382 }
3383
3384 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3385 /// in \p Use can trigger undefined behavior.
3386 static bool canCauseUndefinedBehavior(const Instruction *Use,
3387 unsigned OperandIdx) {
3388 // This is not safe to introduce undef when the operand is on
3389 // the right hand side of a division-like instruction.
3390 if (OperandIdx != 1)
3391 return false;
3392 switch (Use->getOpcode()) {
3393 default:
3394 return false;
3395 case Instruction::SDiv:
3396 case Instruction::UDiv:
3397 case Instruction::SRem:
3398 case Instruction::URem:
3399 return true;
3400 case Instruction::FDiv:
3401 case Instruction::FRem:
3402 return !Use->hasNoNaNs();
3403 }
3404 llvm_unreachable(nullptr);
3405 }
3406
3407public:
3408 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3409 Instruction *Transition, unsigned CombineCost)
3410 : TLI(TLI), TTI(TTI), Transition(Transition),
3411 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3412 assert(Transition && "Do not know how to promote null");
3413 }
3414
3415 /// \brief Check if we can promote \p ToBePromoted to \p Type.
3416 bool canPromote(const Instruction *ToBePromoted) const {
3417 // We could support CastInst too.
3418 return isa<BinaryOperator>(ToBePromoted);
3419 }
3420
3421 /// \brief Check if it is profitable to promote \p ToBePromoted
3422 /// by moving downward the transition through.
3423 bool shouldPromote(const Instruction *ToBePromoted) const {
3424 // Promote only if all the operands can be statically expanded.
3425 // Indeed, we do not want to introduce any new kind of transitions.
3426 for (const Use &U : ToBePromoted->operands()) {
3427 const Value *Val = U.get();
3428 if (Val == getEndOfTransition()) {
3429 // If the use is a division and the transition is on the rhs,
3430 // we cannot promote the operation, otherwise we may create a
3431 // division by zero.
3432 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3433 return false;
3434 continue;
3435 }
3436 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3437 !isa<ConstantFP>(Val))
3438 return false;
3439 }
3440 // Check that the resulting operation is legal.
3441 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3442 if (!ISDOpcode)
3443 return false;
3444 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00003445 TLI.isOperationLegalOrCustom(
3446 ISDOpcode, TLI.getValueType(getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00003447 }
3448
3449 /// \brief Check whether or not \p Use can be combined
3450 /// with the transition.
3451 /// I.e., is it possible to do Use(Transition) => AnotherUse?
3452 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3453
3454 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3455 void enqueueForPromotion(Instruction *ToBePromoted) {
3456 InstsToBePromoted.push_back(ToBePromoted);
3457 }
3458
3459 /// \brief Set the instruction that will be combined with the transition.
3460 void recordCombineInstruction(Instruction *ToBeCombined) {
3461 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3462 CombineInst = ToBeCombined;
3463 }
3464
3465 /// \brief Promote all the instructions enqueued for promotion if it is
3466 /// is profitable.
3467 /// \return True if the promotion happened, false otherwise.
3468 bool promote() {
3469 // Check if there is something to promote.
3470 // Right now, if we do not have anything to combine with,
3471 // we assume the promotion is not profitable.
3472 if (InstsToBePromoted.empty() || !CombineInst)
3473 return false;
3474
3475 // Check cost.
3476 if (!StressStoreExtract && !isProfitableToPromote())
3477 return false;
3478
3479 // Promote.
3480 for (auto &ToBePromoted : InstsToBePromoted)
3481 promoteImpl(ToBePromoted);
3482 InstsToBePromoted.clear();
3483 return true;
3484 }
3485};
3486} // End of anonymous namespace.
3487
3488void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3489 // At this point, we know that all the operands of ToBePromoted but Def
3490 // can be statically promoted.
3491 // For Def, we need to use its parameter in ToBePromoted:
3492 // b = ToBePromoted ty1 a
3493 // Def = Transition ty1 b to ty2
3494 // Move the transition down.
3495 // 1. Replace all uses of the promoted operation by the transition.
3496 // = ... b => = ... Def.
3497 assert(ToBePromoted->getType() == Transition->getType() &&
3498 "The type of the result of the transition does not match "
3499 "the final type");
3500 ToBePromoted->replaceAllUsesWith(Transition);
3501 // 2. Update the type of the uses.
3502 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3503 Type *TransitionTy = getTransitionType();
3504 ToBePromoted->mutateType(TransitionTy);
3505 // 3. Update all the operands of the promoted operation with promoted
3506 // operands.
3507 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3508 for (Use &U : ToBePromoted->operands()) {
3509 Value *Val = U.get();
3510 Value *NewVal = nullptr;
3511 if (Val == Transition)
3512 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3513 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3514 isa<ConstantFP>(Val)) {
3515 // Use a splat constant if it is not safe to use undef.
3516 NewVal = getConstantVector(
3517 cast<Constant>(Val),
3518 isa<UndefValue>(Val) ||
3519 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3520 } else
3521 assert(0 && "Did you modified shouldPromote and forgot to update this?");
3522 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3523 }
3524 Transition->removeFromParent();
3525 Transition->insertAfter(ToBePromoted);
3526 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3527}
3528
3529/// Some targets can do store(extractelement) with one instruction.
3530/// Try to push the extractelement towards the stores when the target
3531/// has this feature and this is profitable.
3532bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
3533 unsigned CombineCost = UINT_MAX;
3534 if (DisableStoreExtract || !TLI ||
3535 (!StressStoreExtract &&
3536 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
3537 Inst->getOperand(1), CombineCost)))
3538 return false;
3539
3540 // At this point we know that Inst is a vector to scalar transition.
3541 // Try to move it down the def-use chain, until:
3542 // - We can combine the transition with its single use
3543 // => we got rid of the transition.
3544 // - We escape the current basic block
3545 // => we would need to check that we are moving it at a cheaper place and
3546 // we do not do that for now.
3547 BasicBlock *Parent = Inst->getParent();
3548 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
3549 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
3550 // If the transition has more than one use, assume this is not going to be
3551 // beneficial.
3552 while (Inst->hasOneUse()) {
3553 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
3554 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
3555
3556 if (ToBePromoted->getParent() != Parent) {
3557 DEBUG(dbgs() << "Instruction to promote is in a different block ("
3558 << ToBePromoted->getParent()->getName()
3559 << ") than the transition (" << Parent->getName() << ").\n");
3560 return false;
3561 }
3562
3563 if (VPH.canCombine(ToBePromoted)) {
3564 DEBUG(dbgs() << "Assume " << *Inst << '\n'
3565 << "will be combined with: " << *ToBePromoted << '\n');
3566 VPH.recordCombineInstruction(ToBePromoted);
3567 bool Changed = VPH.promote();
3568 NumStoreExtractExposed += Changed;
3569 return Changed;
3570 }
3571
3572 DEBUG(dbgs() << "Try promoting.\n");
3573 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
3574 return false;
3575
3576 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
3577
3578 VPH.enqueueForPromotion(ToBePromoted);
3579 Inst = ToBePromoted;
3580 }
3581 return false;
3582}
3583
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003584bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003585 if (PHINode *P = dyn_cast<PHINode>(I)) {
3586 // It is possible for very late stage optimizations (such as SimplifyCFG)
3587 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3588 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00003589 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00003590 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003591 P->replaceAllUsesWith(V);
3592 P->eraseFromParent();
3593 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00003594 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003595 }
Chris Lattneree588de2011-01-15 07:29:01 +00003596 return false;
3597 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003598
Chris Lattneree588de2011-01-15 07:29:01 +00003599 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003600 // If the source of the cast is a constant, then this should have
3601 // already been constant folded. The only reason NOT to constant fold
3602 // it is if something (e.g. LSR) was careful to place the constant
3603 // evaluation in a block other than then one that uses it (e.g. to hoist
3604 // the address of globals out of a loop). If this is the case, we don't
3605 // want to forward-subst the cast.
3606 if (isa<Constant>(CI->getOperand(0)))
3607 return false;
3608
Chris Lattneree588de2011-01-15 07:29:01 +00003609 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3610 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003611
Chris Lattneree588de2011-01-15 07:29:01 +00003612 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00003613 /// Sink a zext or sext into its user blocks if the target type doesn't
3614 /// fit in one register
3615 if (TLI && TLI->getTypeAction(CI->getContext(),
3616 TLI->getValueType(CI->getType())) ==
3617 TargetLowering::TypeExpandInteger) {
3618 return SinkCast(CI);
3619 } else {
3620 bool MadeChange = MoveExtToFormExtLoad(I);
3621 return MadeChange | OptimizeExtUses(I);
3622 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003623 }
Chris Lattneree588de2011-01-15 07:29:01 +00003624 return false;
3625 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003626
Chris Lattneree588de2011-01-15 07:29:01 +00003627 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00003628 if (!TLI || !TLI->hasMultipleConditionRegisters())
3629 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00003630
Chris Lattneree588de2011-01-15 07:29:01 +00003631 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003632 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00003633 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3634 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00003635 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003636
Chris Lattneree588de2011-01-15 07:29:01 +00003637 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003638 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00003639 return OptimizeMemoryInst(I, SI->getOperand(1),
3640 SI->getOperand(0)->getType());
3641 return false;
3642 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003643
Yi Jiangd069f632014-04-21 19:34:27 +00003644 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3645
3646 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3647 BinOp->getOpcode() == Instruction::LShr)) {
3648 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3649 if (TLI && CI && TLI->hasExtractBitsInsn())
3650 return OptimizeExtractBits(BinOp, CI, *TLI);
3651
3652 return false;
3653 }
3654
Chris Lattneree588de2011-01-15 07:29:01 +00003655 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003656 if (GEPI->hasAllZeroIndices()) {
3657 /// The GEP operand must be a pointer, so must its result -> BitCast
3658 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3659 GEPI->getName(), GEPI);
3660 GEPI->replaceAllUsesWith(NC);
3661 GEPI->eraseFromParent();
3662 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003663 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00003664 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003665 }
Chris Lattneree588de2011-01-15 07:29:01 +00003666 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003667 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003668
Chris Lattneree588de2011-01-15 07:29:01 +00003669 if (CallInst *CI = dyn_cast<CallInst>(I))
3670 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003671
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003672 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3673 return OptimizeSelectInst(SI);
3674
Tim Northoveraeb8e062014-02-19 10:02:43 +00003675 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3676 return OptimizeShuffleVectorInst(SVI);
3677
Quentin Colombetc32615d2014-10-31 17:52:53 +00003678 if (isa<ExtractElementInst>(I))
3679 return OptimizeExtractElementInst(I);
3680
Chris Lattneree588de2011-01-15 07:29:01 +00003681 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003682}
3683
Chris Lattnerf2836d12007-03-31 04:06:36 +00003684// In this pass we look for GEP and cast instructions that are used
3685// across basic blocks and rewrite them to improve basic-block-at-a-time
3686// selection.
3687bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00003688 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00003689 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00003690
Chris Lattner7a277142011-01-15 07:14:54 +00003691 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00003692 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00003693 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003694
Benjamin Kramer455fa352012-11-23 19:17:06 +00003695 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3696
Chris Lattnerf2836d12007-03-31 04:06:36 +00003697 return MadeChange;
3698}
Devang Patel53771ba2011-08-18 00:50:51 +00003699
3700// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00003701// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00003702// find a node corresponding to the value.
3703bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3704 bool MadeChange = false;
3705 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
Craig Topperc0196b12014-04-14 00:51:57 +00003706 Instruction *PrevNonDbgInst = nullptr;
Devang Patel53771ba2011-08-18 00:50:51 +00003707 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3708 Instruction *Insn = BI; ++BI;
3709 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00003710 // Leave dbg.values that refer to an alloca alone. These
3711 // instrinsics describe the address of a variable (= the alloca)
3712 // being taken. They should not be moved next to the alloca
3713 // (and to the beginning of the scope), but rather stay close to
3714 // where said address is used.
3715 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00003716 PrevNonDbgInst = Insn;
3717 continue;
3718 }
3719
3720 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3721 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3722 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3723 DVI->removeFromParent();
3724 if (isa<PHINode>(VI))
3725 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3726 else
3727 DVI->insertAfter(VI);
3728 MadeChange = true;
3729 ++NumDbgValueMoved;
3730 }
3731 }
3732 }
3733 return MadeChange;
3734}
Tim Northovercea0abb2014-03-29 08:22:29 +00003735
3736// If there is a sequence that branches based on comparing a single bit
3737// against zero that can be combined into a single instruction, and the
3738// target supports folding these into a single instruction, sink the
3739// mask and compare into the branch uses. Do this before OptimizeBlock ->
3740// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3741// searched for.
3742bool CodeGenPrepare::sinkAndCmp(Function &F) {
3743 if (!EnableAndCmpSinking)
3744 return false;
3745 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3746 return false;
3747 bool MadeChange = false;
3748 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3749 BasicBlock *BB = I++;
3750
3751 // Does this BB end with the following?
3752 // %andVal = and %val, #single-bit-set
3753 // %icmpVal = icmp %andResult, 0
3754 // br i1 %cmpVal label %dest1, label %dest2"
3755 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3756 if (!Brcc || !Brcc->isConditional())
3757 continue;
3758 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3759 if (!Cmp || Cmp->getParent() != BB)
3760 continue;
3761 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3762 if (!Zero || !Zero->isZero())
3763 continue;
3764 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3765 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3766 continue;
3767 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3768 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3769 continue;
3770 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3771
3772 // Push the "and; icmp" for any users that are conditional branches.
3773 // Since there can only be one branch use per BB, we don't need to keep
3774 // track of which BBs we insert into.
3775 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3776 UI != E; ) {
3777 Use &TheUse = *UI;
3778 // Find brcc use.
3779 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3780 ++UI;
3781 if (!BrccUser || !BrccUser->isConditional())
3782 continue;
3783 BasicBlock *UserBB = BrccUser->getParent();
3784 if (UserBB == BB) continue;
3785 DEBUG(dbgs() << "found Brcc use\n");
3786
3787 // Sink the "and; icmp" to use.
3788 MadeChange = true;
3789 BinaryOperator *NewAnd =
3790 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3791 BrccUser);
3792 CmpInst *NewCmp =
3793 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3794 "", BrccUser);
3795 TheUse = NewCmp;
3796 ++NumAndCmpsMoved;
3797 DEBUG(BrccUser->getParent()->dump());
3798 }
3799 }
3800 return MadeChange;
3801}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00003802
3803/// \brief Scale down both weights to fit into uint32_t.
3804static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
3805 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
3806 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
3807 NewTrue = NewTrue / Scale;
3808 NewFalse = NewFalse / Scale;
3809}
3810
3811/// \brief Some targets prefer to split a conditional branch like:
3812/// \code
3813/// %0 = icmp ne i32 %a, 0
3814/// %1 = icmp ne i32 %b, 0
3815/// %or.cond = or i1 %0, %1
3816/// br i1 %or.cond, label %TrueBB, label %FalseBB
3817/// \endcode
3818/// into multiple branch instructions like:
3819/// \code
3820/// bb1:
3821/// %0 = icmp ne i32 %a, 0
3822/// br i1 %0, label %TrueBB, label %bb2
3823/// bb2:
3824/// %1 = icmp ne i32 %b, 0
3825/// br i1 %1, label %TrueBB, label %FalseBB
3826/// \endcode
3827/// This usually allows instruction selection to do even further optimizations
3828/// and combine the compare with the branch instruction. Currently this is
3829/// applied for targets which have "cheap" jump instructions.
3830///
3831/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
3832///
3833bool CodeGenPrepare::splitBranchCondition(Function &F) {
3834 if (!TM || TM->Options.EnableFastISel != true ||
3835 !TLI || TLI->isJumpExpensive())
3836 return false;
3837
3838 bool MadeChange = false;
3839 for (auto &BB : F) {
3840 // Does this BB end with the following?
3841 // %cond1 = icmp|fcmp|binary instruction ...
3842 // %cond2 = icmp|fcmp|binary instruction ...
3843 // %cond.or = or|and i1 %cond1, cond2
3844 // br i1 %cond.or label %dest1, label %dest2"
3845 BinaryOperator *LogicOp;
3846 BasicBlock *TBB, *FBB;
3847 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
3848 continue;
3849
3850 unsigned Opc;
3851 Instruction *Cond1, *Cond2;
3852 if (match(LogicOp, m_And(m_OneUse(m_Instruction(Cond1)),
3853 m_OneUse(m_Instruction(Cond2)))))
3854 Opc = Instruction::And;
3855 else if (match(LogicOp, m_Or(m_OneUse(m_Instruction(Cond1)),
3856 m_OneUse(m_Instruction(Cond2)))))
3857 Opc = Instruction::Or;
3858 else
3859 continue;
3860
3861 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
3862 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
3863 continue;
3864
3865 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
3866
3867 // Create a new BB.
3868 auto *InsertBefore = std::next(Function::iterator(BB))
3869 .getNodePtrUnchecked();
3870 auto TmpBB = BasicBlock::Create(BB.getContext(),
3871 BB.getName() + ".cond.split",
3872 BB.getParent(), InsertBefore);
3873
3874 // Update original basic block by using the first condition directly by the
3875 // branch instruction and removing the no longer needed and/or instruction.
3876 auto *Br1 = cast<BranchInst>(BB.getTerminator());
3877 Br1->setCondition(Cond1);
3878 LogicOp->eraseFromParent();
3879 Cond2->removeFromParent();
3880 // Depending on the conditon we have to either replace the true or the false
3881 // successor of the original branch instruction.
3882 if (Opc == Instruction::And)
3883 Br1->setSuccessor(0, TmpBB);
3884 else
3885 Br1->setSuccessor(1, TmpBB);
3886
3887 // Fill in the new basic block.
3888 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
3889 Cond2->insertBefore(Br2);
3890
3891 // Update PHI nodes in both successors. The original BB needs to be
3892 // replaced in one succesor's PHI nodes, because the branch comes now from
3893 // the newly generated BB (NewBB). In the other successor we need to add one
3894 // incoming edge to the PHI nodes, because both branch instructions target
3895 // now the same successor. Depending on the original branch condition
3896 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
3897 // we perfrom the correct update for the PHI nodes.
3898 // This doesn't change the successor order of the just created branch
3899 // instruction (or any other instruction).
3900 if (Opc == Instruction::Or)
3901 std::swap(TBB, FBB);
3902
3903 // Replace the old BB with the new BB.
3904 for (auto &I : *TBB) {
3905 PHINode *PN = dyn_cast<PHINode>(&I);
3906 if (!PN)
3907 break;
3908 int i;
3909 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
3910 PN->setIncomingBlock(i, TmpBB);
3911 }
3912
3913 // Add another incoming edge form the new BB.
3914 for (auto &I : *FBB) {
3915 PHINode *PN = dyn_cast<PHINode>(&I);
3916 if (!PN)
3917 break;
3918 auto *Val = PN->getIncomingValueForBlock(&BB);
3919 PN->addIncoming(Val, TmpBB);
3920 }
3921
3922 // Update the branch weights (from SelectionDAGBuilder::
3923 // FindMergedConditions).
3924 if (Opc == Instruction::Or) {
3925 // Codegen X | Y as:
3926 // BB1:
3927 // jmp_if_X TBB
3928 // jmp TmpBB
3929 // TmpBB:
3930 // jmp_if_Y TBB
3931 // jmp FBB
3932 //
3933
3934 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
3935 // The requirement is that
3936 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
3937 // = TrueProb for orignal BB.
3938 // Assuming the orignal weights are A and B, one choice is to set BB1's
3939 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
3940 // assumes that
3941 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
3942 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
3943 // TmpBB, but the math is more complicated.
3944 uint64_t TrueWeight, FalseWeight;
3945 if (Br1->getBranchWeights(TrueWeight, FalseWeight)) {
3946 uint64_t NewTrueWeight = TrueWeight;
3947 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
3948 scaleWeights(NewTrueWeight, NewFalseWeight);
3949 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
3950 .createBranchWeights(TrueWeight, FalseWeight));
3951
3952 NewTrueWeight = TrueWeight;
3953 NewFalseWeight = 2 * FalseWeight;
3954 scaleWeights(NewTrueWeight, NewFalseWeight);
3955 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
3956 .createBranchWeights(TrueWeight, FalseWeight));
3957 }
3958 } else {
3959 // Codegen X & Y as:
3960 // BB1:
3961 // jmp_if_X TmpBB
3962 // jmp FBB
3963 // TmpBB:
3964 // jmp_if_Y TBB
3965 // jmp FBB
3966 //
3967 // This requires creation of TmpBB after CurBB.
3968
3969 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
3970 // The requirement is that
3971 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
3972 // = FalseProb for orignal BB.
3973 // Assuming the orignal weights are A and B, one choice is to set BB1's
3974 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
3975 // assumes that
3976 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
3977 uint64_t TrueWeight, FalseWeight;
3978 if (Br1->getBranchWeights(TrueWeight, FalseWeight)) {
3979 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
3980 uint64_t NewFalseWeight = FalseWeight;
3981 scaleWeights(NewTrueWeight, NewFalseWeight);
3982 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
3983 .createBranchWeights(TrueWeight, FalseWeight));
3984
3985 NewTrueWeight = 2 * TrueWeight;
3986 NewFalseWeight = FalseWeight;
3987 scaleWeights(NewTrueWeight, NewFalseWeight);
3988 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
3989 .createBranchWeights(TrueWeight, FalseWeight));
3990 }
3991 }
3992
3993 // Request DOM Tree update.
3994 // Note: No point in getting fancy here, since the DT info is never
3995 // available to CodeGenPrepare and the existing update code is broken
3996 // anyways.
3997 ModifiedDT = true;
3998
3999 MadeChange = true;
4000
4001 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4002 TmpBB->dump());
4003 }
4004 return MadeChange;
4005}