blob: 330dad7ef1ba03a2fb4790dc9fa63bb5fcf3c8d1 [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
16#define DEBUG_TYPE "codegenprepare"
Quentin Colombeta3490842014-02-22 00:07:45 +000017#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/InstructionSimplify.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"
Chandler Carruth820a9082014-03-04 11:08:18 +000033#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000034#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000035#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000036#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000037#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000038#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000040#include "llvm/Target/TargetLibraryInfo.h"
41#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000042#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000045#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000049
Cameron Zwarichced753f2011-01-05 17:27:27 +000050STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000051STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000053STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 "sunken Cmps");
55STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 "of sunken Casts");
57STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000059STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000062STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000063STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000064STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000065
Cameron Zwarich338d3622011-03-11 21:52:04 +000066static cl::opt<bool> DisableBranchOpts(
67 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
68 cl::desc("Disable branch optimizations in CodeGenPrepare"));
69
Benjamin Kramer3d38c172012-05-06 14:25:16 +000070static cl::opt<bool> DisableSelectToBranch(
71 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
72 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000073
Hal Finkelc3998302014-04-12 00:59:48 +000074static cl::opt<bool> AddrSinkUsingGEPs(
75 "addr-sink-using-gep", cl::Hidden, cl::init(false),
76 cl::desc("Address sinking in CGP using GEPs."));
77
Tim Northovercea0abb2014-03-29 08:22:29 +000078static cl::opt<bool> EnableAndCmpSinking(
79 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
80 cl::desc("Enable sinkinig and/cmp into branches."));
81
Eric Christopherc1ea1492008-09-24 05:32:41 +000082namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000083typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
84typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
85
Chris Lattner2dd09db2009-09-02 06:11:42 +000086 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000087 /// TLI - Keep a pointer of a TargetLowering to consult for determining
88 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +000089 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +000090 const TargetLowering *TLI;
Chad Rosierc24b86f2011-12-01 03:08:23 +000091 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +000092 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +000093
Chris Lattner7a277142011-01-15 07:14:54 +000094 /// CurInstIterator - As we scan instructions optimizing them, this is the
95 /// next instruction to optimize. Xforms that can invalidate this should
96 /// update it.
97 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +000098
Evan Cheng0663f232011-03-21 01:19:09 +000099 /// Keeps track of non-local addresses that have been sunk into a block.
100 /// This allows us to avoid inserting duplicate code for blocks with
101 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000102 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000103
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000104 /// Keeps track of all truncates inserted for the current function.
105 SetOfInstrs InsertedTruncsSet;
106 /// Keeps track of the type of the related instruction before their
107 /// promotion for the current function.
108 InstrToOrigTy PromotedInsts;
109
Devang Patel8f606d72011-03-24 15:35:25 +0000110 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000111 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000112 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000113
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000114 /// OptSize - True if optimizing for size.
115 bool OptSize;
116
Chris Lattnerf2836d12007-03-31 04:06:36 +0000117 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000118 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000119 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
120 : FunctionPass(ID), TM(TM), TLI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000121 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
122 }
Craig Topper4584cd52014-03-07 09:26:03 +0000123 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000124
Craig Topper4584cd52014-03-07 09:26:03 +0000125 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000126
Craig Topper4584cd52014-03-07 09:26:03 +0000127 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000128 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000129 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000130 }
131
Chris Lattnerf2836d12007-03-31 04:06:36 +0000132 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000133 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000134 bool EliminateMostlyEmptyBlocks(Function &F);
135 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
136 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000137 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000138 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000139 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000140 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000141 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000142 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000143 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000144 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000145 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000146 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000147 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000148 bool sinkAndCmp(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000149 };
150}
Devang Patel09f162c2007-05-01 21:15:47 +0000151
Devang Patel8c78a0b2007-05-03 01:11:54 +0000152char CodeGenPrepare::ID = 0;
Quentin Colombetdc0b2ea2014-01-16 21:44:34 +0000153static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
154 initializeTargetLibraryInfoPass(Registry);
155 PassInfo *PI = new PassInfo(
156 "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
157 PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
158 PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
159 Registry.registerPass(*PI, true);
160 return PI;
161}
162
163void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
164 CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
165}
Chris Lattnerf2836d12007-03-31 04:06:36 +0000166
Bill Wendling7a639ea2013-06-19 21:07:11 +0000167FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
168 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000169}
170
Chris Lattnerf2836d12007-03-31 04:06:36 +0000171bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000172 if (skipOptnoneFunction(F))
173 return false;
174
Chris Lattnerf2836d12007-03-31 04:06:36 +0000175 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000176 // Clear per function information.
177 InsertedTruncsSet.clear();
178 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000179
Devang Patel8f606d72011-03-24 15:35:25 +0000180 ModifiedDT = false;
Bill Wendling7a639ea2013-06-19 21:07:11 +0000181 if (TM) TLI = TM->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000182 TLInfo = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000183 DominatorTreeWrapperPass *DTWP =
184 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000185 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Bill Wendling698e84f2012-12-30 10:32:01 +0000186 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
187 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000188
Preston Gurdcdf540d2012-09-04 18:22:17 +0000189 /// This optimization identifies DIV instructions that can be
190 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000191 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000192 const DenseMap<unsigned int, unsigned int> &BypassWidths =
193 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000194 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000195 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000196 }
197
198 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000199 // unconditional branch.
200 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000201
Devang Patel53771ba2011-08-18 00:50:51 +0000202 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000203 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000204 // find a node corresponding to the value.
205 EverMadeChange |= PlaceDbgValues(F);
206
Tim Northovercea0abb2014-03-29 08:22:29 +0000207 // If there is a mask, compare against zero, and branch that can be combined
208 // into a single target instruction, push the mask and compare into branch
209 // users. Do this before OptimizeBlock -> OptimizeInst ->
210 // OptimizeCmpExpression, which perturbs the pattern being searched for.
211 if (!DisableBranchOpts)
212 EverMadeChange |= sinkAndCmp(F);
213
Chris Lattnerc3748562007-04-02 01:35:34 +0000214 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000215 while (MadeChange) {
216 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000217 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000218 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000219 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000220 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000221 EverMadeChange |= MadeChange;
222 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000223
224 SunkAddrs.clear();
225
Cameron Zwarich338d3622011-03-11 21:52:04 +0000226 if (!DisableBranchOpts) {
227 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000228 SmallPtrSet<BasicBlock*, 8> WorkList;
229 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
230 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000231 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000232 if (!MadeChange) continue;
233
234 for (SmallVectorImpl<BasicBlock*>::iterator
235 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
236 if (pred_begin(*II) == pred_end(*II))
237 WorkList.insert(*II);
238 }
239
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000240 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000241 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000242 while (!WorkList.empty()) {
243 BasicBlock *BB = *WorkList.begin();
244 WorkList.erase(BB);
245 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
246
247 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000248
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000249 for (SmallVectorImpl<BasicBlock*>::iterator
250 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
251 if (pred_begin(*II) == pred_end(*II))
252 WorkList.insert(*II);
253 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000254
Nadav Rotem70409992012-08-14 05:19:07 +0000255 // Merge pairs of basic blocks with unconditional branches, connected by
256 // a single edge.
257 if (EverMadeChange || MadeChange)
258 MadeChange |= EliminateFallThrough(F);
259
Evan Cheng0663f232011-03-21 01:19:09 +0000260 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000261 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000262 EverMadeChange |= MadeChange;
263 }
264
Devang Patel8f606d72011-03-24 15:35:25 +0000265 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000266 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000267
Chris Lattnerf2836d12007-03-31 04:06:36 +0000268 return EverMadeChange;
269}
270
Nadav Rotem70409992012-08-14 05:19:07 +0000271/// EliminateFallThrough - Merge basic blocks which are connected
272/// by a single edge, where one of the basic blocks has a single successor
273/// pointing to the other basic block, which has a single predecessor.
274bool CodeGenPrepare::EliminateFallThrough(Function &F) {
275 bool Changed = false;
276 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000277 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000278 BasicBlock *BB = I++;
279 // If the destination block has a single pred, then this is a trivial
280 // edge, just collapse it.
281 BasicBlock *SinglePred = BB->getSinglePredecessor();
282
Evan Cheng64a223a2012-09-28 23:58:57 +0000283 // Don't merge if BB's address is taken.
284 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000285
286 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
287 if (Term && !Term->isConditional()) {
288 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000289 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000290 // Remember if SinglePred was the entry block of the function.
291 // If so, we will need to move BB back to the entry position.
292 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
293 MergeBasicBlockIntoOnlyPred(BB, this);
294
295 if (isEntry && BB != &BB->getParent()->getEntryBlock())
296 BB->moveBefore(&BB->getParent()->getEntryBlock());
297
298 // We have erased a block. Update the iterator.
299 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000300 }
301 }
302 return Changed;
303}
304
Dale Johannesen4026b042009-03-27 01:13:37 +0000305/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
306/// debug info directives, and an unconditional branch. Passes before isel
307/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
308/// isel. Start by eliminating these blocks so we can split them the way we
309/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000310bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
311 bool MadeChange = false;
312 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000313 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000314 BasicBlock *BB = I++;
315
316 // If this block doesn't end with an uncond branch, ignore it.
317 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
318 if (!BI || !BI->isUnconditional())
319 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000320
Dale Johannesen4026b042009-03-27 01:13:37 +0000321 // If the instruction before the branch (skipping debug info) isn't a phi
322 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000323 BasicBlock::iterator BBI = BI;
324 if (BBI != BB->begin()) {
325 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000326 while (isa<DbgInfoIntrinsic>(BBI)) {
327 if (BBI == BB->begin())
328 break;
329 --BBI;
330 }
331 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
332 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000333 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000334
Chris Lattnerc3748562007-04-02 01:35:34 +0000335 // Do not break infinite loops.
336 BasicBlock *DestBB = BI->getSuccessor(0);
337 if (DestBB == BB)
338 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000339
Chris Lattnerc3748562007-04-02 01:35:34 +0000340 if (!CanMergeBlocks(BB, DestBB))
341 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000342
Chris Lattnerc3748562007-04-02 01:35:34 +0000343 EliminateMostlyEmptyBlock(BB);
344 MadeChange = true;
345 }
346 return MadeChange;
347}
348
349/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
350/// single uncond branch between them, and BB contains no other non-phi
351/// instructions.
352bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
353 const BasicBlock *DestBB) const {
354 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
355 // the successor. If there are more complex condition (e.g. preheaders),
356 // don't mess around with them.
357 BasicBlock::const_iterator BBI = BB->begin();
358 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000359 for (const User *U : PN->users()) {
360 const Instruction *UI = cast<Instruction>(U);
361 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000362 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000363 // If User is inside DestBB block and it is a PHINode then check
364 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000365 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000366 if (UI->getParent() == DestBB) {
367 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000368 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
369 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
370 if (Insn && Insn->getParent() == BB &&
371 Insn->getParent() != UPN->getIncomingBlock(I))
372 return false;
373 }
374 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 }
376 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000377
Chris Lattnerc3748562007-04-02 01:35:34 +0000378 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
379 // and DestBB may have conflicting incoming values for the block. If so, we
380 // can't merge the block.
381 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
382 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000383
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000385 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
387 // It is faster to get preds from a PHI than with pred_iterator.
388 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
389 BBPreds.insert(BBPN->getIncomingBlock(i));
390 } else {
391 BBPreds.insert(pred_begin(BB), pred_end(BB));
392 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000393
Chris Lattnerc3748562007-04-02 01:35:34 +0000394 // Walk the preds of DestBB.
395 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
396 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
397 if (BBPreds.count(Pred)) { // Common predecessor?
398 BBI = DestBB->begin();
399 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
400 const Value *V1 = PN->getIncomingValueForBlock(Pred);
401 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000402
Chris Lattnerc3748562007-04-02 01:35:34 +0000403 // If V2 is a phi node in BB, look up what the mapped value will be.
404 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
405 if (V2PN->getParent() == BB)
406 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000407
Chris Lattnerc3748562007-04-02 01:35:34 +0000408 // If there is a conflict, bail out.
409 if (V1 != V2) return false;
410 }
411 }
412 }
413
414 return true;
415}
416
417
418/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
419/// an unconditional branch in it.
420void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
421 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
422 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000423
David Greene74e2d492010-01-05 01:27:11 +0000424 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000425
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 // If the destination block has a single pred, then this is a trivial edge,
427 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000428 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000429 if (SinglePred != DestBB) {
430 // Remember if SinglePred was the entry block of the function. If so, we
431 // will need to move BB back to the entry position.
432 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000433 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000434
Chris Lattner8a172da2008-11-28 19:54:49 +0000435 if (isEntry && BB != &BB->getParent()->getEntryBlock())
436 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000437
David Greene74e2d492010-01-05 01:27:11 +0000438 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000439 return;
440 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000441 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442
Chris Lattnerc3748562007-04-02 01:35:34 +0000443 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
444 // to handle the new incoming edges it is about to have.
445 PHINode *PN;
446 for (BasicBlock::iterator BBI = DestBB->begin();
447 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
448 // Remove the incoming value for BB, and remember it.
449 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000450
Chris Lattnerc3748562007-04-02 01:35:34 +0000451 // Two options: either the InVal is a phi node defined in BB or it is some
452 // value that dominates BB.
453 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
454 if (InValPhi && InValPhi->getParent() == BB) {
455 // Add all of the input values of the input PHI as inputs of this phi.
456 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
457 PN->addIncoming(InValPhi->getIncomingValue(i),
458 InValPhi->getIncomingBlock(i));
459 } else {
460 // Otherwise, add one instance of the dominating value for each edge that
461 // we will be adding.
462 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
463 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
464 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
465 } else {
466 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
467 PN->addIncoming(InVal, *PI);
468 }
469 }
470 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000471
Chris Lattnerc3748562007-04-02 01:35:34 +0000472 // The PHIs are now updated, change everything that refers to BB to use
473 // DestBB and remove BB.
474 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000475 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000476 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
477 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
478 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
479 DT->changeImmediateDominator(DestBB, NewIDom);
480 DT->eraseNode(BB);
481 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000482 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000483 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000484
David Greene74e2d492010-01-05 01:27:11 +0000485 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000486}
487
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000488/// SinkCast - Sink the specified cast instruction into its user blocks
489static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000490 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000491
Chris Lattnerf2836d12007-03-31 04:06:36 +0000492 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000493 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000494
Chris Lattnerf2836d12007-03-31 04:06:36 +0000495 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000496 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000497 UI != E; ) {
498 Use &TheUse = UI.getUse();
499 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000500
Chris Lattnerf2836d12007-03-31 04:06:36 +0000501 // Figure out which BB this cast is used in. For PHI's this is the
502 // appropriate predecessor block.
503 BasicBlock *UserBB = User->getParent();
504 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000505 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000506 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000507
Chris Lattnerf2836d12007-03-31 04:06:36 +0000508 // Preincrement use iterator so we don't invalidate it.
509 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000510
Chris Lattnerf2836d12007-03-31 04:06:36 +0000511 // If this user is in the same block as the cast, don't change the cast.
512 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000513
Chris Lattnerf2836d12007-03-31 04:06:36 +0000514 // If we have already inserted a cast into this block, use it.
515 CastInst *&InsertedCast = InsertedCasts[UserBB];
516
517 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000518 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000519 InsertedCast =
520 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000521 InsertPt);
522 MadeChange = true;
523 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000524
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000525 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000526 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000527 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000528 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000529
Chris Lattnerf2836d12007-03-31 04:06:36 +0000530 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000531 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000532 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000533 MadeChange = true;
534 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000535
Chris Lattnerf2836d12007-03-31 04:06:36 +0000536 return MadeChange;
537}
538
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000539/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
540/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
541/// sink it into user blocks to reduce the number of virtual
542/// registers that must be created and coalesced.
543///
544/// Return true if any changes are made.
545///
546static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
547 // If this is a noop copy,
548 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
549 EVT DstVT = TLI.getValueType(CI->getType());
550
551 // This is an fp<->int conversion?
552 if (SrcVT.isInteger() != DstVT.isInteger())
553 return false;
554
555 // If this is an extension, it will be a zero or sign extension, which
556 // isn't a noop.
557 if (SrcVT.bitsLT(DstVT)) return false;
558
559 // If these values will be promoted, find out what they will be promoted
560 // to. This helps us consider truncates on PPC as noop copies when they
561 // are.
562 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
563 TargetLowering::TypePromoteInteger)
564 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
565 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
566 TargetLowering::TypePromoteInteger)
567 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
568
569 // If, after promotion, these are the same types, this is a noop copy.
570 if (SrcVT != DstVT)
571 return false;
572
573 return SinkCast(CI);
574}
575
Eric Christopherc1ea1492008-09-24 05:32:41 +0000576/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000577/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000578/// a clear win except on targets with multiple condition code registers
579/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000580///
581/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000582static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000583 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000584
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000585 /// InsertedCmp - Only insert a cmp in each block once.
586 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000587
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000588 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000589 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000590 UI != E; ) {
591 Use &TheUse = UI.getUse();
592 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000593
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000594 // Preincrement use iterator so we don't invalidate it.
595 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000596
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000597 // Don't bother for PHI nodes.
598 if (isa<PHINode>(User))
599 continue;
600
601 // Figure out which BB this cmp is used in.
602 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000603
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000604 // If this user is in the same block as the cmp, don't change the cmp.
605 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000606
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000607 // If we have already inserted a cmp into this block, use it.
608 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
609
610 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000611 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000612 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000613 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000614 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000615 CI->getOperand(1), "", InsertPt);
616 MadeChange = true;
617 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000618
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000619 // Replace a use of the cmp with a use of the new cmp.
620 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000621 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000622 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000623
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000624 // If we removed all uses, nuke the cmp.
625 if (CI->use_empty())
626 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000627
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000628 return MadeChange;
629}
630
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000631namespace {
632class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
633protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000634 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000635 CI->replaceAllUsesWith(With);
636 CI->eraseFromParent();
637 }
Craig Topper4584cd52014-03-07 09:26:03 +0000638 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000639 if (ConstantInt *SizeCI =
640 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
641 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000642 return false;
643 }
644};
645} // end anonymous namespace
646
Eric Christopher4b7948e2010-03-11 02:41:03 +0000647bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000648 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000649
Chris Lattner7a277142011-01-15 07:14:54 +0000650 // Lower inline assembly if we can.
651 // If we found an inline asm expession, and if the target knows how to
652 // lower it to normal LLVM code, do so now.
653 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
654 if (TLI->ExpandInlineAsm(CI)) {
655 // Avoid invalidating the iterator.
656 CurInstIterator = BB->begin();
657 // Avoid processing instructions out of order, which could cause
658 // reuse before a value is defined.
659 SunkAddrs.clear();
660 return true;
661 }
662 // Sink address computing for memory operands into the block.
663 if (OptimizeInlineAsmInst(CI))
664 return true;
665 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000666
Eric Christopher4b7948e2010-03-11 02:41:03 +0000667 // Lower all uses of llvm.objectsize.*
668 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
669 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000670 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000671 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000672 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
673
Chris Lattner1b93be52011-01-15 07:25:29 +0000674 // Substituting this can cause recursive simplifications, which can
675 // invalidate our iterator. Use a WeakVH to hold onto it in case this
676 // happens.
677 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000678
Craig Topperc0196b12014-04-14 00:51:57 +0000679 replaceAndRecursivelySimplify(CI, RetVal,
680 TLI ? TLI->getDataLayout() : nullptr,
681 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000682
683 // If the iterator instruction was recursively deleted, start over at the
684 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000685 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000686 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000687 SunkAddrs.clear();
688 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000689 return true;
690 }
691
Pete Cooper615fd892012-03-13 20:59:56 +0000692 if (II && TLI) {
693 SmallVector<Value*, 2> PtrOps;
694 Type *AccessTy;
695 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
696 while (!PtrOps.empty())
697 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
698 return true;
699 }
700
Eric Christopher4b7948e2010-03-11 02:41:03 +0000701 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +0000702 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000703
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000704 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +0000705 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000706 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000707
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000708 // Lower all default uses of _chk calls. This is very similar
709 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000710 // that have the default "don't know" as the objectsize. Anything else
711 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000712 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000713 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000714}
Chris Lattner1b93be52011-01-15 07:25:29 +0000715
Evan Cheng0663f232011-03-21 01:19:09 +0000716/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
717/// instructions to the predecessor to enable tail call optimizations. The
718/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000719/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000720/// bb0:
721/// %tmp0 = tail call i32 @f0()
722/// br label %return
723/// bb1:
724/// %tmp1 = tail call i32 @f1()
725/// br label %return
726/// bb2:
727/// %tmp2 = tail call i32 @f2()
728/// br label %return
729/// return:
730/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
731/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000732/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000733///
734/// =>
735///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000736/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000737/// bb0:
738/// %tmp0 = tail call i32 @f0()
739/// ret i32 %tmp0
740/// bb1:
741/// %tmp1 = tail call i32 @f1()
742/// ret i32 %tmp1
743/// bb2:
744/// %tmp2 = tail call i32 @f2()
745/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000746/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000747bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000748 if (!TLI)
749 return false;
750
Benjamin Kramer455fa352012-11-23 19:17:06 +0000751 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
752 if (!RI)
753 return false;
754
Craig Topperc0196b12014-04-14 00:51:57 +0000755 PHINode *PN = nullptr;
756 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +0000757 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000758 if (V) {
759 BCI = dyn_cast<BitCastInst>(V);
760 if (BCI)
761 V = BCI->getOperand(0);
762
763 PN = dyn_cast<PHINode>(V);
764 if (!PN)
765 return false;
766 }
Evan Cheng0663f232011-03-21 01:19:09 +0000767
Cameron Zwarich4649f172011-03-24 04:52:10 +0000768 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000769 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000770
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000771 // It's not safe to eliminate the sign / zero extension of the return value.
772 // See llvm::isInTailCallPosition().
773 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000774 AttributeSet CallerAttrs = F->getAttributes();
775 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
776 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000777 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000778
Cameron Zwarich4649f172011-03-24 04:52:10 +0000779 // Make sure there are no instructions between the PHI and return, or that the
780 // return is the first instruction in the block.
781 if (PN) {
782 BasicBlock::iterator BI = BB->begin();
783 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000784 if (&*BI == BCI)
785 // Also skip over the bitcast.
786 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000787 if (&*BI != RI)
788 return false;
789 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000790 BasicBlock::iterator BI = BB->begin();
791 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
792 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000793 return false;
794 }
Evan Cheng0663f232011-03-21 01:19:09 +0000795
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000796 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
797 /// call.
798 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000799 if (PN) {
800 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
801 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
802 // Make sure the phi value is indeed produced by the tail call.
803 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
804 TLI->mayBeEmittedAsTailCall(CI))
805 TailCalls.push_back(CI);
806 }
807 } else {
808 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
809 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
810 if (!VisitedBBs.insert(*PI))
811 continue;
812
813 BasicBlock::InstListType &InstList = (*PI)->getInstList();
814 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
815 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000816 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
817 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000818 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000819
Cameron Zwarich4649f172011-03-24 04:52:10 +0000820 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +0000821 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000822 TailCalls.push_back(CI);
823 }
Evan Cheng0663f232011-03-21 01:19:09 +0000824 }
825
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000826 bool Changed = false;
827 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
828 CallInst *CI = TailCalls[i];
829 CallSite CS(CI);
830
831 // Conservatively require the attributes of the call to match those of the
832 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +0000833 AttributeSet CalleeAttrs = CS.getAttributes();
834 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000835 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +0000836 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000837 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000838 continue;
839
840 // Make sure the call instruction is followed by an unconditional branch to
841 // the return block.
842 BasicBlock *CallBB = CI->getParent();
843 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
844 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
845 continue;
846
847 // Duplicate the return into CallBB.
848 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000849 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000850 ++NumRetsDup;
851 }
852
853 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +0000854 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000855 BB->eraseFromParent();
856
857 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +0000858}
859
Chris Lattner728f9022008-11-25 07:09:13 +0000860//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +0000861// Memory Optimization
862//===----------------------------------------------------------------------===//
863
Chandler Carruthc8925912013-01-05 02:09:22 +0000864namespace {
865
866/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
867/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +0000868struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +0000869 Value *BaseReg;
870 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +0000871 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +0000872 void print(raw_ostream &OS) const;
873 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +0000874
Chandler Carruthc8925912013-01-05 02:09:22 +0000875 bool operator==(const ExtAddrMode& O) const {
876 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
877 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
878 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
879 }
880};
881
Eli Friedmanc1f1f852013-09-10 23:09:24 +0000882#ifndef NDEBUG
883static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
884 AM.print(OS);
885 return OS;
886}
887#endif
888
Chandler Carruthc8925912013-01-05 02:09:22 +0000889void ExtAddrMode::print(raw_ostream &OS) const {
890 bool NeedPlus = false;
891 OS << "[";
892 if (BaseGV) {
893 OS << (NeedPlus ? " + " : "")
894 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000895 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000896 NeedPlus = true;
897 }
898
899 if (BaseOffs)
900 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
901
902 if (BaseReg) {
903 OS << (NeedPlus ? " + " : "")
904 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000905 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000906 NeedPlus = true;
907 }
908 if (Scale) {
909 OS << (NeedPlus ? " + " : "")
910 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000911 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000912 }
913
914 OS << ']';
915}
916
917#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
918void ExtAddrMode::dump() const {
919 print(dbgs());
920 dbgs() << '\n';
921}
922#endif
923
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000924/// \brief This class provides transaction based operation on the IR.
925/// Every change made through this class is recorded in the internal state and
926/// can be undone (rollback) until commit is called.
927class TypePromotionTransaction {
928
929 /// \brief This represents the common interface of the individual transaction.
930 /// Each class implements the logic for doing one specific modification on
931 /// the IR via the TypePromotionTransaction.
932 class TypePromotionAction {
933 protected:
934 /// The Instruction modified.
935 Instruction *Inst;
936
937 public:
938 /// \brief Constructor of the action.
939 /// The constructor performs the related action on the IR.
940 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
941
942 virtual ~TypePromotionAction() {}
943
944 /// \brief Undo the modification done by this action.
945 /// When this method is called, the IR must be in the same state as it was
946 /// before this action was applied.
947 /// \pre Undoing the action works if and only if the IR is in the exact same
948 /// state as it was directly after this action was applied.
949 virtual void undo() = 0;
950
951 /// \brief Advocate every change made by this action.
952 /// When the results on the IR of the action are to be kept, it is important
953 /// to call this function, otherwise hidden information may be kept forever.
954 virtual void commit() {
955 // Nothing to be done, this action is not doing anything.
956 }
957 };
958
959 /// \brief Utility to remember the position of an instruction.
960 class InsertionHandler {
961 /// Position of an instruction.
962 /// Either an instruction:
963 /// - Is the first in a basic block: BB is used.
964 /// - Has a previous instructon: PrevInst is used.
965 union {
966 Instruction *PrevInst;
967 BasicBlock *BB;
968 } Point;
969 /// Remember whether or not the instruction had a previous instruction.
970 bool HasPrevInstruction;
971
972 public:
973 /// \brief Record the position of \p Inst.
974 InsertionHandler(Instruction *Inst) {
975 BasicBlock::iterator It = Inst;
976 HasPrevInstruction = (It != (Inst->getParent()->begin()));
977 if (HasPrevInstruction)
978 Point.PrevInst = --It;
979 else
980 Point.BB = Inst->getParent();
981 }
982
983 /// \brief Insert \p Inst at the recorded position.
984 void insert(Instruction *Inst) {
985 if (HasPrevInstruction) {
986 if (Inst->getParent())
987 Inst->removeFromParent();
988 Inst->insertAfter(Point.PrevInst);
989 } else {
990 Instruction *Position = Point.BB->getFirstInsertionPt();
991 if (Inst->getParent())
992 Inst->moveBefore(Position);
993 else
994 Inst->insertBefore(Position);
995 }
996 }
997 };
998
999 /// \brief Move an instruction before another.
1000 class InstructionMoveBefore : public TypePromotionAction {
1001 /// Original position of the instruction.
1002 InsertionHandler Position;
1003
1004 public:
1005 /// \brief Move \p Inst before \p Before.
1006 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1007 : TypePromotionAction(Inst), Position(Inst) {
1008 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1009 Inst->moveBefore(Before);
1010 }
1011
1012 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001013 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001014 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1015 Position.insert(Inst);
1016 }
1017 };
1018
1019 /// \brief Set the operand of an instruction with a new value.
1020 class OperandSetter : public TypePromotionAction {
1021 /// Original operand of the instruction.
1022 Value *Origin;
1023 /// Index of the modified instruction.
1024 unsigned Idx;
1025
1026 public:
1027 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1028 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1029 : TypePromotionAction(Inst), Idx(Idx) {
1030 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1031 << "for:" << *Inst << "\n"
1032 << "with:" << *NewVal << "\n");
1033 Origin = Inst->getOperand(Idx);
1034 Inst->setOperand(Idx, NewVal);
1035 }
1036
1037 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001038 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001039 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1040 << "for: " << *Inst << "\n"
1041 << "with: " << *Origin << "\n");
1042 Inst->setOperand(Idx, Origin);
1043 }
1044 };
1045
1046 /// \brief Hide the operands of an instruction.
1047 /// Do as if this instruction was not using any of its operands.
1048 class OperandsHider : public TypePromotionAction {
1049 /// The list of original operands.
1050 SmallVector<Value *, 4> OriginalValues;
1051
1052 public:
1053 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1054 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1055 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1056 unsigned NumOpnds = Inst->getNumOperands();
1057 OriginalValues.reserve(NumOpnds);
1058 for (unsigned It = 0; It < NumOpnds; ++It) {
1059 // Save the current operand.
1060 Value *Val = Inst->getOperand(It);
1061 OriginalValues.push_back(Val);
1062 // Set a dummy one.
1063 // We could use OperandSetter here, but that would implied an overhead
1064 // that we are not willing to pay.
1065 Inst->setOperand(It, UndefValue::get(Val->getType()));
1066 }
1067 }
1068
1069 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001070 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001071 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1072 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1073 Inst->setOperand(It, OriginalValues[It]);
1074 }
1075 };
1076
1077 /// \brief Build a truncate instruction.
1078 class TruncBuilder : public TypePromotionAction {
1079 public:
1080 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1081 /// result.
1082 /// trunc Opnd to Ty.
1083 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1084 IRBuilder<> Builder(Opnd);
1085 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1086 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1087 }
1088
1089 /// \brief Get the built instruction.
1090 Instruction *getBuiltInstruction() { return Inst; }
1091
1092 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001093 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001094 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1095 Inst->eraseFromParent();
1096 }
1097 };
1098
1099 /// \brief Build a sign extension instruction.
1100 class SExtBuilder : public TypePromotionAction {
1101 public:
1102 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1103 /// result.
1104 /// sext Opnd to Ty.
1105 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1106 : TypePromotionAction(Inst) {
1107 IRBuilder<> Builder(InsertPt);
1108 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1109 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1110 }
1111
1112 /// \brief Get the built instruction.
1113 Instruction *getBuiltInstruction() { return Inst; }
1114
1115 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001116 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001117 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1118 Inst->eraseFromParent();
1119 }
1120 };
1121
1122 /// \brief Mutate an instruction to another type.
1123 class TypeMutator : public TypePromotionAction {
1124 /// Record the original type.
1125 Type *OrigTy;
1126
1127 public:
1128 /// \brief Mutate the type of \p Inst into \p NewTy.
1129 TypeMutator(Instruction *Inst, Type *NewTy)
1130 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1131 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1132 << "\n");
1133 Inst->mutateType(NewTy);
1134 }
1135
1136 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001137 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001138 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1139 << "\n");
1140 Inst->mutateType(OrigTy);
1141 }
1142 };
1143
1144 /// \brief Replace the uses of an instruction by another instruction.
1145 class UsesReplacer : public TypePromotionAction {
1146 /// Helper structure to keep track of the replaced uses.
1147 struct InstructionAndIdx {
1148 /// The instruction using the instruction.
1149 Instruction *Inst;
1150 /// The index where this instruction is used for Inst.
1151 unsigned Idx;
1152 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1153 : Inst(Inst), Idx(Idx) {}
1154 };
1155
1156 /// Keep track of the original uses (pair Instruction, Index).
1157 SmallVector<InstructionAndIdx, 4> OriginalUses;
1158 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1159
1160 public:
1161 /// \brief Replace all the use of \p Inst by \p New.
1162 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1163 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1164 << "\n");
1165 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001166 for (Use &U : Inst->uses()) {
1167 Instruction *UserI = cast<Instruction>(U.getUser());
1168 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001169 }
1170 // Now, we can replace the uses.
1171 Inst->replaceAllUsesWith(New);
1172 }
1173
1174 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001175 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001176 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1177 for (use_iterator UseIt = OriginalUses.begin(),
1178 EndIt = OriginalUses.end();
1179 UseIt != EndIt; ++UseIt) {
1180 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1181 }
1182 }
1183 };
1184
1185 /// \brief Remove an instruction from the IR.
1186 class InstructionRemover : public TypePromotionAction {
1187 /// Original position of the instruction.
1188 InsertionHandler Inserter;
1189 /// Helper structure to hide all the link to the instruction. In other
1190 /// words, this helps to do as if the instruction was removed.
1191 OperandsHider Hider;
1192 /// Keep track of the uses replaced, if any.
1193 UsesReplacer *Replacer;
1194
1195 public:
1196 /// \brief Remove all reference of \p Inst and optinally replace all its
1197 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001198 /// \pre If !Inst->use_empty(), then New != nullptr
1199 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001200 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001201 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001202 if (New)
1203 Replacer = new UsesReplacer(Inst, New);
1204 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1205 Inst->removeFromParent();
1206 }
1207
1208 ~InstructionRemover() { delete Replacer; }
1209
1210 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001211 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001212
1213 /// \brief Resurrect the instruction and reassign it to the proper uses if
1214 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001215 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001216 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1217 Inserter.insert(Inst);
1218 if (Replacer)
1219 Replacer->undo();
1220 Hider.undo();
1221 }
1222 };
1223
1224public:
1225 /// Restoration point.
1226 /// The restoration point is a pointer to an action instead of an iterator
1227 /// because the iterator may be invalidated but not the pointer.
1228 typedef const TypePromotionAction *ConstRestorationPt;
1229 /// Advocate every changes made in that transaction.
1230 void commit();
1231 /// Undo all the changes made after the given point.
1232 void rollback(ConstRestorationPt Point);
1233 /// Get the current restoration point.
1234 ConstRestorationPt getRestorationPoint() const;
1235
1236 /// \name API for IR modification with state keeping to support rollback.
1237 /// @{
1238 /// Same as Instruction::setOperand.
1239 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1240 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001241 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001242 /// Same as Value::replaceAllUsesWith.
1243 void replaceAllUsesWith(Instruction *Inst, Value *New);
1244 /// Same as Value::mutateType.
1245 void mutateType(Instruction *Inst, Type *NewTy);
1246 /// Same as IRBuilder::createTrunc.
1247 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1248 /// Same as IRBuilder::createSExt.
1249 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1250 /// Same as Instruction::moveBefore.
1251 void moveBefore(Instruction *Inst, Instruction *Before);
1252 /// @}
1253
1254 ~TypePromotionTransaction();
1255
1256private:
1257 /// The ordered list of actions made so far.
1258 SmallVector<TypePromotionAction *, 16> Actions;
1259 typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1260};
1261
1262void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1263 Value *NewVal) {
1264 Actions.push_back(
1265 new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1266}
1267
1268void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1269 Value *NewVal) {
1270 Actions.push_back(
1271 new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1272}
1273
1274void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1275 Value *New) {
1276 Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1277}
1278
1279void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1280 Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1281}
1282
1283Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1284 Type *Ty) {
1285 TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1286 Actions.push_back(TB);
1287 return TB->getBuiltInstruction();
1288}
1289
1290Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1291 Value *Opnd, Type *Ty) {
1292 SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1293 Actions.push_back(SB);
1294 return SB->getBuiltInstruction();
1295}
1296
1297void TypePromotionTransaction::moveBefore(Instruction *Inst,
1298 Instruction *Before) {
1299 Actions.push_back(
1300 new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1301}
1302
1303TypePromotionTransaction::ConstRestorationPt
1304TypePromotionTransaction::getRestorationPoint() const {
Craig Topperc0196b12014-04-14 00:51:57 +00001305 return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001306}
1307
1308void TypePromotionTransaction::commit() {
1309 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1310 ++It) {
1311 (*It)->commit();
1312 delete *It;
1313 }
1314 Actions.clear();
1315}
1316
1317void TypePromotionTransaction::rollback(
1318 TypePromotionTransaction::ConstRestorationPt Point) {
1319 while (!Actions.empty() && Point != (*Actions.rbegin())) {
1320 TypePromotionAction *Curr = Actions.pop_back_val();
1321 Curr->undo();
1322 delete Curr;
1323 }
1324}
1325
1326TypePromotionTransaction::~TypePromotionTransaction() {
1327 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1328 delete *It;
1329 Actions.clear();
1330}
Chandler Carruthc8925912013-01-05 02:09:22 +00001331
1332/// \brief A helper class for matching addressing modes.
1333///
1334/// This encapsulates the logic for matching the target-legal addressing modes.
1335class AddressingModeMatcher {
1336 SmallVectorImpl<Instruction*> &AddrModeInsts;
1337 const TargetLowering &TLI;
1338
1339 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1340 /// the memory instruction that we're computing this address for.
1341 Type *AccessTy;
1342 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001343
Chandler Carruthc8925912013-01-05 02:09:22 +00001344 /// AddrMode - This is the addressing mode that we're building up. This is
1345 /// part of the return value of this addressing mode matching stuff.
1346 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001347
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001348 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1349 const SetOfInstrs &InsertedTruncs;
1350 /// A map from the instructions to their type before promotion.
1351 InstrToOrigTy &PromotedInsts;
1352 /// The ongoing transaction where every action should be registered.
1353 TypePromotionTransaction &TPT;
1354
Chandler Carruthc8925912013-01-05 02:09:22 +00001355 /// IgnoreProfitability - This is set to true when we should not do
1356 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1357 /// always returns true.
1358 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001359
Chandler Carruthc8925912013-01-05 02:09:22 +00001360 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1361 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001362 Instruction *MI, ExtAddrMode &AM,
1363 const SetOfInstrs &InsertedTruncs,
1364 InstrToOrigTy &PromotedInsts,
1365 TypePromotionTransaction &TPT)
1366 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1367 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001368 IgnoreProfitability = false;
1369 }
1370public:
Stephen Lin837bba12013-07-15 17:55:02 +00001371
Chandler Carruthc8925912013-01-05 02:09:22 +00001372 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1373 /// give an access type of AccessTy. This returns a list of involved
1374 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001375 /// \p InsertedTruncs The truncate instruction inserted by other
1376 /// CodeGenPrepare
1377 /// optimizations.
1378 /// \p PromotedInsts maps the instructions to their type before promotion.
1379 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001380 static ExtAddrMode Match(Value *V, Type *AccessTy,
1381 Instruction *MemoryInst,
1382 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001383 const TargetLowering &TLI,
1384 const SetOfInstrs &InsertedTruncs,
1385 InstrToOrigTy &PromotedInsts,
1386 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001387 ExtAddrMode Result;
1388
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001389 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1390 MemoryInst, Result, InsertedTruncs,
1391 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001392 (void)Success; assert(Success && "Couldn't select *anything*?");
1393 return Result;
1394 }
1395private:
1396 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1397 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001398 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00001399 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00001400 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1401 ExtAddrMode &AMBefore,
1402 ExtAddrMode &AMAfter);
1403 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001404 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1405 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001406};
1407
1408/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1409/// Return true and update AddrMode if this addr mode is legal for the target,
1410/// false if not.
1411bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1412 unsigned Depth) {
1413 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1414 // mode. Just process that directly.
1415 if (Scale == 1)
1416 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001417
Chandler Carruthc8925912013-01-05 02:09:22 +00001418 // If the scale is 0, it takes nothing to add this.
1419 if (Scale == 0)
1420 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001421
Chandler Carruthc8925912013-01-05 02:09:22 +00001422 // If we already have a scale of this value, we can add to it, otherwise, we
1423 // need an available scale field.
1424 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1425 return false;
1426
1427 ExtAddrMode TestAddrMode = AddrMode;
1428
1429 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1430 // [A+B + A*7] -> [B+A*8].
1431 TestAddrMode.Scale += Scale;
1432 TestAddrMode.ScaledReg = ScaleReg;
1433
1434 // If the new address isn't legal, bail out.
1435 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1436 return false;
1437
1438 // It was legal, so commit it.
1439 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001440
Chandler Carruthc8925912013-01-05 02:09:22 +00001441 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1442 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1443 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00001444 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00001445 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1446 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1447 TestAddrMode.ScaledReg = AddLHS;
1448 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001449
Chandler Carruthc8925912013-01-05 02:09:22 +00001450 // If this addressing mode is legal, commit it and remember that we folded
1451 // this instruction.
1452 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1453 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1454 AddrMode = TestAddrMode;
1455 return true;
1456 }
1457 }
1458
1459 // Otherwise, not (x+c)*scale, just return what we have.
1460 return true;
1461}
1462
1463/// MightBeFoldableInst - This is a little filter, which returns true if an
1464/// addressing computation involving I might be folded into a load/store
1465/// accessing it. This doesn't need to be perfect, but needs to accept at least
1466/// the set of instructions that MatchOperationAddr can.
1467static bool MightBeFoldableInst(Instruction *I) {
1468 switch (I->getOpcode()) {
1469 case Instruction::BitCast:
1470 // Don't touch identity bitcasts.
1471 if (I->getType() == I->getOperand(0)->getType())
1472 return false;
1473 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1474 case Instruction::PtrToInt:
1475 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1476 return true;
1477 case Instruction::IntToPtr:
1478 // We know the input is intptr_t, so this is foldable.
1479 return true;
1480 case Instruction::Add:
1481 return true;
1482 case Instruction::Mul:
1483 case Instruction::Shl:
1484 // Can only handle X*C and X << C.
1485 return isa<ConstantInt>(I->getOperand(1));
1486 case Instruction::GetElementPtr:
1487 return true;
1488 default:
1489 return false;
1490 }
1491}
1492
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001493/// \brief Hepler class to perform type promotion.
1494class TypePromotionHelper {
1495 /// \brief Utility function to check whether or not a sign extension of
1496 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1497 /// using the operands of \p Inst or promoting \p Inst.
1498 /// In other words, check if:
1499 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1500 /// #1 Promotion applies:
1501 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1502 /// #2 Operand reuses:
1503 /// sext opnd1 to ConsideredSExtType.
1504 /// \p PromotedInsts maps the instructions to their type before promotion.
1505 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1506 const InstrToOrigTy &PromotedInsts);
1507
1508 /// \brief Utility function to determine if \p OpIdx should be promoted when
1509 /// promoting \p Inst.
1510 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1511 if (isa<SelectInst>(Inst) && OpIdx == 0)
1512 return false;
1513 return true;
1514 }
1515
1516 /// \brief Utility function to promote the operand of \p SExt when this
1517 /// operand is a promotable trunc or sext.
1518 /// \p PromotedInsts maps the instructions to their type before promotion.
1519 /// \p CreatedInsts[out] contains how many non-free instructions have been
1520 /// created to promote the operand of SExt.
1521 /// Should never be called directly.
1522 /// \return The promoted value which is used instead of SExt.
1523 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1524 TypePromotionTransaction &TPT,
1525 InstrToOrigTy &PromotedInsts,
1526 unsigned &CreatedInsts);
1527
1528 /// \brief Utility function to promote the operand of \p SExt when this
1529 /// operand is promotable and is not a supported trunc or sext.
1530 /// \p PromotedInsts maps the instructions to their type before promotion.
1531 /// \p CreatedInsts[out] contains how many non-free instructions have been
1532 /// created to promote the operand of SExt.
1533 /// Should never be called directly.
1534 /// \return The promoted value which is used instead of SExt.
1535 static Value *promoteOperandForOther(Instruction *SExt,
1536 TypePromotionTransaction &TPT,
1537 InstrToOrigTy &PromotedInsts,
1538 unsigned &CreatedInsts);
1539
1540public:
1541 /// Type for the utility function that promotes the operand of SExt.
1542 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1543 InstrToOrigTy &PromotedInsts,
1544 unsigned &CreatedInsts);
1545 /// \brief Given a sign extend instruction \p SExt, return the approriate
1546 /// action to promote the operand of \p SExt instead of using SExt.
1547 /// \return NULL if no promotable action is possible with the current
1548 /// sign extension.
1549 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1550 /// the others CodeGenPrepare optimizations. This information is important
1551 /// because we do not want to promote these instructions as CodeGenPrepare
1552 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1553 /// \p PromotedInsts maps the instructions to their type before promotion.
1554 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1555 const TargetLowering &TLI,
1556 const InstrToOrigTy &PromotedInsts);
1557};
1558
1559bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1560 Type *ConsideredSExtType,
1561 const InstrToOrigTy &PromotedInsts) {
1562 // We can always get through sext.
1563 if (isa<SExtInst>(Inst))
1564 return true;
1565
1566 // We can get through binary operator, if it is legal. In other words, the
1567 // binary operator must have a nuw or nsw flag.
1568 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1569 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1570 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1571 return true;
1572
1573 // Check if we can do the following simplification.
1574 // sext(trunc(sext)) --> sext
1575 if (!isa<TruncInst>(Inst))
1576 return false;
1577
1578 Value *OpndVal = Inst->getOperand(0);
1579 // Check if we can use this operand in the sext.
1580 // If the type is larger than the result type of the sign extension,
1581 // we cannot.
1582 if (OpndVal->getType()->getIntegerBitWidth() >
1583 ConsideredSExtType->getIntegerBitWidth())
1584 return false;
1585
1586 // If the operand of the truncate is not an instruction, we will not have
1587 // any information on the dropped bits.
1588 // (Actually we could for constant but it is not worth the extra logic).
1589 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1590 if (!Opnd)
1591 return false;
1592
1593 // Check if the source of the type is narrow enough.
1594 // I.e., check that trunc just drops sign extended bits.
1595 // #1 get the type of the operand.
1596 const Type *OpndType;
1597 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1598 if (It != PromotedInsts.end())
1599 OpndType = It->second;
1600 else if (isa<SExtInst>(Opnd))
1601 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1602 else
1603 return false;
1604
1605 // #2 check that the truncate just drop sign extended bits.
1606 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1607 return true;
1608
1609 return false;
1610}
1611
1612TypePromotionHelper::Action TypePromotionHelper::getAction(
1613 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1614 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1615 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1616 Type *SExtTy = SExt->getType();
1617 // If the operand of the sign extension is not an instruction, we cannot
1618 // get through.
1619 // If it, check we can get through.
1620 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
Craig Topperc0196b12014-04-14 00:51:57 +00001621 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001622
1623 // Do not promote if the operand has been added by codegenprepare.
1624 // Otherwise, it means we are undoing an optimization that is likely to be
1625 // redone, thus causing potential infinite loop.
1626 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00001627 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001628
1629 // SExt or Trunc instructions.
1630 // Return the related handler.
1631 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1632 return promoteOperandForTruncAndSExt;
1633
1634 // Regular instruction.
1635 // Abort early if we will have to insert non-free instructions.
1636 if (!SExtOpnd->hasOneUse() &&
1637 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00001638 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001639 return promoteOperandForOther;
1640}
1641
1642Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1643 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1644 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1645 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1646 // get through it and this method should not be called.
1647 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1648 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1649 // => sext(opnd).
1650 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1651 CreatedInsts = 0;
1652
1653 // Remove dead code.
1654 if (SExtOpnd->use_empty())
1655 TPT.eraseInstruction(SExtOpnd);
1656
1657 // Check if the sext is still needed.
1658 if (SExt->getType() != SExt->getOperand(0)->getType())
1659 return SExt;
1660
1661 // At this point we have: sext ty opnd to ty.
1662 // Reassign the uses of SExt to the opnd and remove SExt.
1663 Value *NextVal = SExt->getOperand(0);
1664 TPT.eraseInstruction(SExt, NextVal);
1665 return NextVal;
1666}
1667
1668Value *
1669TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1670 TypePromotionTransaction &TPT,
1671 InstrToOrigTy &PromotedInsts,
1672 unsigned &CreatedInsts) {
1673 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1674 // get through it and this method should not be called.
1675 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1676 CreatedInsts = 0;
1677 if (!SExtOpnd->hasOneUse()) {
1678 // SExtOpnd will be promoted.
1679 // All its uses, but SExt, will need to use a truncated value of the
1680 // promoted version.
1681 // Create the truncate now.
1682 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1683 Trunc->removeFromParent();
1684 // Insert it just after the definition.
1685 Trunc->insertAfter(SExtOpnd);
1686
1687 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1688 // Restore the operand of SExt (which has been replace by the previous call
1689 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1690 TPT.setOperand(SExt, 0, SExtOpnd);
1691 }
1692
1693 // Get through the Instruction:
1694 // 1. Update its type.
1695 // 2. Replace the uses of SExt by Inst.
1696 // 3. Sign extend each operand that needs to be sign extended.
1697
1698 // Remember the original type of the instruction before promotion.
1699 // This is useful to know that the high bits are sign extended bits.
1700 PromotedInsts.insert(
1701 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1702 // Step #1.
1703 TPT.mutateType(SExtOpnd, SExt->getType());
1704 // Step #2.
1705 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1706 // Step #3.
1707 Instruction *SExtForOpnd = SExt;
1708
1709 DEBUG(dbgs() << "Propagate SExt to operands\n");
1710 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1711 ++OpIdx) {
1712 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1713 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1714 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1715 DEBUG(dbgs() << "No need to propagate\n");
1716 continue;
1717 }
1718 // Check if we can statically sign extend the operand.
1719 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1720 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1721 DEBUG(dbgs() << "Statically sign extend\n");
1722 TPT.setOperand(
1723 SExtOpnd, OpIdx,
1724 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1725 continue;
1726 }
1727 // UndefValue are typed, so we have to statically sign extend them.
1728 if (isa<UndefValue>(Opnd)) {
1729 DEBUG(dbgs() << "Statically sign extend\n");
1730 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1731 continue;
1732 }
1733
1734 // Otherwise we have to explicity sign extend the operand.
1735 // Check if SExt was reused to sign extend an operand.
1736 if (!SExtForOpnd) {
1737 // If yes, create a new one.
1738 DEBUG(dbgs() << "More operands to sext\n");
1739 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1740 ++CreatedInsts;
1741 }
1742
1743 TPT.setOperand(SExtForOpnd, 0, Opnd);
1744
1745 // Move the sign extension before the insertion point.
1746 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1747 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1748 // If more sext are required, new instructions will have to be created.
Craig Topperc0196b12014-04-14 00:51:57 +00001749 SExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001750 }
1751 if (SExtForOpnd == SExt) {
1752 DEBUG(dbgs() << "Sign extension is useless now\n");
1753 TPT.eraseInstruction(SExt);
1754 }
1755 return SExtOpnd;
1756}
1757
Quentin Colombet867c5502014-02-14 22:23:22 +00001758/// IsPromotionProfitable - Check whether or not promoting an instruction
1759/// to a wider type was profitable.
1760/// \p MatchedSize gives the number of instructions that have been matched
1761/// in the addressing mode after the promotion was applied.
1762/// \p SizeWithPromotion gives the number of created instructions for
1763/// the promotion plus the number of instructions that have been
1764/// matched in the addressing mode before the promotion.
1765/// \p PromotedOperand is the value that has been promoted.
1766/// \return True if the promotion is profitable, false otherwise.
1767bool
1768AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1769 unsigned SizeWithPromotion,
1770 Value *PromotedOperand) const {
1771 // We folded less instructions than what we created to promote the operand.
1772 // This is not profitable.
1773 if (MatchedSize < SizeWithPromotion)
1774 return false;
1775 if (MatchedSize > SizeWithPromotion)
1776 return true;
1777 // The promotion is neutral but it may help folding the sign extension in
1778 // loads for instance.
1779 // Check that we did not create an illegal instruction.
1780 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1781 if (!PromotedInst)
1782 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00001783 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1784 // If the ISDOpcode is undefined, it was undefined before the promotion.
1785 if (!ISDOpcode)
1786 return true;
1787 // Otherwise, check if the promoted instruction is legal or not.
1788 return TLI.isOperationLegalOrCustom(ISDOpcode,
Quentin Colombet867c5502014-02-14 22:23:22 +00001789 EVT::getEVT(PromotedInst->getType()));
1790}
1791
Chandler Carruthc8925912013-01-05 02:09:22 +00001792/// MatchOperationAddr - Given an instruction or constant expr, see if we can
1793/// fold the operation into the addressing mode. If so, update the addressing
1794/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001795/// If \p MovedAway is not NULL, it contains the information of whether or
1796/// not AddrInst has to be folded into the addressing mode on success.
1797/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1798/// because it has been moved away.
1799/// Thus AddrInst must not be added in the matched instructions.
1800/// This state can happen when AddrInst is a sext, since it may be moved away.
1801/// Therefore, AddrInst may not be valid when MovedAway is true and it must
1802/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00001803bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001804 unsigned Depth,
1805 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001806 // Avoid exponential behavior on extremely deep expression trees.
1807 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001808
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001809 // By default, all matched instructions stay in place.
1810 if (MovedAway)
1811 *MovedAway = false;
1812
Chandler Carruthc8925912013-01-05 02:09:22 +00001813 switch (Opcode) {
1814 case Instruction::PtrToInt:
1815 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1816 return MatchAddr(AddrInst->getOperand(0), Depth);
1817 case Instruction::IntToPtr:
1818 // This inttoptr is a no-op if the integer type is pointer sized.
1819 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00001820 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00001821 return MatchAddr(AddrInst->getOperand(0), Depth);
1822 return false;
1823 case Instruction::BitCast:
1824 // BitCast is always a noop, and we can handle it as long as it is
1825 // int->int or pointer->pointer (we don't want int<->fp or something).
1826 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1827 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1828 // Don't touch identity bitcasts. These were probably put here by LSR,
1829 // and we don't want to mess around with them. Assume it knows what it
1830 // is doing.
1831 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1832 return MatchAddr(AddrInst->getOperand(0), Depth);
1833 return false;
1834 case Instruction::Add: {
1835 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1836 ExtAddrMode BackupAddrMode = AddrMode;
1837 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001838 // Start a transaction at this point.
1839 // The LHS may match but not the RHS.
1840 // Therefore, we need a higher level restoration point to undo partially
1841 // matched operation.
1842 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1843 TPT.getRestorationPoint();
1844
Chandler Carruthc8925912013-01-05 02:09:22 +00001845 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1846 MatchAddr(AddrInst->getOperand(0), Depth+1))
1847 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001848
Chandler Carruthc8925912013-01-05 02:09:22 +00001849 // Restore the old addr mode info.
1850 AddrMode = BackupAddrMode;
1851 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001852 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00001853
Chandler Carruthc8925912013-01-05 02:09:22 +00001854 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1855 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1856 MatchAddr(AddrInst->getOperand(1), Depth+1))
1857 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001858
Chandler Carruthc8925912013-01-05 02:09:22 +00001859 // Otherwise we definitely can't merge the ADD in.
1860 AddrMode = BackupAddrMode;
1861 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001862 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00001863 break;
1864 }
1865 //case Instruction::Or:
1866 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1867 //break;
1868 case Instruction::Mul:
1869 case Instruction::Shl: {
1870 // Can only handle X*C and X << C.
1871 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1872 if (!RHS) return false;
1873 int64_t Scale = RHS->getSExtValue();
1874 if (Opcode == Instruction::Shl)
1875 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001876
Chandler Carruthc8925912013-01-05 02:09:22 +00001877 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1878 }
1879 case Instruction::GetElementPtr: {
1880 // Scan the GEP. We check it if it contains constant offsets and at most
1881 // one variable offset.
1882 int VariableOperand = -1;
1883 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00001884
Chandler Carruthc8925912013-01-05 02:09:22 +00001885 int64_t ConstantOffset = 0;
1886 const DataLayout *TD = TLI.getDataLayout();
1887 gep_type_iterator GTI = gep_type_begin(AddrInst);
1888 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1889 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1890 const StructLayout *SL = TD->getStructLayout(STy);
1891 unsigned Idx =
1892 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1893 ConstantOffset += SL->getElementOffset(Idx);
1894 } else {
1895 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1896 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1897 ConstantOffset += CI->getSExtValue()*TypeSize;
1898 } else if (TypeSize) { // Scales of zero don't do anything.
1899 // We only allow one variable index at the moment.
1900 if (VariableOperand != -1)
1901 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001902
Chandler Carruthc8925912013-01-05 02:09:22 +00001903 // Remember the variable index.
1904 VariableOperand = i;
1905 VariableScale = TypeSize;
1906 }
1907 }
1908 }
Stephen Lin837bba12013-07-15 17:55:02 +00001909
Chandler Carruthc8925912013-01-05 02:09:22 +00001910 // A common case is for the GEP to only do a constant offset. In this case,
1911 // just add it to the disp field and check validity.
1912 if (VariableOperand == -1) {
1913 AddrMode.BaseOffs += ConstantOffset;
1914 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1915 // Check to see if we can fold the base pointer in too.
1916 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1917 return true;
1918 }
1919 AddrMode.BaseOffs -= ConstantOffset;
1920 return false;
1921 }
1922
1923 // Save the valid addressing mode in case we can't match.
1924 ExtAddrMode BackupAddrMode = AddrMode;
1925 unsigned OldSize = AddrModeInsts.size();
1926
1927 // See if the scale and offset amount is valid for this target.
1928 AddrMode.BaseOffs += ConstantOffset;
1929
1930 // Match the base operand of the GEP.
1931 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1932 // If it couldn't be matched, just stuff the value in a register.
1933 if (AddrMode.HasBaseReg) {
1934 AddrMode = BackupAddrMode;
1935 AddrModeInsts.resize(OldSize);
1936 return false;
1937 }
1938 AddrMode.HasBaseReg = true;
1939 AddrMode.BaseReg = AddrInst->getOperand(0);
1940 }
1941
1942 // Match the remaining variable portion of the GEP.
1943 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1944 Depth)) {
1945 // If it couldn't be matched, try stuffing the base into a register
1946 // instead of matching it, and retrying the match of the scale.
1947 AddrMode = BackupAddrMode;
1948 AddrModeInsts.resize(OldSize);
1949 if (AddrMode.HasBaseReg)
1950 return false;
1951 AddrMode.HasBaseReg = true;
1952 AddrMode.BaseReg = AddrInst->getOperand(0);
1953 AddrMode.BaseOffs += ConstantOffset;
1954 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1955 VariableScale, Depth)) {
1956 // If even that didn't work, bail.
1957 AddrMode = BackupAddrMode;
1958 AddrModeInsts.resize(OldSize);
1959 return false;
1960 }
1961 }
1962
1963 return true;
1964 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001965 case Instruction::SExt: {
1966 // Try to move this sext out of the way of the addressing mode.
1967 Instruction *SExt = cast<Instruction>(AddrInst);
1968 // Ask for a method for doing so.
1969 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1970 SExt, InsertedTruncs, TLI, PromotedInsts);
1971 if (!TPH)
1972 return false;
1973
1974 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1975 TPT.getRestorationPoint();
1976 unsigned CreatedInsts = 0;
1977 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1978 // SExt has been moved away.
1979 // Thus either it will be rematched later in the recursive calls or it is
1980 // gone. Anyway, we must not fold it into the addressing mode at this point.
1981 // E.g.,
1982 // op = add opnd, 1
1983 // idx = sext op
1984 // addr = gep base, idx
1985 // is now:
1986 // promotedOpnd = sext opnd <- no match here
1987 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
1988 // addr = gep base, op <- match
1989 if (MovedAway)
1990 *MovedAway = true;
1991
1992 assert(PromotedOperand &&
1993 "TypePromotionHelper should have filtered out those cases");
1994
1995 ExtAddrMode BackupAddrMode = AddrMode;
1996 unsigned OldSize = AddrModeInsts.size();
1997
1998 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00001999 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2000 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002001 AddrMode = BackupAddrMode;
2002 AddrModeInsts.resize(OldSize);
2003 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2004 TPT.rollback(LastKnownGood);
2005 return false;
2006 }
2007 return true;
2008 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002009 }
2010 return false;
2011}
2012
2013/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2014/// addressing mode. If Addr can't be added to AddrMode this returns false and
2015/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2016/// or intptr_t for the target.
2017///
2018bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002019 // Start a transaction at this point that we will rollback if the matching
2020 // fails.
2021 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2022 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002023 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2024 // Fold in immediates if legal for the target.
2025 AddrMode.BaseOffs += CI->getSExtValue();
2026 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2027 return true;
2028 AddrMode.BaseOffs -= CI->getSExtValue();
2029 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2030 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002031 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002032 AddrMode.BaseGV = GV;
2033 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2034 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002035 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002036 }
2037 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2038 ExtAddrMode BackupAddrMode = AddrMode;
2039 unsigned OldSize = AddrModeInsts.size();
2040
2041 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002042 bool MovedAway = false;
2043 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2044 // This instruction may have been move away. If so, there is nothing
2045 // to check here.
2046 if (MovedAway)
2047 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002048 // Okay, it's possible to fold this. Check to see if it is actually
2049 // *profitable* to do so. We use a simple cost model to avoid increasing
2050 // register pressure too much.
2051 if (I->hasOneUse() ||
2052 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2053 AddrModeInsts.push_back(I);
2054 return true;
2055 }
Stephen Lin837bba12013-07-15 17:55:02 +00002056
Chandler Carruthc8925912013-01-05 02:09:22 +00002057 // It isn't profitable to do this, roll back.
2058 //cerr << "NOT FOLDING: " << *I;
2059 AddrMode = BackupAddrMode;
2060 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002061 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002062 }
2063 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2064 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2065 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002066 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002067 } else if (isa<ConstantPointerNull>(Addr)) {
2068 // Null pointer gets folded without affecting the addressing mode.
2069 return true;
2070 }
2071
2072 // Worse case, the target should support [reg] addressing modes. :)
2073 if (!AddrMode.HasBaseReg) {
2074 AddrMode.HasBaseReg = true;
2075 AddrMode.BaseReg = Addr;
2076 // Still check for legality in case the target supports [imm] but not [i+r].
2077 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2078 return true;
2079 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002080 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002081 }
2082
2083 // If the base register is already taken, see if we can do [r+r].
2084 if (AddrMode.Scale == 0) {
2085 AddrMode.Scale = 1;
2086 AddrMode.ScaledReg = Addr;
2087 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2088 return true;
2089 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002090 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002091 }
2092 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002093 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002094 return false;
2095}
2096
2097/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2098/// inline asm call are due to memory operands. If so, return true, otherwise
2099/// return false.
2100static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2101 const TargetLowering &TLI) {
2102 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2103 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2104 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002105
Chandler Carruthc8925912013-01-05 02:09:22 +00002106 // Compute the constraint code and ConstraintType to use.
2107 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2108
2109 // If this asm operand is our Value*, and if it isn't an indirect memory
2110 // operand, we can't fold it!
2111 if (OpInfo.CallOperandVal == OpVal &&
2112 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2113 !OpInfo.isIndirect))
2114 return false;
2115 }
2116
2117 return true;
2118}
2119
2120/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2121/// memory use. If we find an obviously non-foldable instruction, return true.
2122/// Add the ultimately found memory instructions to MemoryUses.
2123static bool FindAllMemoryUses(Instruction *I,
2124 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2125 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2126 const TargetLowering &TLI) {
2127 // If we already considered this instruction, we're done.
2128 if (!ConsideredInsts.insert(I))
2129 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002130
Chandler Carruthc8925912013-01-05 02:09:22 +00002131 // If this is an obviously unfoldable instruction, bail out.
2132 if (!MightBeFoldableInst(I))
2133 return true;
2134
2135 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002136 for (Use &U : I->uses()) {
2137 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002138
Chandler Carruthcdf47882014-03-09 03:16:01 +00002139 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2140 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002141 continue;
2142 }
Stephen Lin837bba12013-07-15 17:55:02 +00002143
Chandler Carruthcdf47882014-03-09 03:16:01 +00002144 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2145 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002146 if (opNo == 0) return true; // Storing addr, not into addr.
2147 MemoryUses.push_back(std::make_pair(SI, opNo));
2148 continue;
2149 }
Stephen Lin837bba12013-07-15 17:55:02 +00002150
Chandler Carruthcdf47882014-03-09 03:16:01 +00002151 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002152 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2153 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002154
Chandler Carruthc8925912013-01-05 02:09:22 +00002155 // If this is a memory operand, we're cool, otherwise bail out.
2156 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2157 return true;
2158 continue;
2159 }
Stephen Lin837bba12013-07-15 17:55:02 +00002160
Chandler Carruthcdf47882014-03-09 03:16:01 +00002161 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002162 return true;
2163 }
2164
2165 return false;
2166}
2167
2168/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2169/// the use site that we're folding it into. If so, there is no cost to
2170/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2171/// that we know are live at the instruction already.
2172bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2173 Value *KnownLive2) {
2174 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002175 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002176 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002177
Chandler Carruthc8925912013-01-05 02:09:22 +00002178 // All values other than instructions and arguments (e.g. constants) are live.
2179 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002180
Chandler Carruthc8925912013-01-05 02:09:22 +00002181 // If Val is a constant sized alloca in the entry block, it is live, this is
2182 // true because it is just a reference to the stack/frame pointer, which is
2183 // live for the whole function.
2184 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2185 if (AI->isStaticAlloca())
2186 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002187
Chandler Carruthc8925912013-01-05 02:09:22 +00002188 // Check to see if this value is already used in the memory instruction's
2189 // block. If so, it's already live into the block at the very least, so we
2190 // can reasonably fold it.
2191 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2192}
2193
2194/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2195/// mode of the machine to fold the specified instruction into a load or store
2196/// that ultimately uses it. However, the specified instruction has multiple
2197/// uses. Given this, it may actually increase register pressure to fold it
2198/// into the load. For example, consider this code:
2199///
2200/// X = ...
2201/// Y = X+1
2202/// use(Y) -> nonload/store
2203/// Z = Y+1
2204/// load Z
2205///
2206/// In this case, Y has multiple uses, and can be folded into the load of Z
2207/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2208/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2209/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2210/// number of computations either.
2211///
2212/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2213/// X was live across 'load Z' for other reasons, we actually *would* want to
2214/// fold the addressing mode in the Z case. This would make Y die earlier.
2215bool AddressingModeMatcher::
2216IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2217 ExtAddrMode &AMAfter) {
2218 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002219
Chandler Carruthc8925912013-01-05 02:09:22 +00002220 // AMBefore is the addressing mode before this instruction was folded into it,
2221 // and AMAfter is the addressing mode after the instruction was folded. Get
2222 // the set of registers referenced by AMAfter and subtract out those
2223 // referenced by AMBefore: this is the set of values which folding in this
2224 // address extends the lifetime of.
2225 //
2226 // Note that there are only two potential values being referenced here,
2227 // BaseReg and ScaleReg (global addresses are always available, as are any
2228 // folded immediates).
2229 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002230
Chandler Carruthc8925912013-01-05 02:09:22 +00002231 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2232 // lifetime wasn't extended by adding this instruction.
2233 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002234 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002235 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002236 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002237
2238 // If folding this instruction (and it's subexprs) didn't extend any live
2239 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002240 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002241 return true;
2242
2243 // If all uses of this instruction are ultimately load/store/inlineasm's,
2244 // check to see if their addressing modes will include this instruction. If
2245 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2246 // uses.
2247 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2248 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2249 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2250 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002251
Chandler Carruthc8925912013-01-05 02:09:22 +00002252 // Now that we know that all uses of this instruction are part of a chain of
2253 // computation involving only operations that could theoretically be folded
2254 // into a memory use, loop over each of these uses and see if they could
2255 // *actually* fold the instruction.
2256 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2257 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2258 Instruction *User = MemoryUses[i].first;
2259 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002260
Chandler Carruthc8925912013-01-05 02:09:22 +00002261 // Get the access type of this use. If the use isn't a pointer, we don't
2262 // know what it accesses.
2263 Value *Address = User->getOperand(OpNo);
2264 if (!Address->getType()->isPointerTy())
2265 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002266 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002267
Chandler Carruthc8925912013-01-05 02:09:22 +00002268 // Do a match against the root of this address, ignoring profitability. This
2269 // will tell us if the addressing mode for the memory operation will
2270 // *actually* cover the shared instruction.
2271 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002272 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2273 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002274 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002275 MemoryInst, Result, InsertedTruncs,
2276 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002277 Matcher.IgnoreProfitability = true;
2278 bool Success = Matcher.MatchAddr(Address, 0);
2279 (void)Success; assert(Success && "Couldn't select *anything*?");
2280
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002281 // The match was to check the profitability, the changes made are not
2282 // part of the original matcher. Therefore, they should be dropped
2283 // otherwise the original matcher will not present the right state.
2284 TPT.rollback(LastKnownGood);
2285
Chandler Carruthc8925912013-01-05 02:09:22 +00002286 // If the match didn't cover I, then it won't be shared by it.
2287 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2288 I) == MatchedAddrModeInsts.end())
2289 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002290
Chandler Carruthc8925912013-01-05 02:09:22 +00002291 MatchedAddrModeInsts.clear();
2292 }
Stephen Lin837bba12013-07-15 17:55:02 +00002293
Chandler Carruthc8925912013-01-05 02:09:22 +00002294 return true;
2295}
2296
2297} // end anonymous namespace
2298
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002299/// IsNonLocalValue - Return true if the specified values are defined in a
2300/// different basic block than BB.
2301static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2302 if (Instruction *I = dyn_cast<Instruction>(V))
2303 return I->getParent() != BB;
2304 return false;
2305}
2306
Bob Wilson53bdae32009-12-03 21:47:07 +00002307/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002308/// addressing modes that can do significant amounts of computation. As such,
2309/// instruction selection will try to get the load or store to do as much
2310/// computation as possible for the program. The problem is that isel can only
2311/// see within a single block. As such, we sink as much legal addressing mode
2312/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002313///
2314/// This method is used to optimize both load/store and inline asms with memory
2315/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002316bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002317 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002318 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002319
2320 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002321 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002322 SmallVector<Value*, 8> worklist;
2323 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002324 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002325
Owen Anderson8ba5f392010-11-27 08:15:55 +00002326 // Use a worklist to iteratively look through PHI nodes, and ensure that
2327 // the addressing mode obtained from the non-PHI roots of the graph
2328 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00002329 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002330 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002331 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002332 SmallVector<Instruction*, 16> AddrModeInsts;
2333 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002334 TypePromotionTransaction TPT;
2335 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2336 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002337 while (!worklist.empty()) {
2338 Value *V = worklist.back();
2339 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002340
Owen Anderson8ba5f392010-11-27 08:15:55 +00002341 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002342 if (!Visited.insert(V)) {
Craig Topperc0196b12014-04-14 00:51:57 +00002343 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002344 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002345 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002346
Owen Anderson8ba5f392010-11-27 08:15:55 +00002347 // For a PHI node, push all of its incoming values.
2348 if (PHINode *P = dyn_cast<PHINode>(V)) {
2349 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2350 worklist.push_back(P->getIncomingValue(i));
2351 continue;
2352 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002353
Owen Anderson8ba5f392010-11-27 08:15:55 +00002354 // For non-PHIs, determine the addressing mode being computed.
2355 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002356 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2357 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2358 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002359
2360 // This check is broken into two cases with very similar code to avoid using
2361 // getNumUses() as much as possible. Some values have a lot of uses, so
2362 // calling getNumUses() unconditionally caused a significant compile-time
2363 // regression.
2364 if (!Consensus) {
2365 Consensus = V;
2366 AddrMode = NewAddrMode;
2367 AddrModeInsts = NewAddrModeInsts;
2368 continue;
2369 } else if (NewAddrMode == AddrMode) {
2370 if (!IsNumUsesConsensusValid) {
2371 NumUsesConsensus = Consensus->getNumUses();
2372 IsNumUsesConsensusValid = true;
2373 }
2374
2375 // Ensure that the obtained addressing mode is equivalent to that obtained
2376 // for all other roots of the PHI traversal. Also, when choosing one
2377 // such root as representative, select the one with the most uses in order
2378 // to keep the cost modeling heuristics in AddressingModeMatcher
2379 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002380 unsigned NumUses = V->getNumUses();
2381 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002382 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002383 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002384 AddrModeInsts = NewAddrModeInsts;
2385 }
2386 continue;
2387 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002388
Craig Topperc0196b12014-04-14 00:51:57 +00002389 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002390 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002391 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002392
Owen Anderson8ba5f392010-11-27 08:15:55 +00002393 // If the addressing mode couldn't be determined, or if multiple different
2394 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002395 if (!Consensus) {
2396 TPT.rollback(LastKnownGood);
2397 return false;
2398 }
2399 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002400
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002401 // Check to see if any of the instructions supersumed by this addr mode are
2402 // non-local to I's BB.
2403 bool AnyNonLocal = false;
2404 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002405 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002406 AnyNonLocal = true;
2407 break;
2408 }
2409 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002410
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002411 // If all the instructions matched are already in this BB, don't do anything.
2412 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002413 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002414 return false;
2415 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002416
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002417 // Insert this computation right after this user. Since our caller is
2418 // scanning from the top of the BB to the bottom, reuse of the expr are
2419 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002420 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002421
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002422 // Now that we determined the addressing expression we want to use and know
2423 // that we have to sink it into this block. Check to see if we have already
2424 // done this for some other load/store instr in this block. If so, reuse the
2425 // computation.
2426 Value *&SunkAddr = SunkAddrs[Addr];
2427 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002428 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002429 << *MemoryInst);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002430 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002431 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00002432 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2433 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2434 // By default, we use the GEP-based method when AA is used later. This
2435 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2436 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2437 << *MemoryInst);
2438 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002439 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002440
2441 // First, find the pointer.
2442 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2443 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002444 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002445 }
2446
2447 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2448 // We can't add more than one pointer together, nor can we scale a
2449 // pointer (both of which seem meaningless).
2450 if (ResultPtr || AddrMode.Scale != 1)
2451 return false;
2452
2453 ResultPtr = AddrMode.ScaledReg;
2454 AddrMode.Scale = 0;
2455 }
2456
2457 if (AddrMode.BaseGV) {
2458 if (ResultPtr)
2459 return false;
2460
2461 ResultPtr = AddrMode.BaseGV;
2462 }
2463
2464 // If the real base value actually came from an inttoptr, then the matcher
2465 // will look through it and provide only the integer value. In that case,
2466 // use it here.
2467 if (!ResultPtr && AddrMode.BaseReg) {
2468 ResultPtr =
2469 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00002470 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002471 } else if (!ResultPtr && AddrMode.Scale == 1) {
2472 ResultPtr =
2473 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2474 AddrMode.Scale = 0;
2475 }
2476
2477 if (!ResultPtr &&
2478 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2479 SunkAddr = Constant::getNullValue(Addr->getType());
2480 } else if (!ResultPtr) {
2481 return false;
2482 } else {
2483 Type *I8PtrTy =
2484 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2485
2486 // Start with the base register. Do this first so that subsequent address
2487 // matching finds it last, which will prevent it from trying to match it
2488 // as the scaled value in case it happens to be a mul. That would be
2489 // problematic if we've sunk a different mul for the scale, because then
2490 // we'd end up sinking both muls.
2491 if (AddrMode.BaseReg) {
2492 Value *V = AddrMode.BaseReg;
2493 if (V->getType() != IntPtrTy)
2494 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2495
2496 ResultIndex = V;
2497 }
2498
2499 // Add the scale value.
2500 if (AddrMode.Scale) {
2501 Value *V = AddrMode.ScaledReg;
2502 if (V->getType() == IntPtrTy) {
2503 // done.
2504 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2505 cast<IntegerType>(V->getType())->getBitWidth()) {
2506 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2507 } else {
2508 // It is only safe to sign extend the BaseReg if we know that the math
2509 // required to create it did not overflow before we extend it. Since
2510 // the original IR value was tossed in favor of a constant back when
2511 // the AddrMode was created we need to bail out gracefully if widths
2512 // do not match instead of extending it.
2513 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2514 if (I && (ResultIndex != AddrMode.BaseReg))
2515 I->eraseFromParent();
2516 return false;
2517 }
2518
2519 if (AddrMode.Scale != 1)
2520 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2521 "sunkaddr");
2522 if (ResultIndex)
2523 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2524 else
2525 ResultIndex = V;
2526 }
2527
2528 // Add in the Base Offset if present.
2529 if (AddrMode.BaseOffs) {
2530 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2531 if (ResultIndex) {
2532 // We need to add this separately from the scale above to help with
2533 // SDAG consecutive load/store merging.
2534 if (ResultPtr->getType() != I8PtrTy)
2535 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2536 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2537 }
2538
2539 ResultIndex = V;
2540 }
2541
2542 if (!ResultIndex) {
2543 SunkAddr = ResultPtr;
2544 } else {
2545 if (ResultPtr->getType() != I8PtrTy)
2546 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2547 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2548 }
2549
2550 if (SunkAddr->getType() != Addr->getType())
2551 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2552 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002553 } else {
David Greene74e2d492010-01-05 01:27:11 +00002554 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002555 << *MemoryInst);
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002556 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002557 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00002558
2559 // Start with the base register. Do this first so that subsequent address
2560 // matching finds it last, which will prevent it from trying to match it
2561 // as the scaled value in case it happens to be a mul. That would be
2562 // problematic if we've sunk a different mul for the scale, because then
2563 // we'd end up sinking both muls.
2564 if (AddrMode.BaseReg) {
2565 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002566 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002567 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002568 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002569 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002570 Result = V;
2571 }
2572
2573 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002574 if (AddrMode.Scale) {
2575 Value *V = AddrMode.ScaledReg;
2576 if (V->getType() == IntPtrTy) {
2577 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002578 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002579 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002580 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2581 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002582 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002583 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002584 // It is only safe to sign extend the BaseReg if we know that the math
2585 // required to create it did not overflow before we extend it. Since
2586 // the original IR value was tossed in favor of a constant back when
2587 // the AddrMode was created we need to bail out gracefully if widths
2588 // do not match instead of extending it.
Jim Grosbach83b44e12014-04-10 00:27:45 +00002589 Instruction *I = dyn_cast<Instruction>(Result);
2590 if (I && (Result != AddrMode.BaseReg))
2591 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002592 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002593 }
2594 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002595 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2596 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002597 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002598 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002599 else
2600 Result = V;
2601 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002602
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002603 // Add in the BaseGV if present.
2604 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002605 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002606 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002607 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002608 else
2609 Result = V;
2610 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002611
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002612 // Add in the Base Offset if present.
2613 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002614 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002615 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002616 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002617 else
2618 Result = V;
2619 }
2620
Craig Topperc0196b12014-04-14 00:51:57 +00002621 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002622 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002623 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002624 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002625 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002626
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002627 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002628
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002629 // If we have no uses, recursively delete the value and all dead instructions
2630 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002631 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002632 // This can cause recursive deletion, which can invalidate our iterator.
2633 // Use a WeakVH to hold onto it in case this happens.
2634 WeakVH IterHandle(CurInstIterator);
2635 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002636
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002637 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002638
2639 if (IterHandle != CurInstIterator) {
2640 // If the iterator instruction was recursively deleted, start over at the
2641 // start of the block.
2642 CurInstIterator = BB->begin();
2643 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002644 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002645 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002646 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002647 return true;
2648}
2649
Evan Cheng1da25002008-02-26 02:42:37 +00002650/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002651/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002652/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002653bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002654 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002655
Nadav Rotem465834c2012-07-24 10:51:42 +00002656 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002657 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002658 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002659 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2660 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002661
Evan Cheng1da25002008-02-26 02:42:37 +00002662 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002663 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002664
Eli Friedman666bbe32008-02-26 18:37:49 +00002665 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2666 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002667 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002668 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002669 } else if (OpInfo.Type == InlineAsm::isInput)
2670 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002671 }
2672
2673 return MadeChange;
2674}
2675
Dan Gohman99429a02009-10-16 20:59:35 +00002676/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2677/// basic block as the load, unless conditions are unfavorable. This allows
2678/// SelectionDAG to fold the extend into the load.
2679///
2680bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2681 // Look for a load being extended.
2682 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2683 if (!LI) return false;
2684
2685 // If they're already in the same block, there's nothing to do.
2686 if (LI->getParent() == I->getParent())
2687 return false;
2688
2689 // If the load has other users and the truncate is not free, this probably
2690 // isn't worthwhile.
2691 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002692 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2693 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002694 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002695 return false;
2696
2697 // Check whether the target supports casts folded into loads.
2698 unsigned LType;
2699 if (isa<ZExtInst>(I))
2700 LType = ISD::ZEXTLOAD;
2701 else {
2702 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2703 LType = ISD::SEXTLOAD;
2704 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002705 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002706 return false;
2707
2708 // Move the extend into the same block as the load, so that SelectionDAG
2709 // can fold it.
2710 I->removeFromParent();
2711 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002712 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002713 return true;
2714}
2715
Evan Chengd3d80172007-12-05 23:58:20 +00002716bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2717 BasicBlock *DefBB = I->getParent();
2718
Bob Wilsonff714f92010-09-21 21:44:14 +00002719 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002720 // other uses of the source with result of extension.
2721 Value *Src = I->getOperand(0);
2722 if (Src->hasOneUse())
2723 return false;
2724
Evan Cheng2011df42007-12-13 07:50:36 +00002725 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002726 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002727 return false;
2728
Evan Cheng7bc89422007-12-12 00:51:06 +00002729 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002730 // this block.
2731 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002732 return false;
2733
Evan Chengd3d80172007-12-05 23:58:20 +00002734 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002735 for (User *U : I->users()) {
2736 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00002737
2738 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002739 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00002740 if (UserBB == DefBB) continue;
2741 DefIsLiveOut = true;
2742 break;
2743 }
2744 if (!DefIsLiveOut)
2745 return false;
2746
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002747 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002748 for (User *U : Src->users()) {
2749 Instruction *UI = cast<Instruction>(U);
2750 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00002751 if (UserBB == DefBB) continue;
2752 // Be conservative. We don't want this xform to end up introducing
2753 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002754 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002755 return false;
2756 }
2757
Evan Chengd3d80172007-12-05 23:58:20 +00002758 // InsertedTruncs - Only insert one trunc in each block once.
2759 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2760
2761 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002762 for (Use &U : Src->uses()) {
2763 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00002764
2765 // Figure out which BB this ext is used in.
2766 BasicBlock *UserBB = User->getParent();
2767 if (UserBB == DefBB) continue;
2768
2769 // Both src and def are live in this block. Rewrite the use.
2770 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2771
2772 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00002773 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00002774 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002775 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00002776 }
2777
2778 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002779 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00002780 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00002781 MadeChange = true;
2782 }
2783
2784 return MadeChange;
2785}
2786
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002787/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2788/// turned into an explicit branch.
2789static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2790 // FIXME: This should use the same heuristics as IfConversion to determine
2791 // whether a select is better represented as a branch. This requires that
2792 // branch probability metadata is preserved for the select, which is not the
2793 // case currently.
2794
2795 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2796
2797 // If the branch is predicted right, an out of order CPU can avoid blocking on
2798 // the compare. Emit cmovs on compares with a memory operand as branches to
2799 // avoid stalls on the load from memory. If the compare has more than one use
2800 // there's probably another cmov or setcc around so it's not worth emitting a
2801 // branch.
2802 if (!Cmp)
2803 return false;
2804
2805 Value *CmpOp0 = Cmp->getOperand(0);
2806 Value *CmpOp1 = Cmp->getOperand(1);
2807
2808 // We check that the memory operand has one use to avoid uses of the loaded
2809 // value directly after the compare, making branches unprofitable.
2810 return Cmp->hasOneUse() &&
2811 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2812 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2813}
2814
2815
Nadav Rotem9d832022012-09-02 12:10:19 +00002816/// If we have a SelectInst that will likely profit from branch prediction,
2817/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002818bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00002819 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2820
2821 // Can we convert the 'select' to CF ?
2822 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002823 return false;
2824
Nadav Rotem9d832022012-09-02 12:10:19 +00002825 TargetLowering::SelectSupportKind SelectKind;
2826 if (VectorCond)
2827 SelectKind = TargetLowering::VectorMaskSelect;
2828 else if (SI->getType()->isVectorTy())
2829 SelectKind = TargetLowering::ScalarCondVectorVal;
2830 else
2831 SelectKind = TargetLowering::ScalarValSelect;
2832
2833 // Do we have efficient codegen support for this kind of 'selects' ?
2834 if (TLI->isSelectSupported(SelectKind)) {
2835 // We have efficient codegen support for the select instruction.
2836 // Check if it is profitable to keep this 'select'.
2837 if (!TLI->isPredictableSelectExpensive() ||
2838 !isFormingBranchFromSelectProfitable(SI))
2839 return false;
2840 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002841
2842 ModifiedDT = true;
2843
2844 // First, we split the block containing the select into 2 blocks.
2845 BasicBlock *StartBlock = SI->getParent();
2846 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2847 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2848
2849 // Create a new block serving as the landing pad for the branch.
2850 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2851 NextBlock->getParent(), NextBlock);
2852
2853 // Move the unconditional branch from the block with the select in it into our
2854 // landing pad block.
2855 StartBlock->getTerminator()->eraseFromParent();
2856 BranchInst::Create(NextBlock, SmallBlock);
2857
2858 // Insert the real conditional branch based on the original condition.
2859 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2860
2861 // The select itself is replaced with a PHI Node.
2862 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2863 PN->takeName(SI);
2864 PN->addIncoming(SI->getTrueValue(), StartBlock);
2865 PN->addIncoming(SI->getFalseValue(), SmallBlock);
2866 SI->replaceAllUsesWith(PN);
2867 SI->eraseFromParent();
2868
2869 // Instruct OptimizeBlock to skip to the next block.
2870 CurInstIterator = StartBlock->end();
2871 ++NumSelectsExpanded;
2872 return true;
2873}
2874
Benjamin Kramer573ff362014-03-01 17:24:40 +00002875static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00002876 SmallVector<int, 16> Mask(SVI->getShuffleMask());
2877 int SplatElem = -1;
2878 for (unsigned i = 0; i < Mask.size(); ++i) {
2879 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
2880 return false;
2881 SplatElem = Mask[i];
2882 }
2883
2884 return true;
2885}
2886
2887/// Some targets have expensive vector shifts if the lanes aren't all the same
2888/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
2889/// it's often worth sinking a shufflevector splat down to its use so that
2890/// codegen can spot all lanes are identical.
2891bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
2892 BasicBlock *DefBB = SVI->getParent();
2893
2894 // Only do this xform if variable vector shifts are particularly expensive.
2895 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
2896 return false;
2897
2898 // We only expect better codegen by sinking a shuffle if we can recognise a
2899 // constant splat.
2900 if (!isBroadcastShuffle(SVI))
2901 return false;
2902
2903 // InsertedShuffles - Only insert a shuffle in each block once.
2904 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
2905
2906 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002907 for (User *U : SVI->users()) {
2908 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00002909
2910 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002911 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00002912 if (UserBB == DefBB) continue;
2913
2914 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002915 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00002916
2917 // Everything checks out, sink the shuffle if the user's block doesn't
2918 // already have a copy.
2919 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
2920
2921 if (!InsertedShuffle) {
2922 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2923 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
2924 SVI->getOperand(1),
2925 SVI->getOperand(2), "", InsertPt);
2926 }
2927
Chandler Carruthcdf47882014-03-09 03:16:01 +00002928 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00002929 MadeChange = true;
2930 }
2931
2932 // If we removed all uses, nuke the shuffle.
2933 if (SVI->use_empty()) {
2934 SVI->eraseFromParent();
2935 MadeChange = true;
2936 }
2937
2938 return MadeChange;
2939}
2940
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002941bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002942 if (PHINode *P = dyn_cast<PHINode>(I)) {
2943 // It is possible for very late stage optimizations (such as SimplifyCFG)
2944 // to introduce PHI nodes too late to be cleaned up. If we detect such a
2945 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00002946 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00002947 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002948 P->replaceAllUsesWith(V);
2949 P->eraseFromParent();
2950 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00002951 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002952 }
Chris Lattneree588de2011-01-15 07:29:01 +00002953 return false;
2954 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002955
Chris Lattneree588de2011-01-15 07:29:01 +00002956 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002957 // If the source of the cast is a constant, then this should have
2958 // already been constant folded. The only reason NOT to constant fold
2959 // it is if something (e.g. LSR) was careful to place the constant
2960 // evaluation in a block other than then one that uses it (e.g. to hoist
2961 // the address of globals out of a loop). If this is the case, we don't
2962 // want to forward-subst the cast.
2963 if (isa<Constant>(CI->getOperand(0)))
2964 return false;
2965
Chris Lattneree588de2011-01-15 07:29:01 +00002966 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2967 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002968
Chris Lattneree588de2011-01-15 07:29:01 +00002969 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00002970 /// Sink a zext or sext into its user blocks if the target type doesn't
2971 /// fit in one register
2972 if (TLI && TLI->getTypeAction(CI->getContext(),
2973 TLI->getValueType(CI->getType())) ==
2974 TargetLowering::TypeExpandInteger) {
2975 return SinkCast(CI);
2976 } else {
2977 bool MadeChange = MoveExtToFormExtLoad(I);
2978 return MadeChange | OptimizeExtUses(I);
2979 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002980 }
Chris Lattneree588de2011-01-15 07:29:01 +00002981 return false;
2982 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002983
Chris Lattneree588de2011-01-15 07:29:01 +00002984 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00002985 if (!TLI || !TLI->hasMultipleConditionRegisters())
2986 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002987
Chris Lattneree588de2011-01-15 07:29:01 +00002988 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002989 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00002990 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2991 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00002992 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002993
Chris Lattneree588de2011-01-15 07:29:01 +00002994 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002995 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00002996 return OptimizeMemoryInst(I, SI->getOperand(1),
2997 SI->getOperand(0)->getType());
2998 return false;
2999 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003000
Chris Lattneree588de2011-01-15 07:29:01 +00003001 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003002 if (GEPI->hasAllZeroIndices()) {
3003 /// The GEP operand must be a pointer, so must its result -> BitCast
3004 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3005 GEPI->getName(), GEPI);
3006 GEPI->replaceAllUsesWith(NC);
3007 GEPI->eraseFromParent();
3008 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003009 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00003010 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003011 }
Chris Lattneree588de2011-01-15 07:29:01 +00003012 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003013 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003014
Chris Lattneree588de2011-01-15 07:29:01 +00003015 if (CallInst *CI = dyn_cast<CallInst>(I))
3016 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003017
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003018 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3019 return OptimizeSelectInst(SI);
3020
Tim Northoveraeb8e062014-02-19 10:02:43 +00003021 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3022 return OptimizeShuffleVectorInst(SVI);
3023
Chris Lattneree588de2011-01-15 07:29:01 +00003024 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003025}
3026
Chris Lattnerf2836d12007-03-31 04:06:36 +00003027// In this pass we look for GEP and cast instructions that are used
3028// across basic blocks and rewrite them to improve basic-block-at-a-time
3029// selection.
3030bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00003031 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00003032 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00003033
Chris Lattner7a277142011-01-15 07:14:54 +00003034 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00003035 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00003036 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003037
Benjamin Kramer455fa352012-11-23 19:17:06 +00003038 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3039
Chris Lattnerf2836d12007-03-31 04:06:36 +00003040 return MadeChange;
3041}
Devang Patel53771ba2011-08-18 00:50:51 +00003042
3043// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00003044// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00003045// find a node corresponding to the value.
3046bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3047 bool MadeChange = false;
3048 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
Craig Topperc0196b12014-04-14 00:51:57 +00003049 Instruction *PrevNonDbgInst = nullptr;
Devang Patel53771ba2011-08-18 00:50:51 +00003050 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3051 Instruction *Insn = BI; ++BI;
3052 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3053 if (!DVI) {
3054 PrevNonDbgInst = Insn;
3055 continue;
3056 }
3057
3058 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3059 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3060 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3061 DVI->removeFromParent();
3062 if (isa<PHINode>(VI))
3063 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3064 else
3065 DVI->insertAfter(VI);
3066 MadeChange = true;
3067 ++NumDbgValueMoved;
3068 }
3069 }
3070 }
3071 return MadeChange;
3072}
Tim Northovercea0abb2014-03-29 08:22:29 +00003073
3074// If there is a sequence that branches based on comparing a single bit
3075// against zero that can be combined into a single instruction, and the
3076// target supports folding these into a single instruction, sink the
3077// mask and compare into the branch uses. Do this before OptimizeBlock ->
3078// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3079// searched for.
3080bool CodeGenPrepare::sinkAndCmp(Function &F) {
3081 if (!EnableAndCmpSinking)
3082 return false;
3083 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3084 return false;
3085 bool MadeChange = false;
3086 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3087 BasicBlock *BB = I++;
3088
3089 // Does this BB end with the following?
3090 // %andVal = and %val, #single-bit-set
3091 // %icmpVal = icmp %andResult, 0
3092 // br i1 %cmpVal label %dest1, label %dest2"
3093 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3094 if (!Brcc || !Brcc->isConditional())
3095 continue;
3096 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3097 if (!Cmp || Cmp->getParent() != BB)
3098 continue;
3099 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3100 if (!Zero || !Zero->isZero())
3101 continue;
3102 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3103 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3104 continue;
3105 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3106 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3107 continue;
3108 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3109
3110 // Push the "and; icmp" for any users that are conditional branches.
3111 // Since there can only be one branch use per BB, we don't need to keep
3112 // track of which BBs we insert into.
3113 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3114 UI != E; ) {
3115 Use &TheUse = *UI;
3116 // Find brcc use.
3117 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3118 ++UI;
3119 if (!BrccUser || !BrccUser->isConditional())
3120 continue;
3121 BasicBlock *UserBB = BrccUser->getParent();
3122 if (UserBB == BB) continue;
3123 DEBUG(dbgs() << "found Brcc use\n");
3124
3125 // Sink the "and; icmp" to use.
3126 MadeChange = true;
3127 BinaryOperator *NewAnd =
3128 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3129 BrccUser);
3130 CmpInst *NewCmp =
3131 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3132 "", BrccUser);
3133 TheUse = NewCmp;
3134 ++NumAndCmpsMoved;
3135 DEBUG(BrccUser->getParent()->dump());
3136 }
3137 }
3138 return MadeChange;
3139}