blob: 9765485b5d51de34011b763d3f85eb419113218b [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"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000044#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000046using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000047using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000048
Cameron Zwarichced753f2011-01-05 17:27:27 +000049STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000050STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
51STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000052STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
53 "sunken Cmps");
54STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
55 "of sunken Casts");
56STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
57 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000058STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
60STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000061STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000062STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000063STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000064
Cameron Zwarich338d3622011-03-11 21:52:04 +000065static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
68
Benjamin Kramer3d38c172012-05-06 14:25:16 +000069static cl::opt<bool> DisableSelectToBranch(
70 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
71 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000072
Tim Northovercea0abb2014-03-29 08:22:29 +000073static cl::opt<bool> EnableAndCmpSinking(
74 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
75 cl::desc("Enable sinkinig and/cmp into branches."));
76
Eric Christopherc1ea1492008-09-24 05:32:41 +000077namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000078typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
79typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
80
Chris Lattner2dd09db2009-09-02 06:11:42 +000081 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000082 /// TLI - Keep a pointer of a TargetLowering to consult for determining
83 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +000084 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +000085 const TargetLowering *TLI;
Chad Rosierc24b86f2011-12-01 03:08:23 +000086 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +000087 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +000088
Chris Lattner7a277142011-01-15 07:14:54 +000089 /// CurInstIterator - As we scan instructions optimizing them, this is the
90 /// next instruction to optimize. Xforms that can invalidate this should
91 /// update it.
92 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +000093
Evan Cheng0663f232011-03-21 01:19:09 +000094 /// Keeps track of non-local addresses that have been sunk into a block.
95 /// This allows us to avoid inserting duplicate code for blocks with
96 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +000097 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +000098
Quentin Colombet3a4bf042014-02-06 21:44:56 +000099 /// Keeps track of all truncates inserted for the current function.
100 SetOfInstrs InsertedTruncsSet;
101 /// Keeps track of the type of the related instruction before their
102 /// promotion for the current function.
103 InstrToOrigTy PromotedInsts;
104
Devang Patel8f606d72011-03-24 15:35:25 +0000105 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000106 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000107 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000108
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000109 /// OptSize - True if optimizing for size.
110 bool OptSize;
111
Chris Lattnerf2836d12007-03-31 04:06:36 +0000112 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000113 static char ID; // Pass identification, replacement for typeid
Bill Wendling7a639ea2013-06-19 21:07:11 +0000114 explicit CodeGenPrepare(const TargetMachine *TM = 0)
115 : FunctionPass(ID), TM(TM), TLI(0) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000116 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
117 }
Craig Topper4584cd52014-03-07 09:26:03 +0000118 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000119
Craig Topper4584cd52014-03-07 09:26:03 +0000120 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000121
Craig Topper4584cd52014-03-07 09:26:03 +0000122 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000123 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000124 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000125 }
126
Chris Lattnerf2836d12007-03-31 04:06:36 +0000127 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000128 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000129 bool EliminateMostlyEmptyBlocks(Function &F);
130 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
131 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000132 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000133 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000134 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000135 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000136 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000137 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000138 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000139 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000140 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000141 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000142 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000143 bool sinkAndCmp(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000144 };
145}
Devang Patel09f162c2007-05-01 21:15:47 +0000146
Devang Patel8c78a0b2007-05-03 01:11:54 +0000147char CodeGenPrepare::ID = 0;
Quentin Colombetdc0b2ea2014-01-16 21:44:34 +0000148static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
149 initializeTargetLibraryInfoPass(Registry);
150 PassInfo *PI = new PassInfo(
151 "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
152 PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
153 PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
154 Registry.registerPass(*PI, true);
155 return PI;
156}
157
158void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
159 CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
160}
Chris Lattnerf2836d12007-03-31 04:06:36 +0000161
Bill Wendling7a639ea2013-06-19 21:07:11 +0000162FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
163 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000164}
165
Chris Lattnerf2836d12007-03-31 04:06:36 +0000166bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000167 if (skipOptnoneFunction(F))
168 return false;
169
Chris Lattnerf2836d12007-03-31 04:06:36 +0000170 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000171 // Clear per function information.
172 InsertedTruncsSet.clear();
173 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000174
Devang Patel8f606d72011-03-24 15:35:25 +0000175 ModifiedDT = false;
Bill Wendling7a639ea2013-06-19 21:07:11 +0000176 if (TM) TLI = TM->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000177 TLInfo = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000178 DominatorTreeWrapperPass *DTWP =
179 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
180 DT = DTWP ? &DTWP->getDomTree() : 0;
Bill Wendling698e84f2012-12-30 10:32:01 +0000181 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
182 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000183
Preston Gurdcdf540d2012-09-04 18:22:17 +0000184 /// This optimization identifies DIV instructions that can be
185 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000186 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000187 const DenseMap<unsigned int, unsigned int> &BypassWidths =
188 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000189 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000190 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000191 }
192
193 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000194 // unconditional branch.
195 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000196
Devang Patel53771ba2011-08-18 00:50:51 +0000197 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000198 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000199 // find a node corresponding to the value.
200 EverMadeChange |= PlaceDbgValues(F);
201
Tim Northovercea0abb2014-03-29 08:22:29 +0000202 // If there is a mask, compare against zero, and branch that can be combined
203 // into a single target instruction, push the mask and compare into branch
204 // users. Do this before OptimizeBlock -> OptimizeInst ->
205 // OptimizeCmpExpression, which perturbs the pattern being searched for.
206 if (!DisableBranchOpts)
207 EverMadeChange |= sinkAndCmp(F);
208
Chris Lattnerc3748562007-04-02 01:35:34 +0000209 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000210 while (MadeChange) {
211 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000212 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000213 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000214 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000215 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000216 EverMadeChange |= MadeChange;
217 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000218
219 SunkAddrs.clear();
220
Cameron Zwarich338d3622011-03-11 21:52:04 +0000221 if (!DisableBranchOpts) {
222 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000223 SmallPtrSet<BasicBlock*, 8> WorkList;
224 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
225 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000226 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000227 if (!MadeChange) continue;
228
229 for (SmallVectorImpl<BasicBlock*>::iterator
230 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
231 if (pred_begin(*II) == pred_end(*II))
232 WorkList.insert(*II);
233 }
234
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000235 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000236 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000237 while (!WorkList.empty()) {
238 BasicBlock *BB = *WorkList.begin();
239 WorkList.erase(BB);
240 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
241
242 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000243
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000244 for (SmallVectorImpl<BasicBlock*>::iterator
245 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
246 if (pred_begin(*II) == pred_end(*II))
247 WorkList.insert(*II);
248 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000249
Nadav Rotem70409992012-08-14 05:19:07 +0000250 // Merge pairs of basic blocks with unconditional branches, connected by
251 // a single edge.
252 if (EverMadeChange || MadeChange)
253 MadeChange |= EliminateFallThrough(F);
254
Evan Cheng0663f232011-03-21 01:19:09 +0000255 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000256 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000257 EverMadeChange |= MadeChange;
258 }
259
Devang Patel8f606d72011-03-24 15:35:25 +0000260 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000261 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000262
Chris Lattnerf2836d12007-03-31 04:06:36 +0000263 return EverMadeChange;
264}
265
Nadav Rotem70409992012-08-14 05:19:07 +0000266/// EliminateFallThrough - Merge basic blocks which are connected
267/// by a single edge, where one of the basic blocks has a single successor
268/// pointing to the other basic block, which has a single predecessor.
269bool CodeGenPrepare::EliminateFallThrough(Function &F) {
270 bool Changed = false;
271 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000272 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000273 BasicBlock *BB = I++;
274 // If the destination block has a single pred, then this is a trivial
275 // edge, just collapse it.
276 BasicBlock *SinglePred = BB->getSinglePredecessor();
277
Evan Cheng64a223a2012-09-28 23:58:57 +0000278 // Don't merge if BB's address is taken.
279 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000280
281 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
282 if (Term && !Term->isConditional()) {
283 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000284 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000285 // Remember if SinglePred was the entry block of the function.
286 // If so, we will need to move BB back to the entry position.
287 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
288 MergeBasicBlockIntoOnlyPred(BB, this);
289
290 if (isEntry && BB != &BB->getParent()->getEntryBlock())
291 BB->moveBefore(&BB->getParent()->getEntryBlock());
292
293 // We have erased a block. Update the iterator.
294 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000295 }
296 }
297 return Changed;
298}
299
Dale Johannesen4026b042009-03-27 01:13:37 +0000300/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
301/// debug info directives, and an unconditional branch. Passes before isel
302/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
303/// isel. Start by eliminating these blocks so we can split them the way we
304/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000305bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
306 bool MadeChange = false;
307 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000308 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000309 BasicBlock *BB = I++;
310
311 // If this block doesn't end with an uncond branch, ignore it.
312 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
313 if (!BI || !BI->isUnconditional())
314 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000315
Dale Johannesen4026b042009-03-27 01:13:37 +0000316 // If the instruction before the branch (skipping debug info) isn't a phi
317 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000318 BasicBlock::iterator BBI = BI;
319 if (BBI != BB->begin()) {
320 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000321 while (isa<DbgInfoIntrinsic>(BBI)) {
322 if (BBI == BB->begin())
323 break;
324 --BBI;
325 }
326 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
327 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000328 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000329
Chris Lattnerc3748562007-04-02 01:35:34 +0000330 // Do not break infinite loops.
331 BasicBlock *DestBB = BI->getSuccessor(0);
332 if (DestBB == BB)
333 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000334
Chris Lattnerc3748562007-04-02 01:35:34 +0000335 if (!CanMergeBlocks(BB, DestBB))
336 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000337
Chris Lattnerc3748562007-04-02 01:35:34 +0000338 EliminateMostlyEmptyBlock(BB);
339 MadeChange = true;
340 }
341 return MadeChange;
342}
343
344/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
345/// single uncond branch between them, and BB contains no other non-phi
346/// instructions.
347bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
348 const BasicBlock *DestBB) const {
349 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
350 // the successor. If there are more complex condition (e.g. preheaders),
351 // don't mess around with them.
352 BasicBlock::const_iterator BBI = BB->begin();
353 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000354 for (const User *U : PN->users()) {
355 const Instruction *UI = cast<Instruction>(U);
356 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000357 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000358 // If User is inside DestBB block and it is a PHINode then check
359 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000360 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000361 if (UI->getParent() == DestBB) {
362 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000363 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
364 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
365 if (Insn && Insn->getParent() == BB &&
366 Insn->getParent() != UPN->getIncomingBlock(I))
367 return false;
368 }
369 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000370 }
371 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000372
Chris Lattnerc3748562007-04-02 01:35:34 +0000373 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
374 // and DestBB may have conflicting incoming values for the block. If so, we
375 // can't merge the block.
376 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
377 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000378
Chris Lattnerc3748562007-04-02 01:35:34 +0000379 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000380 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000381 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
382 // It is faster to get preds from a PHI than with pred_iterator.
383 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
384 BBPreds.insert(BBPN->getIncomingBlock(i));
385 } else {
386 BBPreds.insert(pred_begin(BB), pred_end(BB));
387 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000388
Chris Lattnerc3748562007-04-02 01:35:34 +0000389 // Walk the preds of DestBB.
390 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
391 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
392 if (BBPreds.count(Pred)) { // Common predecessor?
393 BBI = DestBB->begin();
394 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
395 const Value *V1 = PN->getIncomingValueForBlock(Pred);
396 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000397
Chris Lattnerc3748562007-04-02 01:35:34 +0000398 // If V2 is a phi node in BB, look up what the mapped value will be.
399 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
400 if (V2PN->getParent() == BB)
401 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000402
Chris Lattnerc3748562007-04-02 01:35:34 +0000403 // If there is a conflict, bail out.
404 if (V1 != V2) return false;
405 }
406 }
407 }
408
409 return true;
410}
411
412
413/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
414/// an unconditional branch in it.
415void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
416 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
417 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000418
David Greene74e2d492010-01-05 01:27:11 +0000419 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000420
Chris Lattnerc3748562007-04-02 01:35:34 +0000421 // If the destination block has a single pred, then this is a trivial edge,
422 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000423 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000424 if (SinglePred != DestBB) {
425 // Remember if SinglePred was the entry block of the function. If so, we
426 // will need to move BB back to the entry position.
427 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000428 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000429
Chris Lattner8a172da2008-11-28 19:54:49 +0000430 if (isEntry && BB != &BB->getParent()->getEntryBlock())
431 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000432
David Greene74e2d492010-01-05 01:27:11 +0000433 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000434 return;
435 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000436 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000437
Chris Lattnerc3748562007-04-02 01:35:34 +0000438 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
439 // to handle the new incoming edges it is about to have.
440 PHINode *PN;
441 for (BasicBlock::iterator BBI = DestBB->begin();
442 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
443 // Remove the incoming value for BB, and remember it.
444 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000445
Chris Lattnerc3748562007-04-02 01:35:34 +0000446 // Two options: either the InVal is a phi node defined in BB or it is some
447 // value that dominates BB.
448 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
449 if (InValPhi && InValPhi->getParent() == BB) {
450 // Add all of the input values of the input PHI as inputs of this phi.
451 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
452 PN->addIncoming(InValPhi->getIncomingValue(i),
453 InValPhi->getIncomingBlock(i));
454 } else {
455 // Otherwise, add one instance of the dominating value for each edge that
456 // we will be adding.
457 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
458 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
459 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
460 } else {
461 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
462 PN->addIncoming(InVal, *PI);
463 }
464 }
465 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000466
Chris Lattnerc3748562007-04-02 01:35:34 +0000467 // The PHIs are now updated, change everything that refers to BB to use
468 // DestBB and remove BB.
469 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000470 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000471 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
472 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
473 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
474 DT->changeImmediateDominator(DestBB, NewIDom);
475 DT->eraseNode(BB);
476 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000477 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000478 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000479
David Greene74e2d492010-01-05 01:27:11 +0000480 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000481}
482
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000483/// SinkCast - Sink the specified cast instruction into its user blocks
484static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000485 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000486
Chris Lattnerf2836d12007-03-31 04:06:36 +0000487 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000488 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000489
Chris Lattnerf2836d12007-03-31 04:06:36 +0000490 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000491 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000492 UI != E; ) {
493 Use &TheUse = UI.getUse();
494 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000495
Chris Lattnerf2836d12007-03-31 04:06:36 +0000496 // Figure out which BB this cast is used in. For PHI's this is the
497 // appropriate predecessor block.
498 BasicBlock *UserBB = User->getParent();
499 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000500 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000501 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000502
Chris Lattnerf2836d12007-03-31 04:06:36 +0000503 // Preincrement use iterator so we don't invalidate it.
504 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000505
Chris Lattnerf2836d12007-03-31 04:06:36 +0000506 // If this user is in the same block as the cast, don't change the cast.
507 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000508
Chris Lattnerf2836d12007-03-31 04:06:36 +0000509 // If we have already inserted a cast into this block, use it.
510 CastInst *&InsertedCast = InsertedCasts[UserBB];
511
512 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000513 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000514 InsertedCast =
515 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000516 InsertPt);
517 MadeChange = true;
518 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000519
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000520 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000521 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000522 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000523 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000524
Chris Lattnerf2836d12007-03-31 04:06:36 +0000525 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000526 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000527 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000528 MadeChange = true;
529 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000530
Chris Lattnerf2836d12007-03-31 04:06:36 +0000531 return MadeChange;
532}
533
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000534/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
535/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
536/// sink it into user blocks to reduce the number of virtual
537/// registers that must be created and coalesced.
538///
539/// Return true if any changes are made.
540///
541static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
542 // If this is a noop copy,
543 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
544 EVT DstVT = TLI.getValueType(CI->getType());
545
546 // This is an fp<->int conversion?
547 if (SrcVT.isInteger() != DstVT.isInteger())
548 return false;
549
550 // If this is an extension, it will be a zero or sign extension, which
551 // isn't a noop.
552 if (SrcVT.bitsLT(DstVT)) return false;
553
554 // If these values will be promoted, find out what they will be promoted
555 // to. This helps us consider truncates on PPC as noop copies when they
556 // are.
557 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
558 TargetLowering::TypePromoteInteger)
559 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
560 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
561 TargetLowering::TypePromoteInteger)
562 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
563
564 // If, after promotion, these are the same types, this is a noop copy.
565 if (SrcVT != DstVT)
566 return false;
567
568 return SinkCast(CI);
569}
570
Eric Christopherc1ea1492008-09-24 05:32:41 +0000571/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000572/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000573/// a clear win except on targets with multiple condition code registers
574/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000575///
576/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000577static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000578 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000579
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000580 /// InsertedCmp - Only insert a cmp in each block once.
581 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000582
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000583 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000584 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000585 UI != E; ) {
586 Use &TheUse = UI.getUse();
587 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000588
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000589 // Preincrement use iterator so we don't invalidate it.
590 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000591
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000592 // Don't bother for PHI nodes.
593 if (isa<PHINode>(User))
594 continue;
595
596 // Figure out which BB this cmp is used in.
597 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000598
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000599 // If this user is in the same block as the cmp, don't change the cmp.
600 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000601
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000602 // If we have already inserted a cmp into this block, use it.
603 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
604
605 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000606 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000607 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000608 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000609 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000610 CI->getOperand(1), "", InsertPt);
611 MadeChange = true;
612 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000613
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000614 // Replace a use of the cmp with a use of the new cmp.
615 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000616 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000617 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000618
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000619 // If we removed all uses, nuke the cmp.
620 if (CI->use_empty())
621 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000622
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000623 return MadeChange;
624}
625
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000626namespace {
627class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
628protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000629 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000630 CI->replaceAllUsesWith(With);
631 CI->eraseFromParent();
632 }
Craig Topper4584cd52014-03-07 09:26:03 +0000633 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000634 if (ConstantInt *SizeCI =
635 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
636 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000637 return false;
638 }
639};
640} // end anonymous namespace
641
Eric Christopher4b7948e2010-03-11 02:41:03 +0000642bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000643 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000644
Chris Lattner7a277142011-01-15 07:14:54 +0000645 // Lower inline assembly if we can.
646 // If we found an inline asm expession, and if the target knows how to
647 // lower it to normal LLVM code, do so now.
648 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
649 if (TLI->ExpandInlineAsm(CI)) {
650 // Avoid invalidating the iterator.
651 CurInstIterator = BB->begin();
652 // Avoid processing instructions out of order, which could cause
653 // reuse before a value is defined.
654 SunkAddrs.clear();
655 return true;
656 }
657 // Sink address computing for memory operands into the block.
658 if (OptimizeInlineAsmInst(CI))
659 return true;
660 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000661
Eric Christopher4b7948e2010-03-11 02:41:03 +0000662 // Lower all uses of llvm.objectsize.*
663 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
664 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000665 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000666 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000667 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
668
Chris Lattner1b93be52011-01-15 07:25:29 +0000669 // Substituting this can cause recursive simplifications, which can
670 // invalidate our iterator. Use a WeakVH to hold onto it in case this
671 // happens.
672 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000673
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000674 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000675 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000676
677 // If the iterator instruction was recursively deleted, start over at the
678 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000679 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000680 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000681 SunkAddrs.clear();
682 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000683 return true;
684 }
685
Pete Cooper615fd892012-03-13 20:59:56 +0000686 if (II && TLI) {
687 SmallVector<Value*, 2> PtrOps;
688 Type *AccessTy;
689 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
690 while (!PtrOps.empty())
691 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
692 return true;
693 }
694
Eric Christopher4b7948e2010-03-11 02:41:03 +0000695 // From here on out we're working with named functions.
696 if (CI->getCalledFunction() == 0) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000697
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000698 // We'll need DataLayout from here on out.
699 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000700 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000701
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000702 // Lower all default uses of _chk calls. This is very similar
703 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000704 // that have the default "don't know" as the objectsize. Anything else
705 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000706 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000707 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000708}
Chris Lattner1b93be52011-01-15 07:25:29 +0000709
Evan Cheng0663f232011-03-21 01:19:09 +0000710/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
711/// instructions to the predecessor to enable tail call optimizations. The
712/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000713/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000714/// bb0:
715/// %tmp0 = tail call i32 @f0()
716/// br label %return
717/// bb1:
718/// %tmp1 = tail call i32 @f1()
719/// br label %return
720/// bb2:
721/// %tmp2 = tail call i32 @f2()
722/// br label %return
723/// return:
724/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
725/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000726/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000727///
728/// =>
729///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000730/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000731/// bb0:
732/// %tmp0 = tail call i32 @f0()
733/// ret i32 %tmp0
734/// bb1:
735/// %tmp1 = tail call i32 @f1()
736/// ret i32 %tmp1
737/// bb2:
738/// %tmp2 = tail call i32 @f2()
739/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000740/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000741bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000742 if (!TLI)
743 return false;
744
Benjamin Kramer455fa352012-11-23 19:17:06 +0000745 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
746 if (!RI)
747 return false;
748
Evan Cheng249716e2012-07-27 21:21:26 +0000749 PHINode *PN = 0;
750 BitCastInst *BCI = 0;
Evan Cheng0663f232011-03-21 01:19:09 +0000751 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000752 if (V) {
753 BCI = dyn_cast<BitCastInst>(V);
754 if (BCI)
755 V = BCI->getOperand(0);
756
757 PN = dyn_cast<PHINode>(V);
758 if (!PN)
759 return false;
760 }
Evan Cheng0663f232011-03-21 01:19:09 +0000761
Cameron Zwarich4649f172011-03-24 04:52:10 +0000762 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000763 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000764
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000765 // It's not safe to eliminate the sign / zero extension of the return value.
766 // See llvm::isInTailCallPosition().
767 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000768 AttributeSet CallerAttrs = F->getAttributes();
769 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
770 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000771 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000772
Cameron Zwarich4649f172011-03-24 04:52:10 +0000773 // Make sure there are no instructions between the PHI and return, or that the
774 // return is the first instruction in the block.
775 if (PN) {
776 BasicBlock::iterator BI = BB->begin();
777 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000778 if (&*BI == BCI)
779 // Also skip over the bitcast.
780 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000781 if (&*BI != RI)
782 return false;
783 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000784 BasicBlock::iterator BI = BB->begin();
785 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
786 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000787 return false;
788 }
Evan Cheng0663f232011-03-21 01:19:09 +0000789
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000790 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
791 /// call.
792 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000793 if (PN) {
794 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
795 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
796 // Make sure the phi value is indeed produced by the tail call.
797 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
798 TLI->mayBeEmittedAsTailCall(CI))
799 TailCalls.push_back(CI);
800 }
801 } else {
802 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
803 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
804 if (!VisitedBBs.insert(*PI))
805 continue;
806
807 BasicBlock::InstListType &InstList = (*PI)->getInstList();
808 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
809 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000810 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
811 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000812 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000813
Cameron Zwarich4649f172011-03-24 04:52:10 +0000814 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +0000815 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000816 TailCalls.push_back(CI);
817 }
Evan Cheng0663f232011-03-21 01:19:09 +0000818 }
819
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000820 bool Changed = false;
821 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
822 CallInst *CI = TailCalls[i];
823 CallSite CS(CI);
824
825 // Conservatively require the attributes of the call to match those of the
826 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +0000827 AttributeSet CalleeAttrs = CS.getAttributes();
828 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000829 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +0000830 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000831 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000832 continue;
833
834 // Make sure the call instruction is followed by an unconditional branch to
835 // the return block.
836 BasicBlock *CallBB = CI->getParent();
837 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
838 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
839 continue;
840
841 // Duplicate the return into CallBB.
842 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000843 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000844 ++NumRetsDup;
845 }
846
847 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +0000848 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000849 BB->eraseFromParent();
850
851 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +0000852}
853
Chris Lattner728f9022008-11-25 07:09:13 +0000854//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +0000855// Memory Optimization
856//===----------------------------------------------------------------------===//
857
Chandler Carruthc8925912013-01-05 02:09:22 +0000858namespace {
859
860/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
861/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +0000862struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +0000863 Value *BaseReg;
864 Value *ScaledReg;
865 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
866 void print(raw_ostream &OS) const;
867 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +0000868
Chandler Carruthc8925912013-01-05 02:09:22 +0000869 bool operator==(const ExtAddrMode& O) const {
870 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
871 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
872 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
873 }
874};
875
Eli Friedmanc1f1f852013-09-10 23:09:24 +0000876#ifndef NDEBUG
877static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
878 AM.print(OS);
879 return OS;
880}
881#endif
882
Chandler Carruthc8925912013-01-05 02:09:22 +0000883void ExtAddrMode::print(raw_ostream &OS) const {
884 bool NeedPlus = false;
885 OS << "[";
886 if (BaseGV) {
887 OS << (NeedPlus ? " + " : "")
888 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000889 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000890 NeedPlus = true;
891 }
892
893 if (BaseOffs)
894 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
895
896 if (BaseReg) {
897 OS << (NeedPlus ? " + " : "")
898 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000899 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000900 NeedPlus = true;
901 }
902 if (Scale) {
903 OS << (NeedPlus ? " + " : "")
904 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000905 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000906 }
907
908 OS << ']';
909}
910
911#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
912void ExtAddrMode::dump() const {
913 print(dbgs());
914 dbgs() << '\n';
915}
916#endif
917
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000918/// \brief This class provides transaction based operation on the IR.
919/// Every change made through this class is recorded in the internal state and
920/// can be undone (rollback) until commit is called.
921class TypePromotionTransaction {
922
923 /// \brief This represents the common interface of the individual transaction.
924 /// Each class implements the logic for doing one specific modification on
925 /// the IR via the TypePromotionTransaction.
926 class TypePromotionAction {
927 protected:
928 /// The Instruction modified.
929 Instruction *Inst;
930
931 public:
932 /// \brief Constructor of the action.
933 /// The constructor performs the related action on the IR.
934 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
935
936 virtual ~TypePromotionAction() {}
937
938 /// \brief Undo the modification done by this action.
939 /// When this method is called, the IR must be in the same state as it was
940 /// before this action was applied.
941 /// \pre Undoing the action works if and only if the IR is in the exact same
942 /// state as it was directly after this action was applied.
943 virtual void undo() = 0;
944
945 /// \brief Advocate every change made by this action.
946 /// When the results on the IR of the action are to be kept, it is important
947 /// to call this function, otherwise hidden information may be kept forever.
948 virtual void commit() {
949 // Nothing to be done, this action is not doing anything.
950 }
951 };
952
953 /// \brief Utility to remember the position of an instruction.
954 class InsertionHandler {
955 /// Position of an instruction.
956 /// Either an instruction:
957 /// - Is the first in a basic block: BB is used.
958 /// - Has a previous instructon: PrevInst is used.
959 union {
960 Instruction *PrevInst;
961 BasicBlock *BB;
962 } Point;
963 /// Remember whether or not the instruction had a previous instruction.
964 bool HasPrevInstruction;
965
966 public:
967 /// \brief Record the position of \p Inst.
968 InsertionHandler(Instruction *Inst) {
969 BasicBlock::iterator It = Inst;
970 HasPrevInstruction = (It != (Inst->getParent()->begin()));
971 if (HasPrevInstruction)
972 Point.PrevInst = --It;
973 else
974 Point.BB = Inst->getParent();
975 }
976
977 /// \brief Insert \p Inst at the recorded position.
978 void insert(Instruction *Inst) {
979 if (HasPrevInstruction) {
980 if (Inst->getParent())
981 Inst->removeFromParent();
982 Inst->insertAfter(Point.PrevInst);
983 } else {
984 Instruction *Position = Point.BB->getFirstInsertionPt();
985 if (Inst->getParent())
986 Inst->moveBefore(Position);
987 else
988 Inst->insertBefore(Position);
989 }
990 }
991 };
992
993 /// \brief Move an instruction before another.
994 class InstructionMoveBefore : public TypePromotionAction {
995 /// Original position of the instruction.
996 InsertionHandler Position;
997
998 public:
999 /// \brief Move \p Inst before \p Before.
1000 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1001 : TypePromotionAction(Inst), Position(Inst) {
1002 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1003 Inst->moveBefore(Before);
1004 }
1005
1006 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001007 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001008 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1009 Position.insert(Inst);
1010 }
1011 };
1012
1013 /// \brief Set the operand of an instruction with a new value.
1014 class OperandSetter : public TypePromotionAction {
1015 /// Original operand of the instruction.
1016 Value *Origin;
1017 /// Index of the modified instruction.
1018 unsigned Idx;
1019
1020 public:
1021 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1022 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1023 : TypePromotionAction(Inst), Idx(Idx) {
1024 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1025 << "for:" << *Inst << "\n"
1026 << "with:" << *NewVal << "\n");
1027 Origin = Inst->getOperand(Idx);
1028 Inst->setOperand(Idx, NewVal);
1029 }
1030
1031 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001032 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001033 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1034 << "for: " << *Inst << "\n"
1035 << "with: " << *Origin << "\n");
1036 Inst->setOperand(Idx, Origin);
1037 }
1038 };
1039
1040 /// \brief Hide the operands of an instruction.
1041 /// Do as if this instruction was not using any of its operands.
1042 class OperandsHider : public TypePromotionAction {
1043 /// The list of original operands.
1044 SmallVector<Value *, 4> OriginalValues;
1045
1046 public:
1047 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1048 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1049 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1050 unsigned NumOpnds = Inst->getNumOperands();
1051 OriginalValues.reserve(NumOpnds);
1052 for (unsigned It = 0; It < NumOpnds; ++It) {
1053 // Save the current operand.
1054 Value *Val = Inst->getOperand(It);
1055 OriginalValues.push_back(Val);
1056 // Set a dummy one.
1057 // We could use OperandSetter here, but that would implied an overhead
1058 // that we are not willing to pay.
1059 Inst->setOperand(It, UndefValue::get(Val->getType()));
1060 }
1061 }
1062
1063 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001064 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001065 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1066 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1067 Inst->setOperand(It, OriginalValues[It]);
1068 }
1069 };
1070
1071 /// \brief Build a truncate instruction.
1072 class TruncBuilder : public TypePromotionAction {
1073 public:
1074 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1075 /// result.
1076 /// trunc Opnd to Ty.
1077 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1078 IRBuilder<> Builder(Opnd);
1079 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1080 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1081 }
1082
1083 /// \brief Get the built instruction.
1084 Instruction *getBuiltInstruction() { return Inst; }
1085
1086 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001087 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001088 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1089 Inst->eraseFromParent();
1090 }
1091 };
1092
1093 /// \brief Build a sign extension instruction.
1094 class SExtBuilder : public TypePromotionAction {
1095 public:
1096 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1097 /// result.
1098 /// sext Opnd to Ty.
1099 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1100 : TypePromotionAction(Inst) {
1101 IRBuilder<> Builder(InsertPt);
1102 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1103 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1104 }
1105
1106 /// \brief Get the built instruction.
1107 Instruction *getBuiltInstruction() { return Inst; }
1108
1109 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001110 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001111 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1112 Inst->eraseFromParent();
1113 }
1114 };
1115
1116 /// \brief Mutate an instruction to another type.
1117 class TypeMutator : public TypePromotionAction {
1118 /// Record the original type.
1119 Type *OrigTy;
1120
1121 public:
1122 /// \brief Mutate the type of \p Inst into \p NewTy.
1123 TypeMutator(Instruction *Inst, Type *NewTy)
1124 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1125 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1126 << "\n");
1127 Inst->mutateType(NewTy);
1128 }
1129
1130 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001131 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001132 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1133 << "\n");
1134 Inst->mutateType(OrigTy);
1135 }
1136 };
1137
1138 /// \brief Replace the uses of an instruction by another instruction.
1139 class UsesReplacer : public TypePromotionAction {
1140 /// Helper structure to keep track of the replaced uses.
1141 struct InstructionAndIdx {
1142 /// The instruction using the instruction.
1143 Instruction *Inst;
1144 /// The index where this instruction is used for Inst.
1145 unsigned Idx;
1146 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1147 : Inst(Inst), Idx(Idx) {}
1148 };
1149
1150 /// Keep track of the original uses (pair Instruction, Index).
1151 SmallVector<InstructionAndIdx, 4> OriginalUses;
1152 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1153
1154 public:
1155 /// \brief Replace all the use of \p Inst by \p New.
1156 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1157 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1158 << "\n");
1159 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001160 for (Use &U : Inst->uses()) {
1161 Instruction *UserI = cast<Instruction>(U.getUser());
1162 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001163 }
1164 // Now, we can replace the uses.
1165 Inst->replaceAllUsesWith(New);
1166 }
1167
1168 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001169 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001170 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1171 for (use_iterator UseIt = OriginalUses.begin(),
1172 EndIt = OriginalUses.end();
1173 UseIt != EndIt; ++UseIt) {
1174 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1175 }
1176 }
1177 };
1178
1179 /// \brief Remove an instruction from the IR.
1180 class InstructionRemover : public TypePromotionAction {
1181 /// Original position of the instruction.
1182 InsertionHandler Inserter;
1183 /// Helper structure to hide all the link to the instruction. In other
1184 /// words, this helps to do as if the instruction was removed.
1185 OperandsHider Hider;
1186 /// Keep track of the uses replaced, if any.
1187 UsesReplacer *Replacer;
1188
1189 public:
1190 /// \brief Remove all reference of \p Inst and optinally replace all its
1191 /// uses with New.
1192 /// \pre If !Inst->use_empty(), then New != NULL
1193 InstructionRemover(Instruction *Inst, Value *New = NULL)
1194 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1195 Replacer(NULL) {
1196 if (New)
1197 Replacer = new UsesReplacer(Inst, New);
1198 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1199 Inst->removeFromParent();
1200 }
1201
1202 ~InstructionRemover() { delete Replacer; }
1203
1204 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001205 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001206
1207 /// \brief Resurrect the instruction and reassign it to the proper uses if
1208 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001209 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001210 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1211 Inserter.insert(Inst);
1212 if (Replacer)
1213 Replacer->undo();
1214 Hider.undo();
1215 }
1216 };
1217
1218public:
1219 /// Restoration point.
1220 /// The restoration point is a pointer to an action instead of an iterator
1221 /// because the iterator may be invalidated but not the pointer.
1222 typedef const TypePromotionAction *ConstRestorationPt;
1223 /// Advocate every changes made in that transaction.
1224 void commit();
1225 /// Undo all the changes made after the given point.
1226 void rollback(ConstRestorationPt Point);
1227 /// Get the current restoration point.
1228 ConstRestorationPt getRestorationPoint() const;
1229
1230 /// \name API for IR modification with state keeping to support rollback.
1231 /// @{
1232 /// Same as Instruction::setOperand.
1233 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1234 /// Same as Instruction::eraseFromParent.
1235 void eraseInstruction(Instruction *Inst, Value *NewVal = NULL);
1236 /// Same as Value::replaceAllUsesWith.
1237 void replaceAllUsesWith(Instruction *Inst, Value *New);
1238 /// Same as Value::mutateType.
1239 void mutateType(Instruction *Inst, Type *NewTy);
1240 /// Same as IRBuilder::createTrunc.
1241 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1242 /// Same as IRBuilder::createSExt.
1243 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1244 /// Same as Instruction::moveBefore.
1245 void moveBefore(Instruction *Inst, Instruction *Before);
1246 /// @}
1247
1248 ~TypePromotionTransaction();
1249
1250private:
1251 /// The ordered list of actions made so far.
1252 SmallVector<TypePromotionAction *, 16> Actions;
1253 typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1254};
1255
1256void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1257 Value *NewVal) {
1258 Actions.push_back(
1259 new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1260}
1261
1262void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1263 Value *NewVal) {
1264 Actions.push_back(
1265 new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1266}
1267
1268void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1269 Value *New) {
1270 Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1271}
1272
1273void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1274 Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1275}
1276
1277Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1278 Type *Ty) {
1279 TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1280 Actions.push_back(TB);
1281 return TB->getBuiltInstruction();
1282}
1283
1284Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1285 Value *Opnd, Type *Ty) {
1286 SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1287 Actions.push_back(SB);
1288 return SB->getBuiltInstruction();
1289}
1290
1291void TypePromotionTransaction::moveBefore(Instruction *Inst,
1292 Instruction *Before) {
1293 Actions.push_back(
1294 new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1295}
1296
1297TypePromotionTransaction::ConstRestorationPt
1298TypePromotionTransaction::getRestorationPoint() const {
1299 return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : NULL;
1300}
1301
1302void TypePromotionTransaction::commit() {
1303 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1304 ++It) {
1305 (*It)->commit();
1306 delete *It;
1307 }
1308 Actions.clear();
1309}
1310
1311void TypePromotionTransaction::rollback(
1312 TypePromotionTransaction::ConstRestorationPt Point) {
1313 while (!Actions.empty() && Point != (*Actions.rbegin())) {
1314 TypePromotionAction *Curr = Actions.pop_back_val();
1315 Curr->undo();
1316 delete Curr;
1317 }
1318}
1319
1320TypePromotionTransaction::~TypePromotionTransaction() {
1321 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1322 delete *It;
1323 Actions.clear();
1324}
Chandler Carruthc8925912013-01-05 02:09:22 +00001325
1326/// \brief A helper class for matching addressing modes.
1327///
1328/// This encapsulates the logic for matching the target-legal addressing modes.
1329class AddressingModeMatcher {
1330 SmallVectorImpl<Instruction*> &AddrModeInsts;
1331 const TargetLowering &TLI;
1332
1333 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1334 /// the memory instruction that we're computing this address for.
1335 Type *AccessTy;
1336 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001337
Chandler Carruthc8925912013-01-05 02:09:22 +00001338 /// AddrMode - This is the addressing mode that we're building up. This is
1339 /// part of the return value of this addressing mode matching stuff.
1340 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001341
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001342 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1343 const SetOfInstrs &InsertedTruncs;
1344 /// A map from the instructions to their type before promotion.
1345 InstrToOrigTy &PromotedInsts;
1346 /// The ongoing transaction where every action should be registered.
1347 TypePromotionTransaction &TPT;
1348
Chandler Carruthc8925912013-01-05 02:09:22 +00001349 /// IgnoreProfitability - This is set to true when we should not do
1350 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1351 /// always returns true.
1352 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001353
Chandler Carruthc8925912013-01-05 02:09:22 +00001354 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1355 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001356 Instruction *MI, ExtAddrMode &AM,
1357 const SetOfInstrs &InsertedTruncs,
1358 InstrToOrigTy &PromotedInsts,
1359 TypePromotionTransaction &TPT)
1360 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1361 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001362 IgnoreProfitability = false;
1363 }
1364public:
Stephen Lin837bba12013-07-15 17:55:02 +00001365
Chandler Carruthc8925912013-01-05 02:09:22 +00001366 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1367 /// give an access type of AccessTy. This returns a list of involved
1368 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001369 /// \p InsertedTruncs The truncate instruction inserted by other
1370 /// CodeGenPrepare
1371 /// optimizations.
1372 /// \p PromotedInsts maps the instructions to their type before promotion.
1373 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001374 static ExtAddrMode Match(Value *V, Type *AccessTy,
1375 Instruction *MemoryInst,
1376 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001377 const TargetLowering &TLI,
1378 const SetOfInstrs &InsertedTruncs,
1379 InstrToOrigTy &PromotedInsts,
1380 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001381 ExtAddrMode Result;
1382
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001383 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1384 MemoryInst, Result, InsertedTruncs,
1385 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001386 (void)Success; assert(Success && "Couldn't select *anything*?");
1387 return Result;
1388 }
1389private:
1390 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1391 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001392 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1393 bool *MovedAway = NULL);
Chandler Carruthc8925912013-01-05 02:09:22 +00001394 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1395 ExtAddrMode &AMBefore,
1396 ExtAddrMode &AMAfter);
1397 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001398 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1399 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001400};
1401
1402/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1403/// Return true and update AddrMode if this addr mode is legal for the target,
1404/// false if not.
1405bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1406 unsigned Depth) {
1407 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1408 // mode. Just process that directly.
1409 if (Scale == 1)
1410 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001411
Chandler Carruthc8925912013-01-05 02:09:22 +00001412 // If the scale is 0, it takes nothing to add this.
1413 if (Scale == 0)
1414 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001415
Chandler Carruthc8925912013-01-05 02:09:22 +00001416 // If we already have a scale of this value, we can add to it, otherwise, we
1417 // need an available scale field.
1418 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1419 return false;
1420
1421 ExtAddrMode TestAddrMode = AddrMode;
1422
1423 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1424 // [A+B + A*7] -> [B+A*8].
1425 TestAddrMode.Scale += Scale;
1426 TestAddrMode.ScaledReg = ScaleReg;
1427
1428 // If the new address isn't legal, bail out.
1429 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1430 return false;
1431
1432 // It was legal, so commit it.
1433 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001434
Chandler Carruthc8925912013-01-05 02:09:22 +00001435 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1436 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1437 // X*Scale + C*Scale to addr mode.
1438 ConstantInt *CI = 0; Value *AddLHS = 0;
1439 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1440 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1441 TestAddrMode.ScaledReg = AddLHS;
1442 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001443
Chandler Carruthc8925912013-01-05 02:09:22 +00001444 // If this addressing mode is legal, commit it and remember that we folded
1445 // this instruction.
1446 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1447 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1448 AddrMode = TestAddrMode;
1449 return true;
1450 }
1451 }
1452
1453 // Otherwise, not (x+c)*scale, just return what we have.
1454 return true;
1455}
1456
1457/// MightBeFoldableInst - This is a little filter, which returns true if an
1458/// addressing computation involving I might be folded into a load/store
1459/// accessing it. This doesn't need to be perfect, but needs to accept at least
1460/// the set of instructions that MatchOperationAddr can.
1461static bool MightBeFoldableInst(Instruction *I) {
1462 switch (I->getOpcode()) {
1463 case Instruction::BitCast:
1464 // Don't touch identity bitcasts.
1465 if (I->getType() == I->getOperand(0)->getType())
1466 return false;
1467 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1468 case Instruction::PtrToInt:
1469 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1470 return true;
1471 case Instruction::IntToPtr:
1472 // We know the input is intptr_t, so this is foldable.
1473 return true;
1474 case Instruction::Add:
1475 return true;
1476 case Instruction::Mul:
1477 case Instruction::Shl:
1478 // Can only handle X*C and X << C.
1479 return isa<ConstantInt>(I->getOperand(1));
1480 case Instruction::GetElementPtr:
1481 return true;
1482 default:
1483 return false;
1484 }
1485}
1486
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001487/// \brief Hepler class to perform type promotion.
1488class TypePromotionHelper {
1489 /// \brief Utility function to check whether or not a sign extension of
1490 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1491 /// using the operands of \p Inst or promoting \p Inst.
1492 /// In other words, check if:
1493 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1494 /// #1 Promotion applies:
1495 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1496 /// #2 Operand reuses:
1497 /// sext opnd1 to ConsideredSExtType.
1498 /// \p PromotedInsts maps the instructions to their type before promotion.
1499 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1500 const InstrToOrigTy &PromotedInsts);
1501
1502 /// \brief Utility function to determine if \p OpIdx should be promoted when
1503 /// promoting \p Inst.
1504 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1505 if (isa<SelectInst>(Inst) && OpIdx == 0)
1506 return false;
1507 return true;
1508 }
1509
1510 /// \brief Utility function to promote the operand of \p SExt when this
1511 /// operand is a promotable trunc or sext.
1512 /// \p PromotedInsts maps the instructions to their type before promotion.
1513 /// \p CreatedInsts[out] contains how many non-free instructions have been
1514 /// created to promote the operand of SExt.
1515 /// Should never be called directly.
1516 /// \return The promoted value which is used instead of SExt.
1517 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1518 TypePromotionTransaction &TPT,
1519 InstrToOrigTy &PromotedInsts,
1520 unsigned &CreatedInsts);
1521
1522 /// \brief Utility function to promote the operand of \p SExt when this
1523 /// operand is promotable and is not a supported trunc or sext.
1524 /// \p PromotedInsts maps the instructions to their type before promotion.
1525 /// \p CreatedInsts[out] contains how many non-free instructions have been
1526 /// created to promote the operand of SExt.
1527 /// Should never be called directly.
1528 /// \return The promoted value which is used instead of SExt.
1529 static Value *promoteOperandForOther(Instruction *SExt,
1530 TypePromotionTransaction &TPT,
1531 InstrToOrigTy &PromotedInsts,
1532 unsigned &CreatedInsts);
1533
1534public:
1535 /// Type for the utility function that promotes the operand of SExt.
1536 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1537 InstrToOrigTy &PromotedInsts,
1538 unsigned &CreatedInsts);
1539 /// \brief Given a sign extend instruction \p SExt, return the approriate
1540 /// action to promote the operand of \p SExt instead of using SExt.
1541 /// \return NULL if no promotable action is possible with the current
1542 /// sign extension.
1543 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1544 /// the others CodeGenPrepare optimizations. This information is important
1545 /// because we do not want to promote these instructions as CodeGenPrepare
1546 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1547 /// \p PromotedInsts maps the instructions to their type before promotion.
1548 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1549 const TargetLowering &TLI,
1550 const InstrToOrigTy &PromotedInsts);
1551};
1552
1553bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1554 Type *ConsideredSExtType,
1555 const InstrToOrigTy &PromotedInsts) {
1556 // We can always get through sext.
1557 if (isa<SExtInst>(Inst))
1558 return true;
1559
1560 // We can get through binary operator, if it is legal. In other words, the
1561 // binary operator must have a nuw or nsw flag.
1562 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1563 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1564 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1565 return true;
1566
1567 // Check if we can do the following simplification.
1568 // sext(trunc(sext)) --> sext
1569 if (!isa<TruncInst>(Inst))
1570 return false;
1571
1572 Value *OpndVal = Inst->getOperand(0);
1573 // Check if we can use this operand in the sext.
1574 // If the type is larger than the result type of the sign extension,
1575 // we cannot.
1576 if (OpndVal->getType()->getIntegerBitWidth() >
1577 ConsideredSExtType->getIntegerBitWidth())
1578 return false;
1579
1580 // If the operand of the truncate is not an instruction, we will not have
1581 // any information on the dropped bits.
1582 // (Actually we could for constant but it is not worth the extra logic).
1583 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1584 if (!Opnd)
1585 return false;
1586
1587 // Check if the source of the type is narrow enough.
1588 // I.e., check that trunc just drops sign extended bits.
1589 // #1 get the type of the operand.
1590 const Type *OpndType;
1591 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1592 if (It != PromotedInsts.end())
1593 OpndType = It->second;
1594 else if (isa<SExtInst>(Opnd))
1595 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1596 else
1597 return false;
1598
1599 // #2 check that the truncate just drop sign extended bits.
1600 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1601 return true;
1602
1603 return false;
1604}
1605
1606TypePromotionHelper::Action TypePromotionHelper::getAction(
1607 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1608 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1609 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1610 Type *SExtTy = SExt->getType();
1611 // If the operand of the sign extension is not an instruction, we cannot
1612 // get through.
1613 // If it, check we can get through.
1614 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1615 return NULL;
1616
1617 // Do not promote if the operand has been added by codegenprepare.
1618 // Otherwise, it means we are undoing an optimization that is likely to be
1619 // redone, thus causing potential infinite loop.
1620 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1621 return NULL;
1622
1623 // SExt or Trunc instructions.
1624 // Return the related handler.
1625 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1626 return promoteOperandForTruncAndSExt;
1627
1628 // Regular instruction.
1629 // Abort early if we will have to insert non-free instructions.
1630 if (!SExtOpnd->hasOneUse() &&
1631 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1632 return NULL;
1633 return promoteOperandForOther;
1634}
1635
1636Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1637 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1638 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1639 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1640 // get through it and this method should not be called.
1641 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1642 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1643 // => sext(opnd).
1644 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1645 CreatedInsts = 0;
1646
1647 // Remove dead code.
1648 if (SExtOpnd->use_empty())
1649 TPT.eraseInstruction(SExtOpnd);
1650
1651 // Check if the sext is still needed.
1652 if (SExt->getType() != SExt->getOperand(0)->getType())
1653 return SExt;
1654
1655 // At this point we have: sext ty opnd to ty.
1656 // Reassign the uses of SExt to the opnd and remove SExt.
1657 Value *NextVal = SExt->getOperand(0);
1658 TPT.eraseInstruction(SExt, NextVal);
1659 return NextVal;
1660}
1661
1662Value *
1663TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1664 TypePromotionTransaction &TPT,
1665 InstrToOrigTy &PromotedInsts,
1666 unsigned &CreatedInsts) {
1667 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1668 // get through it and this method should not be called.
1669 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1670 CreatedInsts = 0;
1671 if (!SExtOpnd->hasOneUse()) {
1672 // SExtOpnd will be promoted.
1673 // All its uses, but SExt, will need to use a truncated value of the
1674 // promoted version.
1675 // Create the truncate now.
1676 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1677 Trunc->removeFromParent();
1678 // Insert it just after the definition.
1679 Trunc->insertAfter(SExtOpnd);
1680
1681 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1682 // Restore the operand of SExt (which has been replace by the previous call
1683 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1684 TPT.setOperand(SExt, 0, SExtOpnd);
1685 }
1686
1687 // Get through the Instruction:
1688 // 1. Update its type.
1689 // 2. Replace the uses of SExt by Inst.
1690 // 3. Sign extend each operand that needs to be sign extended.
1691
1692 // Remember the original type of the instruction before promotion.
1693 // This is useful to know that the high bits are sign extended bits.
1694 PromotedInsts.insert(
1695 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1696 // Step #1.
1697 TPT.mutateType(SExtOpnd, SExt->getType());
1698 // Step #2.
1699 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1700 // Step #3.
1701 Instruction *SExtForOpnd = SExt;
1702
1703 DEBUG(dbgs() << "Propagate SExt to operands\n");
1704 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1705 ++OpIdx) {
1706 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1707 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1708 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1709 DEBUG(dbgs() << "No need to propagate\n");
1710 continue;
1711 }
1712 // Check if we can statically sign extend the operand.
1713 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1714 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1715 DEBUG(dbgs() << "Statically sign extend\n");
1716 TPT.setOperand(
1717 SExtOpnd, OpIdx,
1718 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1719 continue;
1720 }
1721 // UndefValue are typed, so we have to statically sign extend them.
1722 if (isa<UndefValue>(Opnd)) {
1723 DEBUG(dbgs() << "Statically sign extend\n");
1724 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1725 continue;
1726 }
1727
1728 // Otherwise we have to explicity sign extend the operand.
1729 // Check if SExt was reused to sign extend an operand.
1730 if (!SExtForOpnd) {
1731 // If yes, create a new one.
1732 DEBUG(dbgs() << "More operands to sext\n");
1733 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1734 ++CreatedInsts;
1735 }
1736
1737 TPT.setOperand(SExtForOpnd, 0, Opnd);
1738
1739 // Move the sign extension before the insertion point.
1740 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1741 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1742 // If more sext are required, new instructions will have to be created.
1743 SExtForOpnd = NULL;
1744 }
1745 if (SExtForOpnd == SExt) {
1746 DEBUG(dbgs() << "Sign extension is useless now\n");
1747 TPT.eraseInstruction(SExt);
1748 }
1749 return SExtOpnd;
1750}
1751
Quentin Colombet867c5502014-02-14 22:23:22 +00001752/// IsPromotionProfitable - Check whether or not promoting an instruction
1753/// to a wider type was profitable.
1754/// \p MatchedSize gives the number of instructions that have been matched
1755/// in the addressing mode after the promotion was applied.
1756/// \p SizeWithPromotion gives the number of created instructions for
1757/// the promotion plus the number of instructions that have been
1758/// matched in the addressing mode before the promotion.
1759/// \p PromotedOperand is the value that has been promoted.
1760/// \return True if the promotion is profitable, false otherwise.
1761bool
1762AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1763 unsigned SizeWithPromotion,
1764 Value *PromotedOperand) const {
1765 // We folded less instructions than what we created to promote the operand.
1766 // This is not profitable.
1767 if (MatchedSize < SizeWithPromotion)
1768 return false;
1769 if (MatchedSize > SizeWithPromotion)
1770 return true;
1771 // The promotion is neutral but it may help folding the sign extension in
1772 // loads for instance.
1773 // Check that we did not create an illegal instruction.
1774 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1775 if (!PromotedInst)
1776 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00001777 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1778 // If the ISDOpcode is undefined, it was undefined before the promotion.
1779 if (!ISDOpcode)
1780 return true;
1781 // Otherwise, check if the promoted instruction is legal or not.
1782 return TLI.isOperationLegalOrCustom(ISDOpcode,
Quentin Colombet867c5502014-02-14 22:23:22 +00001783 EVT::getEVT(PromotedInst->getType()));
1784}
1785
Chandler Carruthc8925912013-01-05 02:09:22 +00001786/// MatchOperationAddr - Given an instruction or constant expr, see if we can
1787/// fold the operation into the addressing mode. If so, update the addressing
1788/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001789/// If \p MovedAway is not NULL, it contains the information of whether or
1790/// not AddrInst has to be folded into the addressing mode on success.
1791/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1792/// because it has been moved away.
1793/// Thus AddrInst must not be added in the matched instructions.
1794/// This state can happen when AddrInst is a sext, since it may be moved away.
1795/// Therefore, AddrInst may not be valid when MovedAway is true and it must
1796/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00001797bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001798 unsigned Depth,
1799 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001800 // Avoid exponential behavior on extremely deep expression trees.
1801 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001802
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001803 // By default, all matched instructions stay in place.
1804 if (MovedAway)
1805 *MovedAway = false;
1806
Chandler Carruthc8925912013-01-05 02:09:22 +00001807 switch (Opcode) {
1808 case Instruction::PtrToInt:
1809 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1810 return MatchAddr(AddrInst->getOperand(0), Depth);
1811 case Instruction::IntToPtr:
1812 // This inttoptr is a no-op if the integer type is pointer sized.
1813 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00001814 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00001815 return MatchAddr(AddrInst->getOperand(0), Depth);
1816 return false;
1817 case Instruction::BitCast:
1818 // BitCast is always a noop, and we can handle it as long as it is
1819 // int->int or pointer->pointer (we don't want int<->fp or something).
1820 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1821 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1822 // Don't touch identity bitcasts. These were probably put here by LSR,
1823 // and we don't want to mess around with them. Assume it knows what it
1824 // is doing.
1825 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1826 return MatchAddr(AddrInst->getOperand(0), Depth);
1827 return false;
1828 case Instruction::Add: {
1829 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1830 ExtAddrMode BackupAddrMode = AddrMode;
1831 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001832 // Start a transaction at this point.
1833 // The LHS may match but not the RHS.
1834 // Therefore, we need a higher level restoration point to undo partially
1835 // matched operation.
1836 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1837 TPT.getRestorationPoint();
1838
Chandler Carruthc8925912013-01-05 02:09:22 +00001839 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1840 MatchAddr(AddrInst->getOperand(0), Depth+1))
1841 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001842
Chandler Carruthc8925912013-01-05 02:09:22 +00001843 // Restore the old addr mode info.
1844 AddrMode = BackupAddrMode;
1845 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001846 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00001847
Chandler Carruthc8925912013-01-05 02:09:22 +00001848 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1849 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1850 MatchAddr(AddrInst->getOperand(1), Depth+1))
1851 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001852
Chandler Carruthc8925912013-01-05 02:09:22 +00001853 // Otherwise we definitely can't merge the ADD in.
1854 AddrMode = BackupAddrMode;
1855 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001856 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00001857 break;
1858 }
1859 //case Instruction::Or:
1860 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1861 //break;
1862 case Instruction::Mul:
1863 case Instruction::Shl: {
1864 // Can only handle X*C and X << C.
1865 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1866 if (!RHS) return false;
1867 int64_t Scale = RHS->getSExtValue();
1868 if (Opcode == Instruction::Shl)
1869 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001870
Chandler Carruthc8925912013-01-05 02:09:22 +00001871 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1872 }
1873 case Instruction::GetElementPtr: {
1874 // Scan the GEP. We check it if it contains constant offsets and at most
1875 // one variable offset.
1876 int VariableOperand = -1;
1877 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00001878
Chandler Carruthc8925912013-01-05 02:09:22 +00001879 int64_t ConstantOffset = 0;
1880 const DataLayout *TD = TLI.getDataLayout();
1881 gep_type_iterator GTI = gep_type_begin(AddrInst);
1882 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1883 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1884 const StructLayout *SL = TD->getStructLayout(STy);
1885 unsigned Idx =
1886 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1887 ConstantOffset += SL->getElementOffset(Idx);
1888 } else {
1889 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1890 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1891 ConstantOffset += CI->getSExtValue()*TypeSize;
1892 } else if (TypeSize) { // Scales of zero don't do anything.
1893 // We only allow one variable index at the moment.
1894 if (VariableOperand != -1)
1895 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001896
Chandler Carruthc8925912013-01-05 02:09:22 +00001897 // Remember the variable index.
1898 VariableOperand = i;
1899 VariableScale = TypeSize;
1900 }
1901 }
1902 }
Stephen Lin837bba12013-07-15 17:55:02 +00001903
Chandler Carruthc8925912013-01-05 02:09:22 +00001904 // A common case is for the GEP to only do a constant offset. In this case,
1905 // just add it to the disp field and check validity.
1906 if (VariableOperand == -1) {
1907 AddrMode.BaseOffs += ConstantOffset;
1908 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1909 // Check to see if we can fold the base pointer in too.
1910 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1911 return true;
1912 }
1913 AddrMode.BaseOffs -= ConstantOffset;
1914 return false;
1915 }
1916
1917 // Save the valid addressing mode in case we can't match.
1918 ExtAddrMode BackupAddrMode = AddrMode;
1919 unsigned OldSize = AddrModeInsts.size();
1920
1921 // See if the scale and offset amount is valid for this target.
1922 AddrMode.BaseOffs += ConstantOffset;
1923
1924 // Match the base operand of the GEP.
1925 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1926 // If it couldn't be matched, just stuff the value in a register.
1927 if (AddrMode.HasBaseReg) {
1928 AddrMode = BackupAddrMode;
1929 AddrModeInsts.resize(OldSize);
1930 return false;
1931 }
1932 AddrMode.HasBaseReg = true;
1933 AddrMode.BaseReg = AddrInst->getOperand(0);
1934 }
1935
1936 // Match the remaining variable portion of the GEP.
1937 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1938 Depth)) {
1939 // If it couldn't be matched, try stuffing the base into a register
1940 // instead of matching it, and retrying the match of the scale.
1941 AddrMode = BackupAddrMode;
1942 AddrModeInsts.resize(OldSize);
1943 if (AddrMode.HasBaseReg)
1944 return false;
1945 AddrMode.HasBaseReg = true;
1946 AddrMode.BaseReg = AddrInst->getOperand(0);
1947 AddrMode.BaseOffs += ConstantOffset;
1948 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1949 VariableScale, Depth)) {
1950 // If even that didn't work, bail.
1951 AddrMode = BackupAddrMode;
1952 AddrModeInsts.resize(OldSize);
1953 return false;
1954 }
1955 }
1956
1957 return true;
1958 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001959 case Instruction::SExt: {
1960 // Try to move this sext out of the way of the addressing mode.
1961 Instruction *SExt = cast<Instruction>(AddrInst);
1962 // Ask for a method for doing so.
1963 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1964 SExt, InsertedTruncs, TLI, PromotedInsts);
1965 if (!TPH)
1966 return false;
1967
1968 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1969 TPT.getRestorationPoint();
1970 unsigned CreatedInsts = 0;
1971 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1972 // SExt has been moved away.
1973 // Thus either it will be rematched later in the recursive calls or it is
1974 // gone. Anyway, we must not fold it into the addressing mode at this point.
1975 // E.g.,
1976 // op = add opnd, 1
1977 // idx = sext op
1978 // addr = gep base, idx
1979 // is now:
1980 // promotedOpnd = sext opnd <- no match here
1981 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
1982 // addr = gep base, op <- match
1983 if (MovedAway)
1984 *MovedAway = true;
1985
1986 assert(PromotedOperand &&
1987 "TypePromotionHelper should have filtered out those cases");
1988
1989 ExtAddrMode BackupAddrMode = AddrMode;
1990 unsigned OldSize = AddrModeInsts.size();
1991
1992 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00001993 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
1994 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001995 AddrMode = BackupAddrMode;
1996 AddrModeInsts.resize(OldSize);
1997 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
1998 TPT.rollback(LastKnownGood);
1999 return false;
2000 }
2001 return true;
2002 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002003 }
2004 return false;
2005}
2006
2007/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2008/// addressing mode. If Addr can't be added to AddrMode this returns false and
2009/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2010/// or intptr_t for the target.
2011///
2012bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002013 // Start a transaction at this point that we will rollback if the matching
2014 // fails.
2015 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2016 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002017 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2018 // Fold in immediates if legal for the target.
2019 AddrMode.BaseOffs += CI->getSExtValue();
2020 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2021 return true;
2022 AddrMode.BaseOffs -= CI->getSExtValue();
2023 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2024 // If this is a global variable, try to fold it into the addressing mode.
2025 if (AddrMode.BaseGV == 0) {
2026 AddrMode.BaseGV = GV;
2027 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2028 return true;
2029 AddrMode.BaseGV = 0;
2030 }
2031 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2032 ExtAddrMode BackupAddrMode = AddrMode;
2033 unsigned OldSize = AddrModeInsts.size();
2034
2035 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002036 bool MovedAway = false;
2037 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2038 // This instruction may have been move away. If so, there is nothing
2039 // to check here.
2040 if (MovedAway)
2041 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002042 // Okay, it's possible to fold this. Check to see if it is actually
2043 // *profitable* to do so. We use a simple cost model to avoid increasing
2044 // register pressure too much.
2045 if (I->hasOneUse() ||
2046 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2047 AddrModeInsts.push_back(I);
2048 return true;
2049 }
Stephen Lin837bba12013-07-15 17:55:02 +00002050
Chandler Carruthc8925912013-01-05 02:09:22 +00002051 // It isn't profitable to do this, roll back.
2052 //cerr << "NOT FOLDING: " << *I;
2053 AddrMode = BackupAddrMode;
2054 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002055 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002056 }
2057 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2058 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2059 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002060 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002061 } else if (isa<ConstantPointerNull>(Addr)) {
2062 // Null pointer gets folded without affecting the addressing mode.
2063 return true;
2064 }
2065
2066 // Worse case, the target should support [reg] addressing modes. :)
2067 if (!AddrMode.HasBaseReg) {
2068 AddrMode.HasBaseReg = true;
2069 AddrMode.BaseReg = Addr;
2070 // Still check for legality in case the target supports [imm] but not [i+r].
2071 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2072 return true;
2073 AddrMode.HasBaseReg = false;
2074 AddrMode.BaseReg = 0;
2075 }
2076
2077 // If the base register is already taken, see if we can do [r+r].
2078 if (AddrMode.Scale == 0) {
2079 AddrMode.Scale = 1;
2080 AddrMode.ScaledReg = Addr;
2081 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2082 return true;
2083 AddrMode.Scale = 0;
2084 AddrMode.ScaledReg = 0;
2085 }
2086 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002087 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002088 return false;
2089}
2090
2091/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2092/// inline asm call are due to memory operands. If so, return true, otherwise
2093/// return false.
2094static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2095 const TargetLowering &TLI) {
2096 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2097 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2098 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002099
Chandler Carruthc8925912013-01-05 02:09:22 +00002100 // Compute the constraint code and ConstraintType to use.
2101 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2102
2103 // If this asm operand is our Value*, and if it isn't an indirect memory
2104 // operand, we can't fold it!
2105 if (OpInfo.CallOperandVal == OpVal &&
2106 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2107 !OpInfo.isIndirect))
2108 return false;
2109 }
2110
2111 return true;
2112}
2113
2114/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2115/// memory use. If we find an obviously non-foldable instruction, return true.
2116/// Add the ultimately found memory instructions to MemoryUses.
2117static bool FindAllMemoryUses(Instruction *I,
2118 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2119 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2120 const TargetLowering &TLI) {
2121 // If we already considered this instruction, we're done.
2122 if (!ConsideredInsts.insert(I))
2123 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002124
Chandler Carruthc8925912013-01-05 02:09:22 +00002125 // If this is an obviously unfoldable instruction, bail out.
2126 if (!MightBeFoldableInst(I))
2127 return true;
2128
2129 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002130 for (Use &U : I->uses()) {
2131 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002132
Chandler Carruthcdf47882014-03-09 03:16:01 +00002133 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2134 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002135 continue;
2136 }
Stephen Lin837bba12013-07-15 17:55:02 +00002137
Chandler Carruthcdf47882014-03-09 03:16:01 +00002138 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2139 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002140 if (opNo == 0) return true; // Storing addr, not into addr.
2141 MemoryUses.push_back(std::make_pair(SI, opNo));
2142 continue;
2143 }
Stephen Lin837bba12013-07-15 17:55:02 +00002144
Chandler Carruthcdf47882014-03-09 03:16:01 +00002145 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002146 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2147 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002148
Chandler Carruthc8925912013-01-05 02:09:22 +00002149 // If this is a memory operand, we're cool, otherwise bail out.
2150 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2151 return true;
2152 continue;
2153 }
Stephen Lin837bba12013-07-15 17:55:02 +00002154
Chandler Carruthcdf47882014-03-09 03:16:01 +00002155 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002156 return true;
2157 }
2158
2159 return false;
2160}
2161
2162/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2163/// the use site that we're folding it into. If so, there is no cost to
2164/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2165/// that we know are live at the instruction already.
2166bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2167 Value *KnownLive2) {
2168 // If Val is either of the known-live values, we know it is live!
2169 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
2170 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002171
Chandler Carruthc8925912013-01-05 02:09:22 +00002172 // All values other than instructions and arguments (e.g. constants) are live.
2173 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002174
Chandler Carruthc8925912013-01-05 02:09:22 +00002175 // If Val is a constant sized alloca in the entry block, it is live, this is
2176 // true because it is just a reference to the stack/frame pointer, which is
2177 // live for the whole function.
2178 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2179 if (AI->isStaticAlloca())
2180 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002181
Chandler Carruthc8925912013-01-05 02:09:22 +00002182 // Check to see if this value is already used in the memory instruction's
2183 // block. If so, it's already live into the block at the very least, so we
2184 // can reasonably fold it.
2185 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2186}
2187
2188/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2189/// mode of the machine to fold the specified instruction into a load or store
2190/// that ultimately uses it. However, the specified instruction has multiple
2191/// uses. Given this, it may actually increase register pressure to fold it
2192/// into the load. For example, consider this code:
2193///
2194/// X = ...
2195/// Y = X+1
2196/// use(Y) -> nonload/store
2197/// Z = Y+1
2198/// load Z
2199///
2200/// In this case, Y has multiple uses, and can be folded into the load of Z
2201/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2202/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2203/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2204/// number of computations either.
2205///
2206/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2207/// X was live across 'load Z' for other reasons, we actually *would* want to
2208/// fold the addressing mode in the Z case. This would make Y die earlier.
2209bool AddressingModeMatcher::
2210IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2211 ExtAddrMode &AMAfter) {
2212 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002213
Chandler Carruthc8925912013-01-05 02:09:22 +00002214 // AMBefore is the addressing mode before this instruction was folded into it,
2215 // and AMAfter is the addressing mode after the instruction was folded. Get
2216 // the set of registers referenced by AMAfter and subtract out those
2217 // referenced by AMBefore: this is the set of values which folding in this
2218 // address extends the lifetime of.
2219 //
2220 // Note that there are only two potential values being referenced here,
2221 // BaseReg and ScaleReg (global addresses are always available, as are any
2222 // folded immediates).
2223 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002224
Chandler Carruthc8925912013-01-05 02:09:22 +00002225 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2226 // lifetime wasn't extended by adding this instruction.
2227 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2228 BaseReg = 0;
2229 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2230 ScaledReg = 0;
2231
2232 // If folding this instruction (and it's subexprs) didn't extend any live
2233 // ranges, we're ok with it.
2234 if (BaseReg == 0 && ScaledReg == 0)
2235 return true;
2236
2237 // If all uses of this instruction are ultimately load/store/inlineasm's,
2238 // check to see if their addressing modes will include this instruction. If
2239 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2240 // uses.
2241 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2242 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2243 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2244 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002245
Chandler Carruthc8925912013-01-05 02:09:22 +00002246 // Now that we know that all uses of this instruction are part of a chain of
2247 // computation involving only operations that could theoretically be folded
2248 // into a memory use, loop over each of these uses and see if they could
2249 // *actually* fold the instruction.
2250 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2251 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2252 Instruction *User = MemoryUses[i].first;
2253 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002254
Chandler Carruthc8925912013-01-05 02:09:22 +00002255 // Get the access type of this use. If the use isn't a pointer, we don't
2256 // know what it accesses.
2257 Value *Address = User->getOperand(OpNo);
2258 if (!Address->getType()->isPointerTy())
2259 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002260 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002261
Chandler Carruthc8925912013-01-05 02:09:22 +00002262 // Do a match against the root of this address, ignoring profitability. This
2263 // will tell us if the addressing mode for the memory operation will
2264 // *actually* cover the shared instruction.
2265 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002266 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2267 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002268 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002269 MemoryInst, Result, InsertedTruncs,
2270 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002271 Matcher.IgnoreProfitability = true;
2272 bool Success = Matcher.MatchAddr(Address, 0);
2273 (void)Success; assert(Success && "Couldn't select *anything*?");
2274
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002275 // The match was to check the profitability, the changes made are not
2276 // part of the original matcher. Therefore, they should be dropped
2277 // otherwise the original matcher will not present the right state.
2278 TPT.rollback(LastKnownGood);
2279
Chandler Carruthc8925912013-01-05 02:09:22 +00002280 // If the match didn't cover I, then it won't be shared by it.
2281 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2282 I) == MatchedAddrModeInsts.end())
2283 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002284
Chandler Carruthc8925912013-01-05 02:09:22 +00002285 MatchedAddrModeInsts.clear();
2286 }
Stephen Lin837bba12013-07-15 17:55:02 +00002287
Chandler Carruthc8925912013-01-05 02:09:22 +00002288 return true;
2289}
2290
2291} // end anonymous namespace
2292
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002293/// IsNonLocalValue - Return true if the specified values are defined in a
2294/// different basic block than BB.
2295static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2296 if (Instruction *I = dyn_cast<Instruction>(V))
2297 return I->getParent() != BB;
2298 return false;
2299}
2300
Bob Wilson53bdae32009-12-03 21:47:07 +00002301/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002302/// addressing modes that can do significant amounts of computation. As such,
2303/// instruction selection will try to get the load or store to do as much
2304/// computation as possible for the program. The problem is that isel can only
2305/// see within a single block. As such, we sink as much legal addressing mode
2306/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002307///
2308/// This method is used to optimize both load/store and inline asms with memory
2309/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002310bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002311 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002312 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002313
2314 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002315 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002316 SmallVector<Value*, 8> worklist;
2317 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002318 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002319
Owen Anderson8ba5f392010-11-27 08:15:55 +00002320 // Use a worklist to iteratively look through PHI nodes, and ensure that
2321 // the addressing mode obtained from the non-PHI roots of the graph
2322 // are equivalent.
2323 Value *Consensus = 0;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002324 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002325 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002326 SmallVector<Instruction*, 16> AddrModeInsts;
2327 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002328 TypePromotionTransaction TPT;
2329 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2330 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002331 while (!worklist.empty()) {
2332 Value *V = worklist.back();
2333 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002334
Owen Anderson8ba5f392010-11-27 08:15:55 +00002335 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002336 if (!Visited.insert(V)) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002337 Consensus = 0;
2338 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002339 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002340
Owen Anderson8ba5f392010-11-27 08:15:55 +00002341 // For a PHI node, push all of its incoming values.
2342 if (PHINode *P = dyn_cast<PHINode>(V)) {
2343 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2344 worklist.push_back(P->getIncomingValue(i));
2345 continue;
2346 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002347
Owen Anderson8ba5f392010-11-27 08:15:55 +00002348 // For non-PHIs, determine the addressing mode being computed.
2349 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002350 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2351 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2352 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002353
2354 // This check is broken into two cases with very similar code to avoid using
2355 // getNumUses() as much as possible. Some values have a lot of uses, so
2356 // calling getNumUses() unconditionally caused a significant compile-time
2357 // regression.
2358 if (!Consensus) {
2359 Consensus = V;
2360 AddrMode = NewAddrMode;
2361 AddrModeInsts = NewAddrModeInsts;
2362 continue;
2363 } else if (NewAddrMode == AddrMode) {
2364 if (!IsNumUsesConsensusValid) {
2365 NumUsesConsensus = Consensus->getNumUses();
2366 IsNumUsesConsensusValid = true;
2367 }
2368
2369 // Ensure that the obtained addressing mode is equivalent to that obtained
2370 // for all other roots of the PHI traversal. Also, when choosing one
2371 // such root as representative, select the one with the most uses in order
2372 // to keep the cost modeling heuristics in AddressingModeMatcher
2373 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002374 unsigned NumUses = V->getNumUses();
2375 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002376 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002377 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002378 AddrModeInsts = NewAddrModeInsts;
2379 }
2380 continue;
2381 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002382
Owen Anderson8ba5f392010-11-27 08:15:55 +00002383 Consensus = 0;
2384 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002385 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002386
Owen Anderson8ba5f392010-11-27 08:15:55 +00002387 // If the addressing mode couldn't be determined, or if multiple different
2388 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002389 if (!Consensus) {
2390 TPT.rollback(LastKnownGood);
2391 return false;
2392 }
2393 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002394
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002395 // Check to see if any of the instructions supersumed by this addr mode are
2396 // non-local to I's BB.
2397 bool AnyNonLocal = false;
2398 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002399 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002400 AnyNonLocal = true;
2401 break;
2402 }
2403 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002404
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002405 // If all the instructions matched are already in this BB, don't do anything.
2406 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002407 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002408 return false;
2409 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002410
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002411 // Insert this computation right after this user. Since our caller is
2412 // scanning from the top of the BB to the bottom, reuse of the expr are
2413 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002414 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002415
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002416 // Now that we determined the addressing expression we want to use and know
2417 // that we have to sink it into this block. Check to see if we have already
2418 // done this for some other load/store instr in this block. If so, reuse the
2419 // computation.
2420 Value *&SunkAddr = SunkAddrs[Addr];
2421 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002422 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002423 << *MemoryInst);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002424 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002425 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002426 } else {
David Greene74e2d492010-01-05 01:27:11 +00002427 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00002428 << *MemoryInst);
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002429 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002430 Value *Result = 0;
Dan Gohmanca194452010-01-19 22:45:06 +00002431
2432 // Start with the base register. Do this first so that subsequent address
2433 // matching finds it last, which will prevent it from trying to match it
2434 // as the scaled value in case it happens to be a mul. That would be
2435 // problematic if we've sunk a different mul for the scale, because then
2436 // we'd end up sinking both muls.
2437 if (AddrMode.BaseReg) {
2438 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002439 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002440 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002441 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002442 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002443 Result = V;
2444 }
2445
2446 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002447 if (AddrMode.Scale) {
2448 Value *V = AddrMode.ScaledReg;
2449 if (V->getType() == IntPtrTy) {
2450 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002451 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002452 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002453 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2454 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002455 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002456 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002457 // It is only safe to sign extend the BaseReg if we know that the math
2458 // required to create it did not overflow before we extend it. Since
2459 // the original IR value was tossed in favor of a constant back when
2460 // the AddrMode was created we need to bail out gracefully if widths
2461 // do not match instead of extending it.
Jim Grosbach83b44e12014-04-10 00:27:45 +00002462 Instruction *I = dyn_cast<Instruction>(Result);
2463 if (I && (Result != AddrMode.BaseReg))
2464 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002465 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002466 }
2467 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002468 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2469 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002470 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002471 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002472 else
2473 Result = V;
2474 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002475
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002476 // Add in the BaseGV if present.
2477 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002478 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002479 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002480 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002481 else
2482 Result = V;
2483 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002484
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002485 // Add in the Base Offset if present.
2486 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002487 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002488 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002489 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002490 else
2491 Result = V;
2492 }
2493
2494 if (Result == 0)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002495 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002496 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002497 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002498 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002499
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002500 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002501
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002502 // If we have no uses, recursively delete the value and all dead instructions
2503 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002504 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002505 // This can cause recursive deletion, which can invalidate our iterator.
2506 // Use a WeakVH to hold onto it in case this happens.
2507 WeakVH IterHandle(CurInstIterator);
2508 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002509
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002510 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002511
2512 if (IterHandle != CurInstIterator) {
2513 // If the iterator instruction was recursively deleted, start over at the
2514 // start of the block.
2515 CurInstIterator = BB->begin();
2516 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002517 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002518 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002519 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002520 return true;
2521}
2522
Evan Cheng1da25002008-02-26 02:42:37 +00002523/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002524/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002525/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002526bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002527 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002528
Nadav Rotem465834c2012-07-24 10:51:42 +00002529 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002530 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002531 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002532 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2533 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002534
Evan Cheng1da25002008-02-26 02:42:37 +00002535 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002536 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002537
Eli Friedman666bbe32008-02-26 18:37:49 +00002538 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2539 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002540 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002541 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002542 } else if (OpInfo.Type == InlineAsm::isInput)
2543 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002544 }
2545
2546 return MadeChange;
2547}
2548
Dan Gohman99429a02009-10-16 20:59:35 +00002549/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2550/// basic block as the load, unless conditions are unfavorable. This allows
2551/// SelectionDAG to fold the extend into the load.
2552///
2553bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2554 // Look for a load being extended.
2555 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2556 if (!LI) return false;
2557
2558 // If they're already in the same block, there's nothing to do.
2559 if (LI->getParent() == I->getParent())
2560 return false;
2561
2562 // If the load has other users and the truncate is not free, this probably
2563 // isn't worthwhile.
2564 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002565 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2566 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002567 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002568 return false;
2569
2570 // Check whether the target supports casts folded into loads.
2571 unsigned LType;
2572 if (isa<ZExtInst>(I))
2573 LType = ISD::ZEXTLOAD;
2574 else {
2575 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2576 LType = ISD::SEXTLOAD;
2577 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002578 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002579 return false;
2580
2581 // Move the extend into the same block as the load, so that SelectionDAG
2582 // can fold it.
2583 I->removeFromParent();
2584 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002585 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002586 return true;
2587}
2588
Evan Chengd3d80172007-12-05 23:58:20 +00002589bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2590 BasicBlock *DefBB = I->getParent();
2591
Bob Wilsonff714f92010-09-21 21:44:14 +00002592 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002593 // other uses of the source with result of extension.
2594 Value *Src = I->getOperand(0);
2595 if (Src->hasOneUse())
2596 return false;
2597
Evan Cheng2011df42007-12-13 07:50:36 +00002598 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002599 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002600 return false;
2601
Evan Cheng7bc89422007-12-12 00:51:06 +00002602 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002603 // this block.
2604 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002605 return false;
2606
Evan Chengd3d80172007-12-05 23:58:20 +00002607 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002608 for (User *U : I->users()) {
2609 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00002610
2611 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002612 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00002613 if (UserBB == DefBB) continue;
2614 DefIsLiveOut = true;
2615 break;
2616 }
2617 if (!DefIsLiveOut)
2618 return false;
2619
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002620 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002621 for (User *U : Src->users()) {
2622 Instruction *UI = cast<Instruction>(U);
2623 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00002624 if (UserBB == DefBB) continue;
2625 // Be conservative. We don't want this xform to end up introducing
2626 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002627 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002628 return false;
2629 }
2630
Evan Chengd3d80172007-12-05 23:58:20 +00002631 // InsertedTruncs - Only insert one trunc in each block once.
2632 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2633
2634 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002635 for (Use &U : Src->uses()) {
2636 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00002637
2638 // Figure out which BB this ext is used in.
2639 BasicBlock *UserBB = User->getParent();
2640 if (UserBB == DefBB) continue;
2641
2642 // Both src and def are live in this block. Rewrite the use.
2643 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2644
2645 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00002646 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00002647 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002648 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00002649 }
2650
2651 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002652 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00002653 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00002654 MadeChange = true;
2655 }
2656
2657 return MadeChange;
2658}
2659
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002660/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2661/// turned into an explicit branch.
2662static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2663 // FIXME: This should use the same heuristics as IfConversion to determine
2664 // whether a select is better represented as a branch. This requires that
2665 // branch probability metadata is preserved for the select, which is not the
2666 // case currently.
2667
2668 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2669
2670 // If the branch is predicted right, an out of order CPU can avoid blocking on
2671 // the compare. Emit cmovs on compares with a memory operand as branches to
2672 // avoid stalls on the load from memory. If the compare has more than one use
2673 // there's probably another cmov or setcc around so it's not worth emitting a
2674 // branch.
2675 if (!Cmp)
2676 return false;
2677
2678 Value *CmpOp0 = Cmp->getOperand(0);
2679 Value *CmpOp1 = Cmp->getOperand(1);
2680
2681 // We check that the memory operand has one use to avoid uses of the loaded
2682 // value directly after the compare, making branches unprofitable.
2683 return Cmp->hasOneUse() &&
2684 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2685 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2686}
2687
2688
Nadav Rotem9d832022012-09-02 12:10:19 +00002689/// If we have a SelectInst that will likely profit from branch prediction,
2690/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002691bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00002692 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2693
2694 // Can we convert the 'select' to CF ?
2695 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002696 return false;
2697
Nadav Rotem9d832022012-09-02 12:10:19 +00002698 TargetLowering::SelectSupportKind SelectKind;
2699 if (VectorCond)
2700 SelectKind = TargetLowering::VectorMaskSelect;
2701 else if (SI->getType()->isVectorTy())
2702 SelectKind = TargetLowering::ScalarCondVectorVal;
2703 else
2704 SelectKind = TargetLowering::ScalarValSelect;
2705
2706 // Do we have efficient codegen support for this kind of 'selects' ?
2707 if (TLI->isSelectSupported(SelectKind)) {
2708 // We have efficient codegen support for the select instruction.
2709 // Check if it is profitable to keep this 'select'.
2710 if (!TLI->isPredictableSelectExpensive() ||
2711 !isFormingBranchFromSelectProfitable(SI))
2712 return false;
2713 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002714
2715 ModifiedDT = true;
2716
2717 // First, we split the block containing the select into 2 blocks.
2718 BasicBlock *StartBlock = SI->getParent();
2719 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2720 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2721
2722 // Create a new block serving as the landing pad for the branch.
2723 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2724 NextBlock->getParent(), NextBlock);
2725
2726 // Move the unconditional branch from the block with the select in it into our
2727 // landing pad block.
2728 StartBlock->getTerminator()->eraseFromParent();
2729 BranchInst::Create(NextBlock, SmallBlock);
2730
2731 // Insert the real conditional branch based on the original condition.
2732 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2733
2734 // The select itself is replaced with a PHI Node.
2735 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2736 PN->takeName(SI);
2737 PN->addIncoming(SI->getTrueValue(), StartBlock);
2738 PN->addIncoming(SI->getFalseValue(), SmallBlock);
2739 SI->replaceAllUsesWith(PN);
2740 SI->eraseFromParent();
2741
2742 // Instruct OptimizeBlock to skip to the next block.
2743 CurInstIterator = StartBlock->end();
2744 ++NumSelectsExpanded;
2745 return true;
2746}
2747
Benjamin Kramer573ff362014-03-01 17:24:40 +00002748static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00002749 SmallVector<int, 16> Mask(SVI->getShuffleMask());
2750 int SplatElem = -1;
2751 for (unsigned i = 0; i < Mask.size(); ++i) {
2752 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
2753 return false;
2754 SplatElem = Mask[i];
2755 }
2756
2757 return true;
2758}
2759
2760/// Some targets have expensive vector shifts if the lanes aren't all the same
2761/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
2762/// it's often worth sinking a shufflevector splat down to its use so that
2763/// codegen can spot all lanes are identical.
2764bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
2765 BasicBlock *DefBB = SVI->getParent();
2766
2767 // Only do this xform if variable vector shifts are particularly expensive.
2768 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
2769 return false;
2770
2771 // We only expect better codegen by sinking a shuffle if we can recognise a
2772 // constant splat.
2773 if (!isBroadcastShuffle(SVI))
2774 return false;
2775
2776 // InsertedShuffles - Only insert a shuffle in each block once.
2777 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
2778
2779 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002780 for (User *U : SVI->users()) {
2781 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00002782
2783 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002784 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00002785 if (UserBB == DefBB) continue;
2786
2787 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002788 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00002789
2790 // Everything checks out, sink the shuffle if the user's block doesn't
2791 // already have a copy.
2792 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
2793
2794 if (!InsertedShuffle) {
2795 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2796 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
2797 SVI->getOperand(1),
2798 SVI->getOperand(2), "", InsertPt);
2799 }
2800
Chandler Carruthcdf47882014-03-09 03:16:01 +00002801 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00002802 MadeChange = true;
2803 }
2804
2805 // If we removed all uses, nuke the shuffle.
2806 if (SVI->use_empty()) {
2807 SVI->eraseFromParent();
2808 MadeChange = true;
2809 }
2810
2811 return MadeChange;
2812}
2813
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002814bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002815 if (PHINode *P = dyn_cast<PHINode>(I)) {
2816 // It is possible for very late stage optimizations (such as SimplifyCFG)
2817 // to introduce PHI nodes too late to be cleaned up. If we detect such a
2818 // trivial PHI, go ahead and zap it here.
Benjamin Kramer30d249a2013-09-24 16:37:40 +00002819 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
2820 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002821 P->replaceAllUsesWith(V);
2822 P->eraseFromParent();
2823 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00002824 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002825 }
Chris Lattneree588de2011-01-15 07:29:01 +00002826 return false;
2827 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002828
Chris Lattneree588de2011-01-15 07:29:01 +00002829 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002830 // If the source of the cast is a constant, then this should have
2831 // already been constant folded. The only reason NOT to constant fold
2832 // it is if something (e.g. LSR) was careful to place the constant
2833 // evaluation in a block other than then one that uses it (e.g. to hoist
2834 // the address of globals out of a loop). If this is the case, we don't
2835 // want to forward-subst the cast.
2836 if (isa<Constant>(CI->getOperand(0)))
2837 return false;
2838
Chris Lattneree588de2011-01-15 07:29:01 +00002839 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2840 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002841
Chris Lattneree588de2011-01-15 07:29:01 +00002842 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00002843 /// Sink a zext or sext into its user blocks if the target type doesn't
2844 /// fit in one register
2845 if (TLI && TLI->getTypeAction(CI->getContext(),
2846 TLI->getValueType(CI->getType())) ==
2847 TargetLowering::TypeExpandInteger) {
2848 return SinkCast(CI);
2849 } else {
2850 bool MadeChange = MoveExtToFormExtLoad(I);
2851 return MadeChange | OptimizeExtUses(I);
2852 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002853 }
Chris Lattneree588de2011-01-15 07:29:01 +00002854 return false;
2855 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002856
Chris Lattneree588de2011-01-15 07:29:01 +00002857 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00002858 if (!TLI || !TLI->hasMultipleConditionRegisters())
2859 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002860
Chris Lattneree588de2011-01-15 07:29:01 +00002861 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002862 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00002863 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2864 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00002865 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002866
Chris Lattneree588de2011-01-15 07:29:01 +00002867 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002868 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00002869 return OptimizeMemoryInst(I, SI->getOperand(1),
2870 SI->getOperand(0)->getType());
2871 return false;
2872 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002873
Chris Lattneree588de2011-01-15 07:29:01 +00002874 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002875 if (GEPI->hasAllZeroIndices()) {
2876 /// The GEP operand must be a pointer, so must its result -> BitCast
2877 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
2878 GEPI->getName(), GEPI);
2879 GEPI->replaceAllUsesWith(NC);
2880 GEPI->eraseFromParent();
2881 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002882 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00002883 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00002884 }
Chris Lattneree588de2011-01-15 07:29:01 +00002885 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002886 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002887
Chris Lattneree588de2011-01-15 07:29:01 +00002888 if (CallInst *CI = dyn_cast<CallInst>(I))
2889 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002890
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002891 if (SelectInst *SI = dyn_cast<SelectInst>(I))
2892 return OptimizeSelectInst(SI);
2893
Tim Northoveraeb8e062014-02-19 10:02:43 +00002894 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
2895 return OptimizeShuffleVectorInst(SVI);
2896
Chris Lattneree588de2011-01-15 07:29:01 +00002897 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00002898}
2899
Chris Lattnerf2836d12007-03-31 04:06:36 +00002900// In this pass we look for GEP and cast instructions that are used
2901// across basic blocks and rewrite them to improve basic-block-at-a-time
2902// selection.
2903bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00002904 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00002905 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00002906
Chris Lattner7a277142011-01-15 07:14:54 +00002907 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00002908 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00002909 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002910
Benjamin Kramer455fa352012-11-23 19:17:06 +00002911 MadeChange |= DupRetToEnableTailCallOpts(&BB);
2912
Chris Lattnerf2836d12007-03-31 04:06:36 +00002913 return MadeChange;
2914}
Devang Patel53771ba2011-08-18 00:50:51 +00002915
2916// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00002917// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00002918// find a node corresponding to the value.
2919bool CodeGenPrepare::PlaceDbgValues(Function &F) {
2920 bool MadeChange = false;
2921 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2922 Instruction *PrevNonDbgInst = NULL;
2923 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
2924 Instruction *Insn = BI; ++BI;
2925 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
2926 if (!DVI) {
2927 PrevNonDbgInst = Insn;
2928 continue;
2929 }
2930
2931 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
2932 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
2933 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
2934 DVI->removeFromParent();
2935 if (isa<PHINode>(VI))
2936 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
2937 else
2938 DVI->insertAfter(VI);
2939 MadeChange = true;
2940 ++NumDbgValueMoved;
2941 }
2942 }
2943 }
2944 return MadeChange;
2945}
Tim Northovercea0abb2014-03-29 08:22:29 +00002946
2947// If there is a sequence that branches based on comparing a single bit
2948// against zero that can be combined into a single instruction, and the
2949// target supports folding these into a single instruction, sink the
2950// mask and compare into the branch uses. Do this before OptimizeBlock ->
2951// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
2952// searched for.
2953bool CodeGenPrepare::sinkAndCmp(Function &F) {
2954 if (!EnableAndCmpSinking)
2955 return false;
2956 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
2957 return false;
2958 bool MadeChange = false;
2959 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
2960 BasicBlock *BB = I++;
2961
2962 // Does this BB end with the following?
2963 // %andVal = and %val, #single-bit-set
2964 // %icmpVal = icmp %andResult, 0
2965 // br i1 %cmpVal label %dest1, label %dest2"
2966 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
2967 if (!Brcc || !Brcc->isConditional())
2968 continue;
2969 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
2970 if (!Cmp || Cmp->getParent() != BB)
2971 continue;
2972 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
2973 if (!Zero || !Zero->isZero())
2974 continue;
2975 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
2976 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
2977 continue;
2978 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
2979 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
2980 continue;
2981 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
2982
2983 // Push the "and; icmp" for any users that are conditional branches.
2984 // Since there can only be one branch use per BB, we don't need to keep
2985 // track of which BBs we insert into.
2986 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
2987 UI != E; ) {
2988 Use &TheUse = *UI;
2989 // Find brcc use.
2990 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
2991 ++UI;
2992 if (!BrccUser || !BrccUser->isConditional())
2993 continue;
2994 BasicBlock *UserBB = BrccUser->getParent();
2995 if (UserBB == BB) continue;
2996 DEBUG(dbgs() << "found Brcc use\n");
2997
2998 // Sink the "and; icmp" to use.
2999 MadeChange = true;
3000 BinaryOperator *NewAnd =
3001 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3002 BrccUser);
3003 CmpInst *NewCmp =
3004 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3005 "", BrccUser);
3006 TheUse = NewCmp;
3007 ++NumAndCmpsMoved;
3008 DEBUG(BrccUser->getParent()->dump());
3009 }
3010 }
3011 return MadeChange;
3012}