blob: 2e2eabd8f1eaa04ffae3a4e4c562471148c938f6 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000021#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000027#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/InlineAsm.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000033#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000034#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000035#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000036#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000037#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000038#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000039#include "llvm/Target/TargetLibraryInfo.h"
40#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000041#include "llvm/Target/TargetSubtargetInfo.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
Chandler Carruth1b9dde02014-04-22 02:02:50 +000049#define DEBUG_TYPE "codegenprepare"
50
Cameron Zwarichced753f2011-01-05 17:27:27 +000051STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000052STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
53STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000054STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
55 "sunken Cmps");
56STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
57 "of sunken Casts");
58STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
59 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000060STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
61STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
62STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000063STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000064STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000065STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000066
Cameron Zwarich338d3622011-03-11 21:52:04 +000067static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
70
Benjamin Kramer3d38c172012-05-06 14:25:16 +000071static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000074
Hal Finkelc3998302014-04-12 00:59:48 +000075static cl::opt<bool> AddrSinkUsingGEPs(
76 "addr-sink-using-gep", cl::Hidden, cl::init(false),
77 cl::desc("Address sinking in CGP using GEPs."));
78
Tim Northovercea0abb2014-03-29 08:22:29 +000079static cl::opt<bool> EnableAndCmpSinking(
80 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
81 cl::desc("Enable sinkinig and/cmp into branches."));
82
Eric Christopherc1ea1492008-09-24 05:32:41 +000083namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000084typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
85typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
86
Chris Lattner2dd09db2009-09-02 06:11:42 +000087 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000088 /// TLI - Keep a pointer of a TargetLowering to consult for determining
89 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +000090 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +000091 const TargetLowering *TLI;
Chad Rosierc24b86f2011-12-01 03:08:23 +000092 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +000093 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +000094
Chris Lattner7a277142011-01-15 07:14:54 +000095 /// CurInstIterator - As we scan instructions optimizing them, this is the
96 /// next instruction to optimize. Xforms that can invalidate this should
97 /// update it.
98 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +000099
Evan Cheng0663f232011-03-21 01:19:09 +0000100 /// Keeps track of non-local addresses that have been sunk into a block.
101 /// This allows us to avoid inserting duplicate code for blocks with
102 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000103 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000104
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000105 /// Keeps track of all truncates inserted for the current function.
106 SetOfInstrs InsertedTruncsSet;
107 /// Keeps track of the type of the related instruction before their
108 /// promotion for the current function.
109 InstrToOrigTy PromotedInsts;
110
Devang Patel8f606d72011-03-24 15:35:25 +0000111 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000112 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000113 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000114
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000115 /// OptSize - True if optimizing for size.
116 bool OptSize;
117
Chris Lattnerf2836d12007-03-31 04:06:36 +0000118 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000119 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000120 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
121 : FunctionPass(ID), TM(TM), TLI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000122 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
123 }
Craig Topper4584cd52014-03-07 09:26:03 +0000124 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000125
Craig Topper4584cd52014-03-07 09:26:03 +0000126 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000127
Craig Topper4584cd52014-03-07 09:26:03 +0000128 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000129 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000130 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000131 }
132
Chris Lattnerf2836d12007-03-31 04:06:36 +0000133 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000134 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000135 bool EliminateMostlyEmptyBlocks(Function &F);
136 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
137 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000138 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000139 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000140 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000141 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000142 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000143 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000144 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000145 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000146 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000147 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000148 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000149 bool sinkAndCmp(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000150 };
151}
Devang Patel09f162c2007-05-01 21:15:47 +0000152
Devang Patel8c78a0b2007-05-03 01:11:54 +0000153char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000154INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
155 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000156
Bill Wendling7a639ea2013-06-19 21:07:11 +0000157FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
158 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000159}
160
Chris Lattnerf2836d12007-03-31 04:06:36 +0000161bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000162 if (skipOptnoneFunction(F))
163 return false;
164
Chris Lattnerf2836d12007-03-31 04:06:36 +0000165 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000166 // Clear per function information.
167 InsertedTruncsSet.clear();
168 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000169
Devang Patel8f606d72011-03-24 15:35:25 +0000170 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000171 if (TM)
172 TLI = TM->getSubtargetImpl()->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000173 TLInfo = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000174 DominatorTreeWrapperPass *DTWP =
175 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000176 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Bill Wendling698e84f2012-12-30 10:32:01 +0000177 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
178 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000179
Preston Gurdcdf540d2012-09-04 18:22:17 +0000180 /// This optimization identifies DIV instructions that can be
181 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000182 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000183 const DenseMap<unsigned int, unsigned int> &BypassWidths =
184 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000185 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000186 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000187 }
188
189 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000190 // unconditional branch.
191 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000192
Devang Patel53771ba2011-08-18 00:50:51 +0000193 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000194 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000195 // find a node corresponding to the value.
196 EverMadeChange |= PlaceDbgValues(F);
197
Tim Northovercea0abb2014-03-29 08:22:29 +0000198 // If there is a mask, compare against zero, and branch that can be combined
199 // into a single target instruction, push the mask and compare into branch
200 // users. Do this before OptimizeBlock -> OptimizeInst ->
201 // OptimizeCmpExpression, which perturbs the pattern being searched for.
202 if (!DisableBranchOpts)
203 EverMadeChange |= sinkAndCmp(F);
204
Chris Lattnerc3748562007-04-02 01:35:34 +0000205 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000206 while (MadeChange) {
207 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000208 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000209 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000210 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000211 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000212 EverMadeChange |= MadeChange;
213 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000214
215 SunkAddrs.clear();
216
Cameron Zwarich338d3622011-03-11 21:52:04 +0000217 if (!DisableBranchOpts) {
218 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000219 SmallPtrSet<BasicBlock*, 8> WorkList;
220 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
221 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000222 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000223 if (!MadeChange) continue;
224
225 for (SmallVectorImpl<BasicBlock*>::iterator
226 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
227 if (pred_begin(*II) == pred_end(*II))
228 WorkList.insert(*II);
229 }
230
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000231 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000232 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000233 while (!WorkList.empty()) {
234 BasicBlock *BB = *WorkList.begin();
235 WorkList.erase(BB);
236 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
237
238 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000239
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000240 for (SmallVectorImpl<BasicBlock*>::iterator
241 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
242 if (pred_begin(*II) == pred_end(*II))
243 WorkList.insert(*II);
244 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000245
Nadav Rotem70409992012-08-14 05:19:07 +0000246 // Merge pairs of basic blocks with unconditional branches, connected by
247 // a single edge.
248 if (EverMadeChange || MadeChange)
249 MadeChange |= EliminateFallThrough(F);
250
Evan Cheng0663f232011-03-21 01:19:09 +0000251 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000252 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000253 EverMadeChange |= MadeChange;
254 }
255
Devang Patel8f606d72011-03-24 15:35:25 +0000256 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000257 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000258
Chris Lattnerf2836d12007-03-31 04:06:36 +0000259 return EverMadeChange;
260}
261
Nadav Rotem70409992012-08-14 05:19:07 +0000262/// EliminateFallThrough - Merge basic blocks which are connected
263/// by a single edge, where one of the basic blocks has a single successor
264/// pointing to the other basic block, which has a single predecessor.
265bool CodeGenPrepare::EliminateFallThrough(Function &F) {
266 bool Changed = false;
267 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000268 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000269 BasicBlock *BB = I++;
270 // If the destination block has a single pred, then this is a trivial
271 // edge, just collapse it.
272 BasicBlock *SinglePred = BB->getSinglePredecessor();
273
Evan Cheng64a223a2012-09-28 23:58:57 +0000274 // Don't merge if BB's address is taken.
275 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000276
277 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
278 if (Term && !Term->isConditional()) {
279 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000280 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000281 // Remember if SinglePred was the entry block of the function.
282 // If so, we will need to move BB back to the entry position.
283 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
284 MergeBasicBlockIntoOnlyPred(BB, this);
285
286 if (isEntry && BB != &BB->getParent()->getEntryBlock())
287 BB->moveBefore(&BB->getParent()->getEntryBlock());
288
289 // We have erased a block. Update the iterator.
290 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000291 }
292 }
293 return Changed;
294}
295
Dale Johannesen4026b042009-03-27 01:13:37 +0000296/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
297/// debug info directives, and an unconditional branch. Passes before isel
298/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
299/// isel. Start by eliminating these blocks so we can split them the way we
300/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000301bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
302 bool MadeChange = false;
303 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000304 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000305 BasicBlock *BB = I++;
306
307 // If this block doesn't end with an uncond branch, ignore it.
308 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
309 if (!BI || !BI->isUnconditional())
310 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000311
Dale Johannesen4026b042009-03-27 01:13:37 +0000312 // If the instruction before the branch (skipping debug info) isn't a phi
313 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000314 BasicBlock::iterator BBI = BI;
315 if (BBI != BB->begin()) {
316 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000317 while (isa<DbgInfoIntrinsic>(BBI)) {
318 if (BBI == BB->begin())
319 break;
320 --BBI;
321 }
322 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
323 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000324 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000325
Chris Lattnerc3748562007-04-02 01:35:34 +0000326 // Do not break infinite loops.
327 BasicBlock *DestBB = BI->getSuccessor(0);
328 if (DestBB == BB)
329 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000330
Chris Lattnerc3748562007-04-02 01:35:34 +0000331 if (!CanMergeBlocks(BB, DestBB))
332 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000333
Chris Lattnerc3748562007-04-02 01:35:34 +0000334 EliminateMostlyEmptyBlock(BB);
335 MadeChange = true;
336 }
337 return MadeChange;
338}
339
340/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
341/// single uncond branch between them, and BB contains no other non-phi
342/// instructions.
343bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
344 const BasicBlock *DestBB) const {
345 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
346 // the successor. If there are more complex condition (e.g. preheaders),
347 // don't mess around with them.
348 BasicBlock::const_iterator BBI = BB->begin();
349 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000350 for (const User *U : PN->users()) {
351 const Instruction *UI = cast<Instruction>(U);
352 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000353 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000354 // If User is inside DestBB block and it is a PHINode then check
355 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000356 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000357 if (UI->getParent() == DestBB) {
358 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000359 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
360 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
361 if (Insn && Insn->getParent() == BB &&
362 Insn->getParent() != UPN->getIncomingBlock(I))
363 return false;
364 }
365 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000366 }
367 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000368
Chris Lattnerc3748562007-04-02 01:35:34 +0000369 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
370 // and DestBB may have conflicting incoming values for the block. If so, we
371 // can't merge the block.
372 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
373 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000374
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000376 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000377 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
378 // It is faster to get preds from a PHI than with pred_iterator.
379 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
380 BBPreds.insert(BBPN->getIncomingBlock(i));
381 } else {
382 BBPreds.insert(pred_begin(BB), pred_end(BB));
383 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000384
Chris Lattnerc3748562007-04-02 01:35:34 +0000385 // Walk the preds of DestBB.
386 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
387 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
388 if (BBPreds.count(Pred)) { // Common predecessor?
389 BBI = DestBB->begin();
390 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
391 const Value *V1 = PN->getIncomingValueForBlock(Pred);
392 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000393
Chris Lattnerc3748562007-04-02 01:35:34 +0000394 // If V2 is a phi node in BB, look up what the mapped value will be.
395 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
396 if (V2PN->getParent() == BB)
397 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000398
Chris Lattnerc3748562007-04-02 01:35:34 +0000399 // If there is a conflict, bail out.
400 if (V1 != V2) return false;
401 }
402 }
403 }
404
405 return true;
406}
407
408
409/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
410/// an unconditional branch in it.
411void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
412 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
413 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000414
David Greene74e2d492010-01-05 01:27:11 +0000415 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000416
Chris Lattnerc3748562007-04-02 01:35:34 +0000417 // If the destination block has a single pred, then this is a trivial edge,
418 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000419 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000420 if (SinglePred != DestBB) {
421 // Remember if SinglePred was the entry block of the function. If so, we
422 // will need to move BB back to the entry position.
423 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000424 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000425
Chris Lattner8a172da2008-11-28 19:54:49 +0000426 if (isEntry && BB != &BB->getParent()->getEntryBlock())
427 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000428
David Greene74e2d492010-01-05 01:27:11 +0000429 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000430 return;
431 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000432 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000433
Chris Lattnerc3748562007-04-02 01:35:34 +0000434 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
435 // to handle the new incoming edges it is about to have.
436 PHINode *PN;
437 for (BasicBlock::iterator BBI = DestBB->begin();
438 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
439 // Remove the incoming value for BB, and remember it.
440 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000441
Chris Lattnerc3748562007-04-02 01:35:34 +0000442 // Two options: either the InVal is a phi node defined in BB or it is some
443 // value that dominates BB.
444 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
445 if (InValPhi && InValPhi->getParent() == BB) {
446 // Add all of the input values of the input PHI as inputs of this phi.
447 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
448 PN->addIncoming(InValPhi->getIncomingValue(i),
449 InValPhi->getIncomingBlock(i));
450 } else {
451 // Otherwise, add one instance of the dominating value for each edge that
452 // we will be adding.
453 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
454 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
455 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
456 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000457 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
458 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000459 }
460 }
461 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000462
Chris Lattnerc3748562007-04-02 01:35:34 +0000463 // The PHIs are now updated, change everything that refers to BB to use
464 // DestBB and remove BB.
465 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000466 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000467 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
468 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
469 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
470 DT->changeImmediateDominator(DestBB, NewIDom);
471 DT->eraseNode(BB);
472 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000473 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000474 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000475
David Greene74e2d492010-01-05 01:27:11 +0000476 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000477}
478
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000479/// SinkCast - Sink the specified cast instruction into its user blocks
480static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000481 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000482
Chris Lattnerf2836d12007-03-31 04:06:36 +0000483 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000484 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000485
Chris Lattnerf2836d12007-03-31 04:06:36 +0000486 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000487 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000488 UI != E; ) {
489 Use &TheUse = UI.getUse();
490 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000491
Chris Lattnerf2836d12007-03-31 04:06:36 +0000492 // Figure out which BB this cast is used in. For PHI's this is the
493 // appropriate predecessor block.
494 BasicBlock *UserBB = User->getParent();
495 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000496 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000497 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000498
Chris Lattnerf2836d12007-03-31 04:06:36 +0000499 // Preincrement use iterator so we don't invalidate it.
500 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000501
Chris Lattnerf2836d12007-03-31 04:06:36 +0000502 // If this user is in the same block as the cast, don't change the cast.
503 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000504
Chris Lattnerf2836d12007-03-31 04:06:36 +0000505 // If we have already inserted a cast into this block, use it.
506 CastInst *&InsertedCast = InsertedCasts[UserBB];
507
508 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000509 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000510 InsertedCast =
511 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000512 InsertPt);
513 MadeChange = true;
514 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000515
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000516 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000517 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000518 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000519 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000520
Chris Lattnerf2836d12007-03-31 04:06:36 +0000521 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000522 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000523 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000524 MadeChange = true;
525 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000526
Chris Lattnerf2836d12007-03-31 04:06:36 +0000527 return MadeChange;
528}
529
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000530/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
531/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
532/// sink it into user blocks to reduce the number of virtual
533/// registers that must be created and coalesced.
534///
535/// Return true if any changes are made.
536///
537static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
538 // If this is a noop copy,
539 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
540 EVT DstVT = TLI.getValueType(CI->getType());
541
542 // This is an fp<->int conversion?
543 if (SrcVT.isInteger() != DstVT.isInteger())
544 return false;
545
546 // If this is an extension, it will be a zero or sign extension, which
547 // isn't a noop.
548 if (SrcVT.bitsLT(DstVT)) return false;
549
550 // If these values will be promoted, find out what they will be promoted
551 // to. This helps us consider truncates on PPC as noop copies when they
552 // are.
553 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
554 TargetLowering::TypePromoteInteger)
555 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
556 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
557 TargetLowering::TypePromoteInteger)
558 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
559
560 // If, after promotion, these are the same types, this is a noop copy.
561 if (SrcVT != DstVT)
562 return false;
563
564 return SinkCast(CI);
565}
566
Eric Christopherc1ea1492008-09-24 05:32:41 +0000567/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000568/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000569/// a clear win except on targets with multiple condition code registers
570/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000571///
572/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000573static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000574 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000575
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000576 /// InsertedCmp - Only insert a cmp in each block once.
577 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000578
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000579 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000580 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000581 UI != E; ) {
582 Use &TheUse = UI.getUse();
583 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000584
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000585 // Preincrement use iterator so we don't invalidate it.
586 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000587
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000588 // Don't bother for PHI nodes.
589 if (isa<PHINode>(User))
590 continue;
591
592 // Figure out which BB this cmp is used in.
593 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000594
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000595 // If this user is in the same block as the cmp, don't change the cmp.
596 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000597
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000598 // If we have already inserted a cmp into this block, use it.
599 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
600
601 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000602 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000603 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000604 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000605 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000606 CI->getOperand(1), "", InsertPt);
607 MadeChange = true;
608 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000609
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000610 // Replace a use of the cmp with a use of the new cmp.
611 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000612 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000613 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000614
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000615 // If we removed all uses, nuke the cmp.
616 if (CI->use_empty())
617 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000618
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000619 return MadeChange;
620}
621
Yi Jiangd069f632014-04-21 19:34:27 +0000622/// isExtractBitsCandidateUse - Check if the candidates could
623/// be combined with shift instruction, which includes:
624/// 1. Truncate instruction
625/// 2. And instruction and the imm is a mask of the low bits:
626/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000627static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000628 if (!isa<TruncInst>(User)) {
629 if (User->getOpcode() != Instruction::And ||
630 !isa<ConstantInt>(User->getOperand(1)))
631 return false;
632
Quentin Colombetd4f44692014-04-22 01:20:34 +0000633 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000634
Quentin Colombetd4f44692014-04-22 01:20:34 +0000635 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000636 return false;
637 }
638 return true;
639}
640
641/// SinkShiftAndTruncate - sink both shift and truncate instruction
642/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000643static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000644SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
645 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
646 const TargetLowering &TLI) {
647 BasicBlock *UserBB = User->getParent();
648 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
649 TruncInst *TruncI = dyn_cast<TruncInst>(User);
650 bool MadeChange = false;
651
652 for (Value::user_iterator TruncUI = TruncI->user_begin(),
653 TruncE = TruncI->user_end();
654 TruncUI != TruncE;) {
655
656 Use &TruncTheUse = TruncUI.getUse();
657 Instruction *TruncUser = cast<Instruction>(*TruncUI);
658 // Preincrement use iterator so we don't invalidate it.
659
660 ++TruncUI;
661
662 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
663 if (!ISDOpcode)
664 continue;
665
Tim Northovere2239ff2014-07-29 10:20:22 +0000666 // If the use is actually a legal node, there will not be an
667 // implicit truncate.
668 // FIXME: always querying the result type is just an
669 // approximation; some nodes' legality is determined by the
670 // operand or other means. There's no good way to find out though.
Yi Jiangd069f632014-04-21 19:34:27 +0000671 if (TLI.isOperationLegalOrCustom(ISDOpcode,
Tim Northovere2239ff2014-07-29 10:20:22 +0000672 EVT::getEVT(TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000673 continue;
674
675 // Don't bother for PHI nodes.
676 if (isa<PHINode>(TruncUser))
677 continue;
678
679 BasicBlock *TruncUserBB = TruncUser->getParent();
680
681 if (UserBB == TruncUserBB)
682 continue;
683
684 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
685 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
686
687 if (!InsertedShift && !InsertedTrunc) {
688 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
689 // Sink the shift
690 if (ShiftI->getOpcode() == Instruction::AShr)
691 InsertedShift =
692 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
693 else
694 InsertedShift =
695 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
696
697 // Sink the trunc
698 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
699 TruncInsertPt++;
700
701 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
702 TruncI->getType(), "", TruncInsertPt);
703
704 MadeChange = true;
705
706 TruncTheUse = InsertedTrunc;
707 }
708 }
709 return MadeChange;
710}
711
712/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
713/// the uses could potentially be combined with this shift instruction and
714/// generate BitExtract instruction. It will only be applied if the architecture
715/// supports BitExtract instruction. Here is an example:
716/// BB1:
717/// %x.extract.shift = lshr i64 %arg1, 32
718/// BB2:
719/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
720/// ==>
721///
722/// BB2:
723/// %x.extract.shift.1 = lshr i64 %arg1, 32
724/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
725///
726/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
727/// instruction.
728/// Return true if any changes are made.
729static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
730 const TargetLowering &TLI) {
731 BasicBlock *DefBB = ShiftI->getParent();
732
733 /// Only insert instructions in each block once.
734 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
735
736 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
737
738 bool MadeChange = false;
739 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
740 UI != E;) {
741 Use &TheUse = UI.getUse();
742 Instruction *User = cast<Instruction>(*UI);
743 // Preincrement use iterator so we don't invalidate it.
744 ++UI;
745
746 // Don't bother for PHI nodes.
747 if (isa<PHINode>(User))
748 continue;
749
750 if (!isExtractBitsCandidateUse(User))
751 continue;
752
753 BasicBlock *UserBB = User->getParent();
754
755 if (UserBB == DefBB) {
756 // If the shift and truncate instruction are in the same BB. The use of
757 // the truncate(TruncUse) may still introduce another truncate if not
758 // legal. In this case, we would like to sink both shift and truncate
759 // instruction to the BB of TruncUse.
760 // for example:
761 // BB1:
762 // i64 shift.result = lshr i64 opnd, imm
763 // trunc.result = trunc shift.result to i16
764 //
765 // BB2:
766 // ----> We will have an implicit truncate here if the architecture does
767 // not have i16 compare.
768 // cmp i16 trunc.result, opnd2
769 //
770 if (isa<TruncInst>(User) && shiftIsLegal
771 // If the type of the truncate is legal, no trucate will be
772 // introduced in other basic blocks.
773 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
774 MadeChange =
775 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
776
777 continue;
778 }
779 // If we have already inserted a shift into this block, use it.
780 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
781
782 if (!InsertedShift) {
783 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
784
785 if (ShiftI->getOpcode() == Instruction::AShr)
786 InsertedShift =
787 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
788 else
789 InsertedShift =
790 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
791
792 MadeChange = true;
793 }
794
795 // Replace a use of the shift with a use of the new shift.
796 TheUse = InsertedShift;
797 }
798
799 // If we removed all uses, nuke the shift.
800 if (ShiftI->use_empty())
801 ShiftI->eraseFromParent();
802
803 return MadeChange;
804}
805
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000806namespace {
807class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
808protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000809 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000810 CI->replaceAllUsesWith(With);
811 CI->eraseFromParent();
812 }
Craig Topper4584cd52014-03-07 09:26:03 +0000813 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000814 if (ConstantInt *SizeCI =
815 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
816 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000817 return false;
818 }
819};
820} // end anonymous namespace
821
Eric Christopher4b7948e2010-03-11 02:41:03 +0000822bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000823 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000824
Chris Lattner7a277142011-01-15 07:14:54 +0000825 // Lower inline assembly if we can.
826 // If we found an inline asm expession, and if the target knows how to
827 // lower it to normal LLVM code, do so now.
828 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
829 if (TLI->ExpandInlineAsm(CI)) {
830 // Avoid invalidating the iterator.
831 CurInstIterator = BB->begin();
832 // Avoid processing instructions out of order, which could cause
833 // reuse before a value is defined.
834 SunkAddrs.clear();
835 return true;
836 }
837 // Sink address computing for memory operands into the block.
838 if (OptimizeInlineAsmInst(CI))
839 return true;
840 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000841
Eric Christopher4b7948e2010-03-11 02:41:03 +0000842 // Lower all uses of llvm.objectsize.*
843 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
844 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000845 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000846 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000847 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
848
Chris Lattner1b93be52011-01-15 07:25:29 +0000849 // Substituting this can cause recursive simplifications, which can
850 // invalidate our iterator. Use a WeakVH to hold onto it in case this
851 // happens.
852 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000853
Craig Topperc0196b12014-04-14 00:51:57 +0000854 replaceAndRecursivelySimplify(CI, RetVal,
855 TLI ? TLI->getDataLayout() : nullptr,
856 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000857
858 // If the iterator instruction was recursively deleted, start over at the
859 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000860 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000861 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000862 SunkAddrs.clear();
863 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000864 return true;
865 }
866
Pete Cooper615fd892012-03-13 20:59:56 +0000867 if (II && TLI) {
868 SmallVector<Value*, 2> PtrOps;
869 Type *AccessTy;
870 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
871 while (!PtrOps.empty())
872 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
873 return true;
874 }
875
Eric Christopher4b7948e2010-03-11 02:41:03 +0000876 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +0000877 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000878
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000879 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +0000880 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000881 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000882
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000883 // Lower all default uses of _chk calls. This is very similar
884 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000885 // that have the default "don't know" as the objectsize. Anything else
886 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000887 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000888 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000889}
Chris Lattner1b93be52011-01-15 07:25:29 +0000890
Evan Cheng0663f232011-03-21 01:19:09 +0000891/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
892/// instructions to the predecessor to enable tail call optimizations. The
893/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000894/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000895/// bb0:
896/// %tmp0 = tail call i32 @f0()
897/// br label %return
898/// bb1:
899/// %tmp1 = tail call i32 @f1()
900/// br label %return
901/// bb2:
902/// %tmp2 = tail call i32 @f2()
903/// br label %return
904/// return:
905/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
906/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000907/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000908///
909/// =>
910///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000911/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000912/// bb0:
913/// %tmp0 = tail call i32 @f0()
914/// ret i32 %tmp0
915/// bb1:
916/// %tmp1 = tail call i32 @f1()
917/// ret i32 %tmp1
918/// bb2:
919/// %tmp2 = tail call i32 @f2()
920/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000921/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000922bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000923 if (!TLI)
924 return false;
925
Benjamin Kramer455fa352012-11-23 19:17:06 +0000926 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
927 if (!RI)
928 return false;
929
Craig Topperc0196b12014-04-14 00:51:57 +0000930 PHINode *PN = nullptr;
931 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +0000932 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000933 if (V) {
934 BCI = dyn_cast<BitCastInst>(V);
935 if (BCI)
936 V = BCI->getOperand(0);
937
938 PN = dyn_cast<PHINode>(V);
939 if (!PN)
940 return false;
941 }
Evan Cheng0663f232011-03-21 01:19:09 +0000942
Cameron Zwarich4649f172011-03-24 04:52:10 +0000943 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000944 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000945
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000946 // It's not safe to eliminate the sign / zero extension of the return value.
947 // See llvm::isInTailCallPosition().
948 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000949 AttributeSet CallerAttrs = F->getAttributes();
950 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
951 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000952 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000953
Cameron Zwarich4649f172011-03-24 04:52:10 +0000954 // Make sure there are no instructions between the PHI and return, or that the
955 // return is the first instruction in the block.
956 if (PN) {
957 BasicBlock::iterator BI = BB->begin();
958 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000959 if (&*BI == BCI)
960 // Also skip over the bitcast.
961 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000962 if (&*BI != RI)
963 return false;
964 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000965 BasicBlock::iterator BI = BB->begin();
966 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
967 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000968 return false;
969 }
Evan Cheng0663f232011-03-21 01:19:09 +0000970
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000971 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
972 /// call.
973 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000974 if (PN) {
975 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
976 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
977 // Make sure the phi value is indeed produced by the tail call.
978 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
979 TLI->mayBeEmittedAsTailCall(CI))
980 TailCalls.push_back(CI);
981 }
982 } else {
983 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000984 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
985 if (!VisitedBBs.insert(*PI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000986 continue;
987
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000988 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +0000989 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
990 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000991 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
992 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000993 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000994
Cameron Zwarich4649f172011-03-24 04:52:10 +0000995 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +0000996 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000997 TailCalls.push_back(CI);
998 }
Evan Cheng0663f232011-03-21 01:19:09 +0000999 }
1000
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001001 bool Changed = false;
1002 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1003 CallInst *CI = TailCalls[i];
1004 CallSite CS(CI);
1005
1006 // Conservatively require the attributes of the call to match those of the
1007 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001008 AttributeSet CalleeAttrs = CS.getAttributes();
1009 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001010 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001011 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001012 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001013 continue;
1014
1015 // Make sure the call instruction is followed by an unconditional branch to
1016 // the return block.
1017 BasicBlock *CallBB = CI->getParent();
1018 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1019 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1020 continue;
1021
1022 // Duplicate the return into CallBB.
1023 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001024 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001025 ++NumRetsDup;
1026 }
1027
1028 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001029 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001030 BB->eraseFromParent();
1031
1032 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001033}
1034
Chris Lattner728f9022008-11-25 07:09:13 +00001035//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001036// Memory Optimization
1037//===----------------------------------------------------------------------===//
1038
Chandler Carruthc8925912013-01-05 02:09:22 +00001039namespace {
1040
1041/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1042/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001043struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001044 Value *BaseReg;
1045 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001046 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001047 void print(raw_ostream &OS) const;
1048 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001049
Chandler Carruthc8925912013-01-05 02:09:22 +00001050 bool operator==(const ExtAddrMode& O) const {
1051 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1052 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1053 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1054 }
1055};
1056
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001057#ifndef NDEBUG
1058static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1059 AM.print(OS);
1060 return OS;
1061}
1062#endif
1063
Chandler Carruthc8925912013-01-05 02:09:22 +00001064void ExtAddrMode::print(raw_ostream &OS) const {
1065 bool NeedPlus = false;
1066 OS << "[";
1067 if (BaseGV) {
1068 OS << (NeedPlus ? " + " : "")
1069 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001070 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001071 NeedPlus = true;
1072 }
1073
Richard Trieuc0f91212014-05-30 03:15:17 +00001074 if (BaseOffs) {
1075 OS << (NeedPlus ? " + " : "")
1076 << BaseOffs;
1077 NeedPlus = true;
1078 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001079
1080 if (BaseReg) {
1081 OS << (NeedPlus ? " + " : "")
1082 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001083 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001084 NeedPlus = true;
1085 }
1086 if (Scale) {
1087 OS << (NeedPlus ? " + " : "")
1088 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001089 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001090 }
1091
1092 OS << ']';
1093}
1094
1095#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1096void ExtAddrMode::dump() const {
1097 print(dbgs());
1098 dbgs() << '\n';
1099}
1100#endif
1101
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001102/// \brief This class provides transaction based operation on the IR.
1103/// Every change made through this class is recorded in the internal state and
1104/// can be undone (rollback) until commit is called.
1105class TypePromotionTransaction {
1106
1107 /// \brief This represents the common interface of the individual transaction.
1108 /// Each class implements the logic for doing one specific modification on
1109 /// the IR via the TypePromotionTransaction.
1110 class TypePromotionAction {
1111 protected:
1112 /// The Instruction modified.
1113 Instruction *Inst;
1114
1115 public:
1116 /// \brief Constructor of the action.
1117 /// The constructor performs the related action on the IR.
1118 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1119
1120 virtual ~TypePromotionAction() {}
1121
1122 /// \brief Undo the modification done by this action.
1123 /// When this method is called, the IR must be in the same state as it was
1124 /// before this action was applied.
1125 /// \pre Undoing the action works if and only if the IR is in the exact same
1126 /// state as it was directly after this action was applied.
1127 virtual void undo() = 0;
1128
1129 /// \brief Advocate every change made by this action.
1130 /// When the results on the IR of the action are to be kept, it is important
1131 /// to call this function, otherwise hidden information may be kept forever.
1132 virtual void commit() {
1133 // Nothing to be done, this action is not doing anything.
1134 }
1135 };
1136
1137 /// \brief Utility to remember the position of an instruction.
1138 class InsertionHandler {
1139 /// Position of an instruction.
1140 /// Either an instruction:
1141 /// - Is the first in a basic block: BB is used.
1142 /// - Has a previous instructon: PrevInst is used.
1143 union {
1144 Instruction *PrevInst;
1145 BasicBlock *BB;
1146 } Point;
1147 /// Remember whether or not the instruction had a previous instruction.
1148 bool HasPrevInstruction;
1149
1150 public:
1151 /// \brief Record the position of \p Inst.
1152 InsertionHandler(Instruction *Inst) {
1153 BasicBlock::iterator It = Inst;
1154 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1155 if (HasPrevInstruction)
1156 Point.PrevInst = --It;
1157 else
1158 Point.BB = Inst->getParent();
1159 }
1160
1161 /// \brief Insert \p Inst at the recorded position.
1162 void insert(Instruction *Inst) {
1163 if (HasPrevInstruction) {
1164 if (Inst->getParent())
1165 Inst->removeFromParent();
1166 Inst->insertAfter(Point.PrevInst);
1167 } else {
1168 Instruction *Position = Point.BB->getFirstInsertionPt();
1169 if (Inst->getParent())
1170 Inst->moveBefore(Position);
1171 else
1172 Inst->insertBefore(Position);
1173 }
1174 }
1175 };
1176
1177 /// \brief Move an instruction before another.
1178 class InstructionMoveBefore : public TypePromotionAction {
1179 /// Original position of the instruction.
1180 InsertionHandler Position;
1181
1182 public:
1183 /// \brief Move \p Inst before \p Before.
1184 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1185 : TypePromotionAction(Inst), Position(Inst) {
1186 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1187 Inst->moveBefore(Before);
1188 }
1189
1190 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001191 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001192 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1193 Position.insert(Inst);
1194 }
1195 };
1196
1197 /// \brief Set the operand of an instruction with a new value.
1198 class OperandSetter : public TypePromotionAction {
1199 /// Original operand of the instruction.
1200 Value *Origin;
1201 /// Index of the modified instruction.
1202 unsigned Idx;
1203
1204 public:
1205 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1206 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1207 : TypePromotionAction(Inst), Idx(Idx) {
1208 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1209 << "for:" << *Inst << "\n"
1210 << "with:" << *NewVal << "\n");
1211 Origin = Inst->getOperand(Idx);
1212 Inst->setOperand(Idx, NewVal);
1213 }
1214
1215 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001216 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001217 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1218 << "for: " << *Inst << "\n"
1219 << "with: " << *Origin << "\n");
1220 Inst->setOperand(Idx, Origin);
1221 }
1222 };
1223
1224 /// \brief Hide the operands of an instruction.
1225 /// Do as if this instruction was not using any of its operands.
1226 class OperandsHider : public TypePromotionAction {
1227 /// The list of original operands.
1228 SmallVector<Value *, 4> OriginalValues;
1229
1230 public:
1231 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1232 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1233 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1234 unsigned NumOpnds = Inst->getNumOperands();
1235 OriginalValues.reserve(NumOpnds);
1236 for (unsigned It = 0; It < NumOpnds; ++It) {
1237 // Save the current operand.
1238 Value *Val = Inst->getOperand(It);
1239 OriginalValues.push_back(Val);
1240 // Set a dummy one.
1241 // We could use OperandSetter here, but that would implied an overhead
1242 // that we are not willing to pay.
1243 Inst->setOperand(It, UndefValue::get(Val->getType()));
1244 }
1245 }
1246
1247 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001248 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001249 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1250 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1251 Inst->setOperand(It, OriginalValues[It]);
1252 }
1253 };
1254
1255 /// \brief Build a truncate instruction.
1256 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001257 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001258 public:
1259 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1260 /// result.
1261 /// trunc Opnd to Ty.
1262 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1263 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001264 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1265 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001266 }
1267
Quentin Colombetac55b152014-09-16 22:36:07 +00001268 /// \brief Get the built value.
1269 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001270
1271 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001272 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001273 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1274 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1275 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001276 }
1277 };
1278
1279 /// \brief Build a sign extension instruction.
1280 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001281 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001282 public:
1283 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1284 /// result.
1285 /// sext Opnd to Ty.
1286 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001287 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001288 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001289 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1290 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001291 }
1292
Quentin Colombetac55b152014-09-16 22:36:07 +00001293 /// \brief Get the built value.
1294 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001295
1296 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001297 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001298 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1299 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1300 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001301 }
1302 };
1303
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001304 /// \brief Build a zero extension instruction.
1305 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001306 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001307 public:
1308 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1309 /// result.
1310 /// zext Opnd to Ty.
1311 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001312 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001313 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001314 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1315 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001316 }
1317
Quentin Colombetac55b152014-09-16 22:36:07 +00001318 /// \brief Get the built value.
1319 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001320
1321 /// \brief Remove the built instruction.
1322 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001323 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1324 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1325 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001326 }
1327 };
1328
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001329 /// \brief Mutate an instruction to another type.
1330 class TypeMutator : public TypePromotionAction {
1331 /// Record the original type.
1332 Type *OrigTy;
1333
1334 public:
1335 /// \brief Mutate the type of \p Inst into \p NewTy.
1336 TypeMutator(Instruction *Inst, Type *NewTy)
1337 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1338 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1339 << "\n");
1340 Inst->mutateType(NewTy);
1341 }
1342
1343 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001344 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001345 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1346 << "\n");
1347 Inst->mutateType(OrigTy);
1348 }
1349 };
1350
1351 /// \brief Replace the uses of an instruction by another instruction.
1352 class UsesReplacer : public TypePromotionAction {
1353 /// Helper structure to keep track of the replaced uses.
1354 struct InstructionAndIdx {
1355 /// The instruction using the instruction.
1356 Instruction *Inst;
1357 /// The index where this instruction is used for Inst.
1358 unsigned Idx;
1359 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1360 : Inst(Inst), Idx(Idx) {}
1361 };
1362
1363 /// Keep track of the original uses (pair Instruction, Index).
1364 SmallVector<InstructionAndIdx, 4> OriginalUses;
1365 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1366
1367 public:
1368 /// \brief Replace all the use of \p Inst by \p New.
1369 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1370 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1371 << "\n");
1372 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001373 for (Use &U : Inst->uses()) {
1374 Instruction *UserI = cast<Instruction>(U.getUser());
1375 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001376 }
1377 // Now, we can replace the uses.
1378 Inst->replaceAllUsesWith(New);
1379 }
1380
1381 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001382 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001383 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1384 for (use_iterator UseIt = OriginalUses.begin(),
1385 EndIt = OriginalUses.end();
1386 UseIt != EndIt; ++UseIt) {
1387 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1388 }
1389 }
1390 };
1391
1392 /// \brief Remove an instruction from the IR.
1393 class InstructionRemover : public TypePromotionAction {
1394 /// Original position of the instruction.
1395 InsertionHandler Inserter;
1396 /// Helper structure to hide all the link to the instruction. In other
1397 /// words, this helps to do as if the instruction was removed.
1398 OperandsHider Hider;
1399 /// Keep track of the uses replaced, if any.
1400 UsesReplacer *Replacer;
1401
1402 public:
1403 /// \brief Remove all reference of \p Inst and optinally replace all its
1404 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001405 /// \pre If !Inst->use_empty(), then New != nullptr
1406 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001407 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001408 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001409 if (New)
1410 Replacer = new UsesReplacer(Inst, New);
1411 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1412 Inst->removeFromParent();
1413 }
1414
1415 ~InstructionRemover() { delete Replacer; }
1416
1417 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001418 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001419
1420 /// \brief Resurrect the instruction and reassign it to the proper uses if
1421 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001422 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001423 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1424 Inserter.insert(Inst);
1425 if (Replacer)
1426 Replacer->undo();
1427 Hider.undo();
1428 }
1429 };
1430
1431public:
1432 /// Restoration point.
1433 /// The restoration point is a pointer to an action instead of an iterator
1434 /// because the iterator may be invalidated but not the pointer.
1435 typedef const TypePromotionAction *ConstRestorationPt;
1436 /// Advocate every changes made in that transaction.
1437 void commit();
1438 /// Undo all the changes made after the given point.
1439 void rollback(ConstRestorationPt Point);
1440 /// Get the current restoration point.
1441 ConstRestorationPt getRestorationPoint() const;
1442
1443 /// \name API for IR modification with state keeping to support rollback.
1444 /// @{
1445 /// Same as Instruction::setOperand.
1446 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1447 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001448 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001449 /// Same as Value::replaceAllUsesWith.
1450 void replaceAllUsesWith(Instruction *Inst, Value *New);
1451 /// Same as Value::mutateType.
1452 void mutateType(Instruction *Inst, Type *NewTy);
1453 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00001454 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001455 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001456 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001457 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001458 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001459 /// Same as Instruction::moveBefore.
1460 void moveBefore(Instruction *Inst, Instruction *Before);
1461 /// @}
1462
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001463private:
1464 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001465 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1466 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001467};
1468
1469void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1470 Value *NewVal) {
1471 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001472 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001473}
1474
1475void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1476 Value *NewVal) {
1477 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001478 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001479}
1480
1481void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1482 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001483 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001484}
1485
1486void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001487 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001488}
1489
Quentin Colombetac55b152014-09-16 22:36:07 +00001490Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1491 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001492 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001493 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001494 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001495 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001496}
1497
Quentin Colombetac55b152014-09-16 22:36:07 +00001498Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1499 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001500 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001501 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001502 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001503 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001504}
1505
Quentin Colombetac55b152014-09-16 22:36:07 +00001506Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1507 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001508 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001509 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001510 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001511 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001512}
1513
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001514void TypePromotionTransaction::moveBefore(Instruction *Inst,
1515 Instruction *Before) {
1516 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001517 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001518}
1519
1520TypePromotionTransaction::ConstRestorationPt
1521TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00001522 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001523}
1524
1525void TypePromotionTransaction::commit() {
1526 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00001527 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001528 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001529 Actions.clear();
1530}
1531
1532void TypePromotionTransaction::rollback(
1533 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00001534 while (!Actions.empty() && Point != Actions.back().get()) {
1535 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001536 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001537 }
1538}
1539
Chandler Carruthc8925912013-01-05 02:09:22 +00001540/// \brief A helper class for matching addressing modes.
1541///
1542/// This encapsulates the logic for matching the target-legal addressing modes.
1543class AddressingModeMatcher {
1544 SmallVectorImpl<Instruction*> &AddrModeInsts;
1545 const TargetLowering &TLI;
1546
1547 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1548 /// the memory instruction that we're computing this address for.
1549 Type *AccessTy;
1550 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001551
Chandler Carruthc8925912013-01-05 02:09:22 +00001552 /// AddrMode - This is the addressing mode that we're building up. This is
1553 /// part of the return value of this addressing mode matching stuff.
1554 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001555
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001556 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1557 const SetOfInstrs &InsertedTruncs;
1558 /// A map from the instructions to their type before promotion.
1559 InstrToOrigTy &PromotedInsts;
1560 /// The ongoing transaction where every action should be registered.
1561 TypePromotionTransaction &TPT;
1562
Chandler Carruthc8925912013-01-05 02:09:22 +00001563 /// IgnoreProfitability - This is set to true when we should not do
1564 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1565 /// always returns true.
1566 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001567
Chandler Carruthc8925912013-01-05 02:09:22 +00001568 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1569 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001570 Instruction *MI, ExtAddrMode &AM,
1571 const SetOfInstrs &InsertedTruncs,
1572 InstrToOrigTy &PromotedInsts,
1573 TypePromotionTransaction &TPT)
1574 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1575 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001576 IgnoreProfitability = false;
1577 }
1578public:
Stephen Lin837bba12013-07-15 17:55:02 +00001579
Chandler Carruthc8925912013-01-05 02:09:22 +00001580 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1581 /// give an access type of AccessTy. This returns a list of involved
1582 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001583 /// \p InsertedTruncs The truncate instruction inserted by other
1584 /// CodeGenPrepare
1585 /// optimizations.
1586 /// \p PromotedInsts maps the instructions to their type before promotion.
1587 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001588 static ExtAddrMode Match(Value *V, Type *AccessTy,
1589 Instruction *MemoryInst,
1590 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001591 const TargetLowering &TLI,
1592 const SetOfInstrs &InsertedTruncs,
1593 InstrToOrigTy &PromotedInsts,
1594 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001595 ExtAddrMode Result;
1596
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001597 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1598 MemoryInst, Result, InsertedTruncs,
1599 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001600 (void)Success; assert(Success && "Couldn't select *anything*?");
1601 return Result;
1602 }
1603private:
1604 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1605 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001606 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00001607 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00001608 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1609 ExtAddrMode &AMBefore,
1610 ExtAddrMode &AMAfter);
1611 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001612 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1613 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001614};
1615
1616/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1617/// Return true and update AddrMode if this addr mode is legal for the target,
1618/// false if not.
1619bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1620 unsigned Depth) {
1621 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1622 // mode. Just process that directly.
1623 if (Scale == 1)
1624 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001625
Chandler Carruthc8925912013-01-05 02:09:22 +00001626 // If the scale is 0, it takes nothing to add this.
1627 if (Scale == 0)
1628 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001629
Chandler Carruthc8925912013-01-05 02:09:22 +00001630 // If we already have a scale of this value, we can add to it, otherwise, we
1631 // need an available scale field.
1632 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1633 return false;
1634
1635 ExtAddrMode TestAddrMode = AddrMode;
1636
1637 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1638 // [A+B + A*7] -> [B+A*8].
1639 TestAddrMode.Scale += Scale;
1640 TestAddrMode.ScaledReg = ScaleReg;
1641
1642 // If the new address isn't legal, bail out.
1643 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1644 return false;
1645
1646 // It was legal, so commit it.
1647 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001648
Chandler Carruthc8925912013-01-05 02:09:22 +00001649 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1650 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1651 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00001652 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00001653 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1654 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1655 TestAddrMode.ScaledReg = AddLHS;
1656 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001657
Chandler Carruthc8925912013-01-05 02:09:22 +00001658 // If this addressing mode is legal, commit it and remember that we folded
1659 // this instruction.
1660 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1661 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1662 AddrMode = TestAddrMode;
1663 return true;
1664 }
1665 }
1666
1667 // Otherwise, not (x+c)*scale, just return what we have.
1668 return true;
1669}
1670
1671/// MightBeFoldableInst - This is a little filter, which returns true if an
1672/// addressing computation involving I might be folded into a load/store
1673/// accessing it. This doesn't need to be perfect, but needs to accept at least
1674/// the set of instructions that MatchOperationAddr can.
1675static bool MightBeFoldableInst(Instruction *I) {
1676 switch (I->getOpcode()) {
1677 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00001678 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00001679 // Don't touch identity bitcasts.
1680 if (I->getType() == I->getOperand(0)->getType())
1681 return false;
1682 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1683 case Instruction::PtrToInt:
1684 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1685 return true;
1686 case Instruction::IntToPtr:
1687 // We know the input is intptr_t, so this is foldable.
1688 return true;
1689 case Instruction::Add:
1690 return true;
1691 case Instruction::Mul:
1692 case Instruction::Shl:
1693 // Can only handle X*C and X << C.
1694 return isa<ConstantInt>(I->getOperand(1));
1695 case Instruction::GetElementPtr:
1696 return true;
1697 default:
1698 return false;
1699 }
1700}
1701
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001702/// \brief Hepler class to perform type promotion.
1703class TypePromotionHelper {
1704 /// \brief Utility function to check whether or not a sign extension of
1705 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1706 /// using the operands of \p Inst or promoting \p Inst.
1707 /// In other words, check if:
1708 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1709 /// #1 Promotion applies:
1710 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1711 /// #2 Operand reuses:
1712 /// sext opnd1 to ConsideredSExtType.
1713 /// \p PromotedInsts maps the instructions to their type before promotion.
1714 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1715 const InstrToOrigTy &PromotedInsts);
1716
1717 /// \brief Utility function to determine if \p OpIdx should be promoted when
1718 /// promoting \p Inst.
1719 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1720 if (isa<SelectInst>(Inst) && OpIdx == 0)
1721 return false;
1722 return true;
1723 }
1724
1725 /// \brief Utility function to promote the operand of \p SExt when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001726 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001727 /// \p PromotedInsts maps the instructions to their type before promotion.
1728 /// \p CreatedInsts[out] contains how many non-free instructions have been
1729 /// created to promote the operand of SExt.
1730 /// Should never be called directly.
1731 /// \return The promoted value which is used instead of SExt.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001732 static Value *promoteOperandForTruncAndAnyExt(Instruction *SExt,
1733 TypePromotionTransaction &TPT,
1734 InstrToOrigTy &PromotedInsts,
1735 unsigned &CreatedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001736
1737 /// \brief Utility function to promote the operand of \p SExt when this
1738 /// operand is promotable and is not a supported trunc or sext.
1739 /// \p PromotedInsts maps the instructions to their type before promotion.
1740 /// \p CreatedInsts[out] contains how many non-free instructions have been
1741 /// created to promote the operand of SExt.
1742 /// Should never be called directly.
1743 /// \return The promoted value which is used instead of SExt.
1744 static Value *promoteOperandForOther(Instruction *SExt,
1745 TypePromotionTransaction &TPT,
1746 InstrToOrigTy &PromotedInsts,
1747 unsigned &CreatedInsts);
1748
1749public:
1750 /// Type for the utility function that promotes the operand of SExt.
1751 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1752 InstrToOrigTy &PromotedInsts,
1753 unsigned &CreatedInsts);
1754 /// \brief Given a sign extend instruction \p SExt, return the approriate
1755 /// action to promote the operand of \p SExt instead of using SExt.
1756 /// \return NULL if no promotable action is possible with the current
1757 /// sign extension.
1758 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1759 /// the others CodeGenPrepare optimizations. This information is important
1760 /// because we do not want to promote these instructions as CodeGenPrepare
1761 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1762 /// \p PromotedInsts maps the instructions to their type before promotion.
1763 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1764 const TargetLowering &TLI,
1765 const InstrToOrigTy &PromotedInsts);
1766};
1767
1768bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1769 Type *ConsideredSExtType,
1770 const InstrToOrigTy &PromotedInsts) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001771 // We can always get through sext or zext.
1772 if (isa<SExtInst>(Inst) || isa<ZExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001773 return true;
1774
1775 // We can get through binary operator, if it is legal. In other words, the
1776 // binary operator must have a nuw or nsw flag.
1777 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1778 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1779 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1780 return true;
1781
1782 // Check if we can do the following simplification.
1783 // sext(trunc(sext)) --> sext
1784 if (!isa<TruncInst>(Inst))
1785 return false;
1786
1787 Value *OpndVal = Inst->getOperand(0);
1788 // Check if we can use this operand in the sext.
1789 // If the type is larger than the result type of the sign extension,
1790 // we cannot.
1791 if (OpndVal->getType()->getIntegerBitWidth() >
1792 ConsideredSExtType->getIntegerBitWidth())
1793 return false;
1794
1795 // If the operand of the truncate is not an instruction, we will not have
1796 // any information on the dropped bits.
1797 // (Actually we could for constant but it is not worth the extra logic).
1798 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1799 if (!Opnd)
1800 return false;
1801
1802 // Check if the source of the type is narrow enough.
1803 // I.e., check that trunc just drops sign extended bits.
1804 // #1 get the type of the operand.
1805 const Type *OpndType;
1806 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1807 if (It != PromotedInsts.end())
1808 OpndType = It->second;
1809 else if (isa<SExtInst>(Opnd))
1810 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1811 else
1812 return false;
1813
1814 // #2 check that the truncate just drop sign extended bits.
1815 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1816 return true;
1817
1818 return false;
1819}
1820
1821TypePromotionHelper::Action TypePromotionHelper::getAction(
1822 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1823 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1824 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1825 Type *SExtTy = SExt->getType();
1826 // If the operand of the sign extension is not an instruction, we cannot
1827 // get through.
1828 // If it, check we can get through.
1829 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
Craig Topperc0196b12014-04-14 00:51:57 +00001830 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001831
1832 // Do not promote if the operand has been added by codegenprepare.
1833 // Otherwise, it means we are undoing an optimization that is likely to be
1834 // redone, thus causing potential infinite loop.
1835 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00001836 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001837
1838 // SExt or Trunc instructions.
1839 // Return the related handler.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001840 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd) ||
1841 isa<ZExtInst>(SExtOpnd))
1842 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001843
1844 // Regular instruction.
1845 // Abort early if we will have to insert non-free instructions.
1846 if (!SExtOpnd->hasOneUse() &&
1847 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00001848 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001849 return promoteOperandForOther;
1850}
1851
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001852Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001853 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1854 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1855 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1856 // get through it and this method should not be called.
1857 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00001858 Value *ExtVal = SExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001859 if (isa<ZExtInst>(SExtOpnd)) {
1860 // Replace sext(zext(opnd))
1861 // => zext(opnd).
Quentin Colombetac55b152014-09-16 22:36:07 +00001862 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001863 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1864 TPT.replaceAllUsesWith(SExt, ZExt);
1865 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001866 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001867 } else {
1868 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1869 // => sext(opnd).
1870 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1871 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001872 CreatedInsts = 0;
1873
1874 // Remove dead code.
1875 if (SExtOpnd->use_empty())
1876 TPT.eraseInstruction(SExtOpnd);
1877
Quentin Colombet9dcb7242014-09-15 18:26:58 +00001878 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00001879 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1880 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
1881 return ExtVal;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001882
Quentin Colombet9dcb7242014-09-15 18:26:58 +00001883 // At this point we have: ext ty opnd to ty.
1884 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1885 Value *NextVal = ExtInst->getOperand(0);
1886 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001887 return NextVal;
1888}
1889
1890Value *
1891TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1892 TypePromotionTransaction &TPT,
1893 InstrToOrigTy &PromotedInsts,
1894 unsigned &CreatedInsts) {
1895 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1896 // get through it and this method should not be called.
1897 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1898 CreatedInsts = 0;
1899 if (!SExtOpnd->hasOneUse()) {
1900 // SExtOpnd will be promoted.
1901 // All its uses, but SExt, will need to use a truncated value of the
1902 // promoted version.
1903 // Create the truncate now.
Quentin Colombetac55b152014-09-16 22:36:07 +00001904 Value *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1905 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
1906 ITrunc->removeFromParent();
1907 // Insert it just after the definition.
1908 ITrunc->insertAfter(SExtOpnd);
1909 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001910
1911 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1912 // Restore the operand of SExt (which has been replace by the previous call
1913 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1914 TPT.setOperand(SExt, 0, SExtOpnd);
1915 }
1916
1917 // Get through the Instruction:
1918 // 1. Update its type.
1919 // 2. Replace the uses of SExt by Inst.
1920 // 3. Sign extend each operand that needs to be sign extended.
1921
1922 // Remember the original type of the instruction before promotion.
1923 // This is useful to know that the high bits are sign extended bits.
1924 PromotedInsts.insert(
1925 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1926 // Step #1.
1927 TPT.mutateType(SExtOpnd, SExt->getType());
1928 // Step #2.
1929 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1930 // Step #3.
1931 Instruction *SExtForOpnd = SExt;
1932
1933 DEBUG(dbgs() << "Propagate SExt to operands\n");
1934 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1935 ++OpIdx) {
1936 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1937 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1938 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1939 DEBUG(dbgs() << "No need to propagate\n");
1940 continue;
1941 }
1942 // Check if we can statically sign extend the operand.
1943 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1944 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1945 DEBUG(dbgs() << "Statically sign extend\n");
1946 TPT.setOperand(
1947 SExtOpnd, OpIdx,
1948 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1949 continue;
1950 }
1951 // UndefValue are typed, so we have to statically sign extend them.
1952 if (isa<UndefValue>(Opnd)) {
1953 DEBUG(dbgs() << "Statically sign extend\n");
1954 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1955 continue;
1956 }
1957
1958 // Otherwise we have to explicity sign extend the operand.
1959 // Check if SExt was reused to sign extend an operand.
1960 if (!SExtForOpnd) {
1961 // If yes, create a new one.
1962 DEBUG(dbgs() << "More operands to sext\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00001963 SExtForOpnd =
1964 cast<Instruction>(TPT.createSExt(SExt, Opnd, SExt->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001965 ++CreatedInsts;
1966 }
1967
1968 TPT.setOperand(SExtForOpnd, 0, Opnd);
1969
1970 // Move the sign extension before the insertion point.
1971 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1972 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1973 // If more sext are required, new instructions will have to be created.
Craig Topperc0196b12014-04-14 00:51:57 +00001974 SExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001975 }
1976 if (SExtForOpnd == SExt) {
1977 DEBUG(dbgs() << "Sign extension is useless now\n");
1978 TPT.eraseInstruction(SExt);
1979 }
1980 return SExtOpnd;
1981}
1982
Quentin Colombet867c5502014-02-14 22:23:22 +00001983/// IsPromotionProfitable - Check whether or not promoting an instruction
1984/// to a wider type was profitable.
1985/// \p MatchedSize gives the number of instructions that have been matched
1986/// in the addressing mode after the promotion was applied.
1987/// \p SizeWithPromotion gives the number of created instructions for
1988/// the promotion plus the number of instructions that have been
1989/// matched in the addressing mode before the promotion.
1990/// \p PromotedOperand is the value that has been promoted.
1991/// \return True if the promotion is profitable, false otherwise.
1992bool
1993AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1994 unsigned SizeWithPromotion,
1995 Value *PromotedOperand) const {
1996 // We folded less instructions than what we created to promote the operand.
1997 // This is not profitable.
1998 if (MatchedSize < SizeWithPromotion)
1999 return false;
2000 if (MatchedSize > SizeWithPromotion)
2001 return true;
2002 // The promotion is neutral but it may help folding the sign extension in
2003 // loads for instance.
2004 // Check that we did not create an illegal instruction.
2005 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2006 if (!PromotedInst)
2007 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00002008 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2009 // If the ISDOpcode is undefined, it was undefined before the promotion.
2010 if (!ISDOpcode)
2011 return true;
2012 // Otherwise, check if the promoted instruction is legal or not.
2013 return TLI.isOperationLegalOrCustom(ISDOpcode,
Quentin Colombet867c5502014-02-14 22:23:22 +00002014 EVT::getEVT(PromotedInst->getType()));
2015}
2016
Chandler Carruthc8925912013-01-05 02:09:22 +00002017/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2018/// fold the operation into the addressing mode. If so, update the addressing
2019/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002020/// If \p MovedAway is not NULL, it contains the information of whether or
2021/// not AddrInst has to be folded into the addressing mode on success.
2022/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2023/// because it has been moved away.
2024/// Thus AddrInst must not be added in the matched instructions.
2025/// This state can happen when AddrInst is a sext, since it may be moved away.
2026/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2027/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002028bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002029 unsigned Depth,
2030 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002031 // Avoid exponential behavior on extremely deep expression trees.
2032 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002033
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002034 // By default, all matched instructions stay in place.
2035 if (MovedAway)
2036 *MovedAway = false;
2037
Chandler Carruthc8925912013-01-05 02:09:22 +00002038 switch (Opcode) {
2039 case Instruction::PtrToInt:
2040 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2041 return MatchAddr(AddrInst->getOperand(0), Depth);
2042 case Instruction::IntToPtr:
2043 // This inttoptr is a no-op if the integer type is pointer sized.
2044 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002045 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002046 return MatchAddr(AddrInst->getOperand(0), Depth);
2047 return false;
2048 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002049 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002050 // BitCast is always a noop, and we can handle it as long as it is
2051 // int->int or pointer->pointer (we don't want int<->fp or something).
2052 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2053 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2054 // Don't touch identity bitcasts. These were probably put here by LSR,
2055 // and we don't want to mess around with them. Assume it knows what it
2056 // is doing.
2057 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2058 return MatchAddr(AddrInst->getOperand(0), Depth);
2059 return false;
2060 case Instruction::Add: {
2061 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2062 ExtAddrMode BackupAddrMode = AddrMode;
2063 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002064 // Start a transaction at this point.
2065 // The LHS may match but not the RHS.
2066 // Therefore, we need a higher level restoration point to undo partially
2067 // matched operation.
2068 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2069 TPT.getRestorationPoint();
2070
Chandler Carruthc8925912013-01-05 02:09:22 +00002071 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2072 MatchAddr(AddrInst->getOperand(0), Depth+1))
2073 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002074
Chandler Carruthc8925912013-01-05 02:09:22 +00002075 // Restore the old addr mode info.
2076 AddrMode = BackupAddrMode;
2077 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002078 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002079
Chandler Carruthc8925912013-01-05 02:09:22 +00002080 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2081 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2082 MatchAddr(AddrInst->getOperand(1), Depth+1))
2083 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002084
Chandler Carruthc8925912013-01-05 02:09:22 +00002085 // Otherwise we definitely can't merge the ADD in.
2086 AddrMode = BackupAddrMode;
2087 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002088 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002089 break;
2090 }
2091 //case Instruction::Or:
2092 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2093 //break;
2094 case Instruction::Mul:
2095 case Instruction::Shl: {
2096 // Can only handle X*C and X << C.
2097 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002098 if (!RHS)
2099 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002100 int64_t Scale = RHS->getSExtValue();
2101 if (Opcode == Instruction::Shl)
2102 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002103
Chandler Carruthc8925912013-01-05 02:09:22 +00002104 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2105 }
2106 case Instruction::GetElementPtr: {
2107 // Scan the GEP. We check it if it contains constant offsets and at most
2108 // one variable offset.
2109 int VariableOperand = -1;
2110 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002111
Chandler Carruthc8925912013-01-05 02:09:22 +00002112 int64_t ConstantOffset = 0;
2113 const DataLayout *TD = TLI.getDataLayout();
2114 gep_type_iterator GTI = gep_type_begin(AddrInst);
2115 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2116 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2117 const StructLayout *SL = TD->getStructLayout(STy);
2118 unsigned Idx =
2119 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2120 ConstantOffset += SL->getElementOffset(Idx);
2121 } else {
2122 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2123 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2124 ConstantOffset += CI->getSExtValue()*TypeSize;
2125 } else if (TypeSize) { // Scales of zero don't do anything.
2126 // We only allow one variable index at the moment.
2127 if (VariableOperand != -1)
2128 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002129
Chandler Carruthc8925912013-01-05 02:09:22 +00002130 // Remember the variable index.
2131 VariableOperand = i;
2132 VariableScale = TypeSize;
2133 }
2134 }
2135 }
Stephen Lin837bba12013-07-15 17:55:02 +00002136
Chandler Carruthc8925912013-01-05 02:09:22 +00002137 // A common case is for the GEP to only do a constant offset. In this case,
2138 // just add it to the disp field and check validity.
2139 if (VariableOperand == -1) {
2140 AddrMode.BaseOffs += ConstantOffset;
2141 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2142 // Check to see if we can fold the base pointer in too.
2143 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2144 return true;
2145 }
2146 AddrMode.BaseOffs -= ConstantOffset;
2147 return false;
2148 }
2149
2150 // Save the valid addressing mode in case we can't match.
2151 ExtAddrMode BackupAddrMode = AddrMode;
2152 unsigned OldSize = AddrModeInsts.size();
2153
2154 // See if the scale and offset amount is valid for this target.
2155 AddrMode.BaseOffs += ConstantOffset;
2156
2157 // Match the base operand of the GEP.
2158 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2159 // If it couldn't be matched, just stuff the value in a register.
2160 if (AddrMode.HasBaseReg) {
2161 AddrMode = BackupAddrMode;
2162 AddrModeInsts.resize(OldSize);
2163 return false;
2164 }
2165 AddrMode.HasBaseReg = true;
2166 AddrMode.BaseReg = AddrInst->getOperand(0);
2167 }
2168
2169 // Match the remaining variable portion of the GEP.
2170 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2171 Depth)) {
2172 // If it couldn't be matched, try stuffing the base into a register
2173 // instead of matching it, and retrying the match of the scale.
2174 AddrMode = BackupAddrMode;
2175 AddrModeInsts.resize(OldSize);
2176 if (AddrMode.HasBaseReg)
2177 return false;
2178 AddrMode.HasBaseReg = true;
2179 AddrMode.BaseReg = AddrInst->getOperand(0);
2180 AddrMode.BaseOffs += ConstantOffset;
2181 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2182 VariableScale, Depth)) {
2183 // If even that didn't work, bail.
2184 AddrMode = BackupAddrMode;
2185 AddrModeInsts.resize(OldSize);
2186 return false;
2187 }
2188 }
2189
2190 return true;
2191 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002192 case Instruction::SExt: {
Sanjay Patelab60d042014-07-16 21:08:10 +00002193 Instruction *SExt = dyn_cast<Instruction>(AddrInst);
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002194 if (!SExt)
2195 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002196
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002197 // Try to move this sext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002198 // Ask for a method for doing so.
2199 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
2200 SExt, InsertedTruncs, TLI, PromotedInsts);
2201 if (!TPH)
2202 return false;
2203
2204 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2205 TPT.getRestorationPoint();
2206 unsigned CreatedInsts = 0;
2207 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
2208 // SExt has been moved away.
2209 // Thus either it will be rematched later in the recursive calls or it is
2210 // gone. Anyway, we must not fold it into the addressing mode at this point.
2211 // E.g.,
2212 // op = add opnd, 1
2213 // idx = sext op
2214 // addr = gep base, idx
2215 // is now:
2216 // promotedOpnd = sext opnd <- no match here
2217 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2218 // addr = gep base, op <- match
2219 if (MovedAway)
2220 *MovedAway = true;
2221
2222 assert(PromotedOperand &&
2223 "TypePromotionHelper should have filtered out those cases");
2224
2225 ExtAddrMode BackupAddrMode = AddrMode;
2226 unsigned OldSize = AddrModeInsts.size();
2227
2228 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002229 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2230 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002231 AddrMode = BackupAddrMode;
2232 AddrModeInsts.resize(OldSize);
2233 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2234 TPT.rollback(LastKnownGood);
2235 return false;
2236 }
2237 return true;
2238 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002239 }
2240 return false;
2241}
2242
2243/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2244/// addressing mode. If Addr can't be added to AddrMode this returns false and
2245/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2246/// or intptr_t for the target.
2247///
2248bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002249 // Start a transaction at this point that we will rollback if the matching
2250 // fails.
2251 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2252 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002253 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2254 // Fold in immediates if legal for the target.
2255 AddrMode.BaseOffs += CI->getSExtValue();
2256 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2257 return true;
2258 AddrMode.BaseOffs -= CI->getSExtValue();
2259 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2260 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002261 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002262 AddrMode.BaseGV = GV;
2263 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2264 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002265 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002266 }
2267 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2268 ExtAddrMode BackupAddrMode = AddrMode;
2269 unsigned OldSize = AddrModeInsts.size();
2270
2271 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002272 bool MovedAway = false;
2273 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2274 // This instruction may have been move away. If so, there is nothing
2275 // to check here.
2276 if (MovedAway)
2277 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002278 // Okay, it's possible to fold this. Check to see if it is actually
2279 // *profitable* to do so. We use a simple cost model to avoid increasing
2280 // register pressure too much.
2281 if (I->hasOneUse() ||
2282 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2283 AddrModeInsts.push_back(I);
2284 return true;
2285 }
Stephen Lin837bba12013-07-15 17:55:02 +00002286
Chandler Carruthc8925912013-01-05 02:09:22 +00002287 // It isn't profitable to do this, roll back.
2288 //cerr << "NOT FOLDING: " << *I;
2289 AddrMode = BackupAddrMode;
2290 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002291 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002292 }
2293 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2294 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2295 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002297 } else if (isa<ConstantPointerNull>(Addr)) {
2298 // Null pointer gets folded without affecting the addressing mode.
2299 return true;
2300 }
2301
2302 // Worse case, the target should support [reg] addressing modes. :)
2303 if (!AddrMode.HasBaseReg) {
2304 AddrMode.HasBaseReg = true;
2305 AddrMode.BaseReg = Addr;
2306 // Still check for legality in case the target supports [imm] but not [i+r].
2307 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2308 return true;
2309 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002310 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002311 }
2312
2313 // If the base register is already taken, see if we can do [r+r].
2314 if (AddrMode.Scale == 0) {
2315 AddrMode.Scale = 1;
2316 AddrMode.ScaledReg = Addr;
2317 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2318 return true;
2319 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002320 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002321 }
2322 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002323 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002324 return false;
2325}
2326
2327/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2328/// inline asm call are due to memory operands. If so, return true, otherwise
2329/// return false.
2330static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2331 const TargetLowering &TLI) {
2332 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2333 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2334 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002335
Chandler Carruthc8925912013-01-05 02:09:22 +00002336 // Compute the constraint code and ConstraintType to use.
2337 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2338
2339 // If this asm operand is our Value*, and if it isn't an indirect memory
2340 // operand, we can't fold it!
2341 if (OpInfo.CallOperandVal == OpVal &&
2342 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2343 !OpInfo.isIndirect))
2344 return false;
2345 }
2346
2347 return true;
2348}
2349
2350/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2351/// memory use. If we find an obviously non-foldable instruction, return true.
2352/// Add the ultimately found memory instructions to MemoryUses.
2353static bool FindAllMemoryUses(Instruction *I,
2354 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Craig Topper71b7b682014-08-21 05:55:13 +00002355 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
Chandler Carruthc8925912013-01-05 02:09:22 +00002356 const TargetLowering &TLI) {
2357 // If we already considered this instruction, we're done.
2358 if (!ConsideredInsts.insert(I))
2359 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002360
Chandler Carruthc8925912013-01-05 02:09:22 +00002361 // If this is an obviously unfoldable instruction, bail out.
2362 if (!MightBeFoldableInst(I))
2363 return true;
2364
2365 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002366 for (Use &U : I->uses()) {
2367 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002368
Chandler Carruthcdf47882014-03-09 03:16:01 +00002369 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2370 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002371 continue;
2372 }
Stephen Lin837bba12013-07-15 17:55:02 +00002373
Chandler Carruthcdf47882014-03-09 03:16:01 +00002374 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2375 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002376 if (opNo == 0) return true; // Storing addr, not into addr.
2377 MemoryUses.push_back(std::make_pair(SI, opNo));
2378 continue;
2379 }
Stephen Lin837bba12013-07-15 17:55:02 +00002380
Chandler Carruthcdf47882014-03-09 03:16:01 +00002381 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002382 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2383 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002384
Chandler Carruthc8925912013-01-05 02:09:22 +00002385 // If this is a memory operand, we're cool, otherwise bail out.
2386 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2387 return true;
2388 continue;
2389 }
Stephen Lin837bba12013-07-15 17:55:02 +00002390
Chandler Carruthcdf47882014-03-09 03:16:01 +00002391 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002392 return true;
2393 }
2394
2395 return false;
2396}
2397
2398/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2399/// the use site that we're folding it into. If so, there is no cost to
2400/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2401/// that we know are live at the instruction already.
2402bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2403 Value *KnownLive2) {
2404 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002405 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002406 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002407
Chandler Carruthc8925912013-01-05 02:09:22 +00002408 // All values other than instructions and arguments (e.g. constants) are live.
2409 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002410
Chandler Carruthc8925912013-01-05 02:09:22 +00002411 // If Val is a constant sized alloca in the entry block, it is live, this is
2412 // true because it is just a reference to the stack/frame pointer, which is
2413 // live for the whole function.
2414 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2415 if (AI->isStaticAlloca())
2416 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002417
Chandler Carruthc8925912013-01-05 02:09:22 +00002418 // Check to see if this value is already used in the memory instruction's
2419 // block. If so, it's already live into the block at the very least, so we
2420 // can reasonably fold it.
2421 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2422}
2423
2424/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2425/// mode of the machine to fold the specified instruction into a load or store
2426/// that ultimately uses it. However, the specified instruction has multiple
2427/// uses. Given this, it may actually increase register pressure to fold it
2428/// into the load. For example, consider this code:
2429///
2430/// X = ...
2431/// Y = X+1
2432/// use(Y) -> nonload/store
2433/// Z = Y+1
2434/// load Z
2435///
2436/// In this case, Y has multiple uses, and can be folded into the load of Z
2437/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2438/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2439/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2440/// number of computations either.
2441///
2442/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2443/// X was live across 'load Z' for other reasons, we actually *would* want to
2444/// fold the addressing mode in the Z case. This would make Y die earlier.
2445bool AddressingModeMatcher::
2446IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2447 ExtAddrMode &AMAfter) {
2448 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002449
Chandler Carruthc8925912013-01-05 02:09:22 +00002450 // AMBefore is the addressing mode before this instruction was folded into it,
2451 // and AMAfter is the addressing mode after the instruction was folded. Get
2452 // the set of registers referenced by AMAfter and subtract out those
2453 // referenced by AMBefore: this is the set of values which folding in this
2454 // address extends the lifetime of.
2455 //
2456 // Note that there are only two potential values being referenced here,
2457 // BaseReg and ScaleReg (global addresses are always available, as are any
2458 // folded immediates).
2459 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002460
Chandler Carruthc8925912013-01-05 02:09:22 +00002461 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2462 // lifetime wasn't extended by adding this instruction.
2463 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002464 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002465 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002466 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002467
2468 // If folding this instruction (and it's subexprs) didn't extend any live
2469 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002470 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002471 return true;
2472
2473 // If all uses of this instruction are ultimately load/store/inlineasm's,
2474 // check to see if their addressing modes will include this instruction. If
2475 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2476 // uses.
2477 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2478 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2479 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2480 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002481
Chandler Carruthc8925912013-01-05 02:09:22 +00002482 // Now that we know that all uses of this instruction are part of a chain of
2483 // computation involving only operations that could theoretically be folded
2484 // into a memory use, loop over each of these uses and see if they could
2485 // *actually* fold the instruction.
2486 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2487 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2488 Instruction *User = MemoryUses[i].first;
2489 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002490
Chandler Carruthc8925912013-01-05 02:09:22 +00002491 // Get the access type of this use. If the use isn't a pointer, we don't
2492 // know what it accesses.
2493 Value *Address = User->getOperand(OpNo);
2494 if (!Address->getType()->isPointerTy())
2495 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002496 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002497
Chandler Carruthc8925912013-01-05 02:09:22 +00002498 // Do a match against the root of this address, ignoring profitability. This
2499 // will tell us if the addressing mode for the memory operation will
2500 // *actually* cover the shared instruction.
2501 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002502 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2503 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002504 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002505 MemoryInst, Result, InsertedTruncs,
2506 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002507 Matcher.IgnoreProfitability = true;
2508 bool Success = Matcher.MatchAddr(Address, 0);
2509 (void)Success; assert(Success && "Couldn't select *anything*?");
2510
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002511 // The match was to check the profitability, the changes made are not
2512 // part of the original matcher. Therefore, they should be dropped
2513 // otherwise the original matcher will not present the right state.
2514 TPT.rollback(LastKnownGood);
2515
Chandler Carruthc8925912013-01-05 02:09:22 +00002516 // If the match didn't cover I, then it won't be shared by it.
2517 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2518 I) == MatchedAddrModeInsts.end())
2519 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002520
Chandler Carruthc8925912013-01-05 02:09:22 +00002521 MatchedAddrModeInsts.clear();
2522 }
Stephen Lin837bba12013-07-15 17:55:02 +00002523
Chandler Carruthc8925912013-01-05 02:09:22 +00002524 return true;
2525}
2526
2527} // end anonymous namespace
2528
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002529/// IsNonLocalValue - Return true if the specified values are defined in a
2530/// different basic block than BB.
2531static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2532 if (Instruction *I = dyn_cast<Instruction>(V))
2533 return I->getParent() != BB;
2534 return false;
2535}
2536
Bob Wilson53bdae32009-12-03 21:47:07 +00002537/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002538/// addressing modes that can do significant amounts of computation. As such,
2539/// instruction selection will try to get the load or store to do as much
2540/// computation as possible for the program. The problem is that isel can only
2541/// see within a single block. As such, we sink as much legal addressing mode
2542/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002543///
2544/// This method is used to optimize both load/store and inline asms with memory
2545/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002546bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002547 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002548 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002549
2550 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002551 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002552 SmallVector<Value*, 8> worklist;
2553 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002554 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002555
Owen Anderson8ba5f392010-11-27 08:15:55 +00002556 // Use a worklist to iteratively look through PHI nodes, and ensure that
2557 // the addressing mode obtained from the non-PHI roots of the graph
2558 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00002559 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002560 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002561 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002562 SmallVector<Instruction*, 16> AddrModeInsts;
2563 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002564 TypePromotionTransaction TPT;
2565 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2566 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002567 while (!worklist.empty()) {
2568 Value *V = worklist.back();
2569 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002570
Owen Anderson8ba5f392010-11-27 08:15:55 +00002571 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002572 if (!Visited.insert(V)) {
Craig Topperc0196b12014-04-14 00:51:57 +00002573 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002574 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002575 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002576
Owen Anderson8ba5f392010-11-27 08:15:55 +00002577 // For a PHI node, push all of its incoming values.
2578 if (PHINode *P = dyn_cast<PHINode>(V)) {
2579 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2580 worklist.push_back(P->getIncomingValue(i));
2581 continue;
2582 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002583
Owen Anderson8ba5f392010-11-27 08:15:55 +00002584 // For non-PHIs, determine the addressing mode being computed.
2585 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002586 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2587 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2588 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002589
2590 // This check is broken into two cases with very similar code to avoid using
2591 // getNumUses() as much as possible. Some values have a lot of uses, so
2592 // calling getNumUses() unconditionally caused a significant compile-time
2593 // regression.
2594 if (!Consensus) {
2595 Consensus = V;
2596 AddrMode = NewAddrMode;
2597 AddrModeInsts = NewAddrModeInsts;
2598 continue;
2599 } else if (NewAddrMode == AddrMode) {
2600 if (!IsNumUsesConsensusValid) {
2601 NumUsesConsensus = Consensus->getNumUses();
2602 IsNumUsesConsensusValid = true;
2603 }
2604
2605 // Ensure that the obtained addressing mode is equivalent to that obtained
2606 // for all other roots of the PHI traversal. Also, when choosing one
2607 // such root as representative, select the one with the most uses in order
2608 // to keep the cost modeling heuristics in AddressingModeMatcher
2609 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002610 unsigned NumUses = V->getNumUses();
2611 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002612 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002613 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002614 AddrModeInsts = NewAddrModeInsts;
2615 }
2616 continue;
2617 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002618
Craig Topperc0196b12014-04-14 00:51:57 +00002619 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002620 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002621 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002622
Owen Anderson8ba5f392010-11-27 08:15:55 +00002623 // If the addressing mode couldn't be determined, or if multiple different
2624 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002625 if (!Consensus) {
2626 TPT.rollback(LastKnownGood);
2627 return false;
2628 }
2629 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002630
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002631 // Check to see if any of the instructions supersumed by this addr mode are
2632 // non-local to I's BB.
2633 bool AnyNonLocal = false;
2634 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002635 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002636 AnyNonLocal = true;
2637 break;
2638 }
2639 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002640
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002641 // If all the instructions matched are already in this BB, don't do anything.
2642 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002643 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002644 return false;
2645 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002646
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002647 // Insert this computation right after this user. Since our caller is
2648 // scanning from the top of the BB to the bottom, reuse of the expr are
2649 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002650 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002651
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002652 // Now that we determined the addressing expression we want to use and know
2653 // that we have to sink it into this block. Check to see if we have already
2654 // done this for some other load/store instr in this block. If so, reuse the
2655 // computation.
2656 Value *&SunkAddr = SunkAddrs[Addr];
2657 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002658 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002659 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002660 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002661 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00002662 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2663 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2664 // By default, we use the GEP-based method when AA is used later. This
2665 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2666 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002667 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00002668 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002669 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002670
2671 // First, find the pointer.
2672 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2673 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002674 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002675 }
2676
2677 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2678 // We can't add more than one pointer together, nor can we scale a
2679 // pointer (both of which seem meaningless).
2680 if (ResultPtr || AddrMode.Scale != 1)
2681 return false;
2682
2683 ResultPtr = AddrMode.ScaledReg;
2684 AddrMode.Scale = 0;
2685 }
2686
2687 if (AddrMode.BaseGV) {
2688 if (ResultPtr)
2689 return false;
2690
2691 ResultPtr = AddrMode.BaseGV;
2692 }
2693
2694 // If the real base value actually came from an inttoptr, then the matcher
2695 // will look through it and provide only the integer value. In that case,
2696 // use it here.
2697 if (!ResultPtr && AddrMode.BaseReg) {
2698 ResultPtr =
2699 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00002700 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002701 } else if (!ResultPtr && AddrMode.Scale == 1) {
2702 ResultPtr =
2703 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2704 AddrMode.Scale = 0;
2705 }
2706
2707 if (!ResultPtr &&
2708 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2709 SunkAddr = Constant::getNullValue(Addr->getType());
2710 } else if (!ResultPtr) {
2711 return false;
2712 } else {
2713 Type *I8PtrTy =
2714 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2715
2716 // Start with the base register. Do this first so that subsequent address
2717 // matching finds it last, which will prevent it from trying to match it
2718 // as the scaled value in case it happens to be a mul. That would be
2719 // problematic if we've sunk a different mul for the scale, because then
2720 // we'd end up sinking both muls.
2721 if (AddrMode.BaseReg) {
2722 Value *V = AddrMode.BaseReg;
2723 if (V->getType() != IntPtrTy)
2724 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2725
2726 ResultIndex = V;
2727 }
2728
2729 // Add the scale value.
2730 if (AddrMode.Scale) {
2731 Value *V = AddrMode.ScaledReg;
2732 if (V->getType() == IntPtrTy) {
2733 // done.
2734 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2735 cast<IntegerType>(V->getType())->getBitWidth()) {
2736 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2737 } else {
2738 // It is only safe to sign extend the BaseReg if we know that the math
2739 // required to create it did not overflow before we extend it. Since
2740 // the original IR value was tossed in favor of a constant back when
2741 // the AddrMode was created we need to bail out gracefully if widths
2742 // do not match instead of extending it.
2743 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2744 if (I && (ResultIndex != AddrMode.BaseReg))
2745 I->eraseFromParent();
2746 return false;
2747 }
2748
2749 if (AddrMode.Scale != 1)
2750 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2751 "sunkaddr");
2752 if (ResultIndex)
2753 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2754 else
2755 ResultIndex = V;
2756 }
2757
2758 // Add in the Base Offset if present.
2759 if (AddrMode.BaseOffs) {
2760 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2761 if (ResultIndex) {
2762 // We need to add this separately from the scale above to help with
2763 // SDAG consecutive load/store merging.
2764 if (ResultPtr->getType() != I8PtrTy)
2765 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2766 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2767 }
2768
2769 ResultIndex = V;
2770 }
2771
2772 if (!ResultIndex) {
2773 SunkAddr = ResultPtr;
2774 } else {
2775 if (ResultPtr->getType() != I8PtrTy)
2776 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2777 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2778 }
2779
2780 if (SunkAddr->getType() != Addr->getType())
2781 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2782 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002783 } else {
David Greene74e2d492010-01-05 01:27:11 +00002784 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002785 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002786 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002787 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00002788
2789 // Start with the base register. Do this first so that subsequent address
2790 // matching finds it last, which will prevent it from trying to match it
2791 // as the scaled value in case it happens to be a mul. That would be
2792 // problematic if we've sunk a different mul for the scale, because then
2793 // we'd end up sinking both muls.
2794 if (AddrMode.BaseReg) {
2795 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002796 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002797 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002798 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002799 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002800 Result = V;
2801 }
2802
2803 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002804 if (AddrMode.Scale) {
2805 Value *V = AddrMode.ScaledReg;
2806 if (V->getType() == IntPtrTy) {
2807 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002808 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002809 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002810 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2811 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002812 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002813 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002814 // It is only safe to sign extend the BaseReg if we know that the math
2815 // required to create it did not overflow before we extend it. Since
2816 // the original IR value was tossed in favor of a constant back when
2817 // the AddrMode was created we need to bail out gracefully if widths
2818 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00002819 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00002820 if (I && (Result != AddrMode.BaseReg))
2821 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002822 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002823 }
2824 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002825 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2826 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002827 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002828 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002829 else
2830 Result = V;
2831 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002832
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002833 // Add in the BaseGV if present.
2834 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002835 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002836 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002837 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002838 else
2839 Result = V;
2840 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002841
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002842 // Add in the Base Offset if present.
2843 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002844 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002845 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002846 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002847 else
2848 Result = V;
2849 }
2850
Craig Topperc0196b12014-04-14 00:51:57 +00002851 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002852 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002853 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002854 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002855 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002856
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002857 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002858
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002859 // If we have no uses, recursively delete the value and all dead instructions
2860 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002861 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002862 // This can cause recursive deletion, which can invalidate our iterator.
2863 // Use a WeakVH to hold onto it in case this happens.
2864 WeakVH IterHandle(CurInstIterator);
2865 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002866
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002867 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002868
2869 if (IterHandle != CurInstIterator) {
2870 // If the iterator instruction was recursively deleted, start over at the
2871 // start of the block.
2872 CurInstIterator = BB->begin();
2873 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002874 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002875 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002876 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002877 return true;
2878}
2879
Evan Cheng1da25002008-02-26 02:42:37 +00002880/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002881/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002882/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002883bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002884 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002885
Nadav Rotem465834c2012-07-24 10:51:42 +00002886 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002887 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002888 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002889 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2890 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002891
Evan Cheng1da25002008-02-26 02:42:37 +00002892 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002893 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002894
Eli Friedman666bbe32008-02-26 18:37:49 +00002895 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2896 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002897 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002898 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002899 } else if (OpInfo.Type == InlineAsm::isInput)
2900 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002901 }
2902
2903 return MadeChange;
2904}
2905
Dan Gohman99429a02009-10-16 20:59:35 +00002906/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2907/// basic block as the load, unless conditions are unfavorable. This allows
2908/// SelectionDAG to fold the extend into the load.
2909///
2910bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2911 // Look for a load being extended.
2912 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2913 if (!LI) return false;
2914
2915 // If they're already in the same block, there's nothing to do.
2916 if (LI->getParent() == I->getParent())
2917 return false;
2918
2919 // If the load has other users and the truncate is not free, this probably
2920 // isn't worthwhile.
2921 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002922 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2923 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002924 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002925 return false;
2926
2927 // Check whether the target supports casts folded into loads.
2928 unsigned LType;
2929 if (isa<ZExtInst>(I))
2930 LType = ISD::ZEXTLOAD;
2931 else {
2932 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2933 LType = ISD::SEXTLOAD;
2934 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002935 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002936 return false;
2937
2938 // Move the extend into the same block as the load, so that SelectionDAG
2939 // can fold it.
2940 I->removeFromParent();
2941 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002942 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002943 return true;
2944}
2945
Evan Chengd3d80172007-12-05 23:58:20 +00002946bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2947 BasicBlock *DefBB = I->getParent();
2948
Bob Wilsonff714f92010-09-21 21:44:14 +00002949 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002950 // other uses of the source with result of extension.
2951 Value *Src = I->getOperand(0);
2952 if (Src->hasOneUse())
2953 return false;
2954
Evan Cheng2011df42007-12-13 07:50:36 +00002955 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002956 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002957 return false;
2958
Evan Cheng7bc89422007-12-12 00:51:06 +00002959 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002960 // this block.
2961 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002962 return false;
2963
Evan Chengd3d80172007-12-05 23:58:20 +00002964 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002965 for (User *U : I->users()) {
2966 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00002967
2968 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002969 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00002970 if (UserBB == DefBB) continue;
2971 DefIsLiveOut = true;
2972 break;
2973 }
2974 if (!DefIsLiveOut)
2975 return false;
2976
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002977 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002978 for (User *U : Src->users()) {
2979 Instruction *UI = cast<Instruction>(U);
2980 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00002981 if (UserBB == DefBB) continue;
2982 // Be conservative. We don't want this xform to end up introducing
2983 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002984 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002985 return false;
2986 }
2987
Evan Chengd3d80172007-12-05 23:58:20 +00002988 // InsertedTruncs - Only insert one trunc in each block once.
2989 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2990
2991 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002992 for (Use &U : Src->uses()) {
2993 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00002994
2995 // Figure out which BB this ext is used in.
2996 BasicBlock *UserBB = User->getParent();
2997 if (UserBB == DefBB) continue;
2998
2999 // Both src and def are live in this block. Rewrite the use.
3000 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3001
3002 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003003 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003004 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003005 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003006 }
3007
3008 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003009 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003010 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003011 MadeChange = true;
3012 }
3013
3014 return MadeChange;
3015}
3016
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003017/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3018/// turned into an explicit branch.
3019static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3020 // FIXME: This should use the same heuristics as IfConversion to determine
3021 // whether a select is better represented as a branch. This requires that
3022 // branch probability metadata is preserved for the select, which is not the
3023 // case currently.
3024
3025 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3026
3027 // If the branch is predicted right, an out of order CPU can avoid blocking on
3028 // the compare. Emit cmovs on compares with a memory operand as branches to
3029 // avoid stalls on the load from memory. If the compare has more than one use
3030 // there's probably another cmov or setcc around so it's not worth emitting a
3031 // branch.
3032 if (!Cmp)
3033 return false;
3034
3035 Value *CmpOp0 = Cmp->getOperand(0);
3036 Value *CmpOp1 = Cmp->getOperand(1);
3037
3038 // We check that the memory operand has one use to avoid uses of the loaded
3039 // value directly after the compare, making branches unprofitable.
3040 return Cmp->hasOneUse() &&
3041 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3042 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3043}
3044
3045
Nadav Rotem9d832022012-09-02 12:10:19 +00003046/// If we have a SelectInst that will likely profit from branch prediction,
3047/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003048bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003049 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3050
3051 // Can we convert the 'select' to CF ?
3052 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003053 return false;
3054
Nadav Rotem9d832022012-09-02 12:10:19 +00003055 TargetLowering::SelectSupportKind SelectKind;
3056 if (VectorCond)
3057 SelectKind = TargetLowering::VectorMaskSelect;
3058 else if (SI->getType()->isVectorTy())
3059 SelectKind = TargetLowering::ScalarCondVectorVal;
3060 else
3061 SelectKind = TargetLowering::ScalarValSelect;
3062
3063 // Do we have efficient codegen support for this kind of 'selects' ?
3064 if (TLI->isSelectSupported(SelectKind)) {
3065 // We have efficient codegen support for the select instruction.
3066 // Check if it is profitable to keep this 'select'.
3067 if (!TLI->isPredictableSelectExpensive() ||
3068 !isFormingBranchFromSelectProfitable(SI))
3069 return false;
3070 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003071
3072 ModifiedDT = true;
3073
3074 // First, we split the block containing the select into 2 blocks.
3075 BasicBlock *StartBlock = SI->getParent();
3076 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3077 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3078
3079 // Create a new block serving as the landing pad for the branch.
3080 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3081 NextBlock->getParent(), NextBlock);
3082
3083 // Move the unconditional branch from the block with the select in it into our
3084 // landing pad block.
3085 StartBlock->getTerminator()->eraseFromParent();
3086 BranchInst::Create(NextBlock, SmallBlock);
3087
3088 // Insert the real conditional branch based on the original condition.
3089 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3090
3091 // The select itself is replaced with a PHI Node.
3092 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3093 PN->takeName(SI);
3094 PN->addIncoming(SI->getTrueValue(), StartBlock);
3095 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3096 SI->replaceAllUsesWith(PN);
3097 SI->eraseFromParent();
3098
3099 // Instruct OptimizeBlock to skip to the next block.
3100 CurInstIterator = StartBlock->end();
3101 ++NumSelectsExpanded;
3102 return true;
3103}
3104
Benjamin Kramer573ff362014-03-01 17:24:40 +00003105static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003106 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3107 int SplatElem = -1;
3108 for (unsigned i = 0; i < Mask.size(); ++i) {
3109 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3110 return false;
3111 SplatElem = Mask[i];
3112 }
3113
3114 return true;
3115}
3116
3117/// Some targets have expensive vector shifts if the lanes aren't all the same
3118/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3119/// it's often worth sinking a shufflevector splat down to its use so that
3120/// codegen can spot all lanes are identical.
3121bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3122 BasicBlock *DefBB = SVI->getParent();
3123
3124 // Only do this xform if variable vector shifts are particularly expensive.
3125 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3126 return false;
3127
3128 // We only expect better codegen by sinking a shuffle if we can recognise a
3129 // constant splat.
3130 if (!isBroadcastShuffle(SVI))
3131 return false;
3132
3133 // InsertedShuffles - Only insert a shuffle in each block once.
3134 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3135
3136 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003137 for (User *U : SVI->users()) {
3138 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003139
3140 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003141 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003142 if (UserBB == DefBB) continue;
3143
3144 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003145 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003146
3147 // Everything checks out, sink the shuffle if the user's block doesn't
3148 // already have a copy.
3149 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3150
3151 if (!InsertedShuffle) {
3152 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3153 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3154 SVI->getOperand(1),
3155 SVI->getOperand(2), "", InsertPt);
3156 }
3157
Chandler Carruthcdf47882014-03-09 03:16:01 +00003158 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003159 MadeChange = true;
3160 }
3161
3162 // If we removed all uses, nuke the shuffle.
3163 if (SVI->use_empty()) {
3164 SVI->eraseFromParent();
3165 MadeChange = true;
3166 }
3167
3168 return MadeChange;
3169}
3170
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003171bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003172 if (PHINode *P = dyn_cast<PHINode>(I)) {
3173 // It is possible for very late stage optimizations (such as SimplifyCFG)
3174 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3175 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00003176 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00003177 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003178 P->replaceAllUsesWith(V);
3179 P->eraseFromParent();
3180 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00003181 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003182 }
Chris Lattneree588de2011-01-15 07:29:01 +00003183 return false;
3184 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003185
Chris Lattneree588de2011-01-15 07:29:01 +00003186 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003187 // If the source of the cast is a constant, then this should have
3188 // already been constant folded. The only reason NOT to constant fold
3189 // it is if something (e.g. LSR) was careful to place the constant
3190 // evaluation in a block other than then one that uses it (e.g. to hoist
3191 // the address of globals out of a loop). If this is the case, we don't
3192 // want to forward-subst the cast.
3193 if (isa<Constant>(CI->getOperand(0)))
3194 return false;
3195
Chris Lattneree588de2011-01-15 07:29:01 +00003196 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3197 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003198
Chris Lattneree588de2011-01-15 07:29:01 +00003199 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00003200 /// Sink a zext or sext into its user blocks if the target type doesn't
3201 /// fit in one register
3202 if (TLI && TLI->getTypeAction(CI->getContext(),
3203 TLI->getValueType(CI->getType())) ==
3204 TargetLowering::TypeExpandInteger) {
3205 return SinkCast(CI);
3206 } else {
3207 bool MadeChange = MoveExtToFormExtLoad(I);
3208 return MadeChange | OptimizeExtUses(I);
3209 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003210 }
Chris Lattneree588de2011-01-15 07:29:01 +00003211 return false;
3212 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003213
Chris Lattneree588de2011-01-15 07:29:01 +00003214 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00003215 if (!TLI || !TLI->hasMultipleConditionRegisters())
3216 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00003217
Chris Lattneree588de2011-01-15 07:29:01 +00003218 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003219 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00003220 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3221 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00003222 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003223
Chris Lattneree588de2011-01-15 07:29:01 +00003224 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003225 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00003226 return OptimizeMemoryInst(I, SI->getOperand(1),
3227 SI->getOperand(0)->getType());
3228 return false;
3229 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003230
Yi Jiangd069f632014-04-21 19:34:27 +00003231 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3232
3233 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3234 BinOp->getOpcode() == Instruction::LShr)) {
3235 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3236 if (TLI && CI && TLI->hasExtractBitsInsn())
3237 return OptimizeExtractBits(BinOp, CI, *TLI);
3238
3239 return false;
3240 }
3241
Chris Lattneree588de2011-01-15 07:29:01 +00003242 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003243 if (GEPI->hasAllZeroIndices()) {
3244 /// The GEP operand must be a pointer, so must its result -> BitCast
3245 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3246 GEPI->getName(), GEPI);
3247 GEPI->replaceAllUsesWith(NC);
3248 GEPI->eraseFromParent();
3249 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003250 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00003251 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003252 }
Chris Lattneree588de2011-01-15 07:29:01 +00003253 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003254 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003255
Chris Lattneree588de2011-01-15 07:29:01 +00003256 if (CallInst *CI = dyn_cast<CallInst>(I))
3257 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003258
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003259 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3260 return OptimizeSelectInst(SI);
3261
Tim Northoveraeb8e062014-02-19 10:02:43 +00003262 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3263 return OptimizeShuffleVectorInst(SVI);
3264
Chris Lattneree588de2011-01-15 07:29:01 +00003265 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003266}
3267
Chris Lattnerf2836d12007-03-31 04:06:36 +00003268// In this pass we look for GEP and cast instructions that are used
3269// across basic blocks and rewrite them to improve basic-block-at-a-time
3270// selection.
3271bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00003272 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00003273 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00003274
Chris Lattner7a277142011-01-15 07:14:54 +00003275 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00003276 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00003277 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003278
Benjamin Kramer455fa352012-11-23 19:17:06 +00003279 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3280
Chris Lattnerf2836d12007-03-31 04:06:36 +00003281 return MadeChange;
3282}
Devang Patel53771ba2011-08-18 00:50:51 +00003283
3284// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00003285// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00003286// find a node corresponding to the value.
3287bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3288 bool MadeChange = false;
3289 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
Craig Topperc0196b12014-04-14 00:51:57 +00003290 Instruction *PrevNonDbgInst = nullptr;
Devang Patel53771ba2011-08-18 00:50:51 +00003291 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3292 Instruction *Insn = BI; ++BI;
3293 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00003294 // Leave dbg.values that refer to an alloca alone. These
3295 // instrinsics describe the address of a variable (= the alloca)
3296 // being taken. They should not be moved next to the alloca
3297 // (and to the beginning of the scope), but rather stay close to
3298 // where said address is used.
3299 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00003300 PrevNonDbgInst = Insn;
3301 continue;
3302 }
3303
3304 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3305 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3306 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3307 DVI->removeFromParent();
3308 if (isa<PHINode>(VI))
3309 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3310 else
3311 DVI->insertAfter(VI);
3312 MadeChange = true;
3313 ++NumDbgValueMoved;
3314 }
3315 }
3316 }
3317 return MadeChange;
3318}
Tim Northovercea0abb2014-03-29 08:22:29 +00003319
3320// If there is a sequence that branches based on comparing a single bit
3321// against zero that can be combined into a single instruction, and the
3322// target supports folding these into a single instruction, sink the
3323// mask and compare into the branch uses. Do this before OptimizeBlock ->
3324// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3325// searched for.
3326bool CodeGenPrepare::sinkAndCmp(Function &F) {
3327 if (!EnableAndCmpSinking)
3328 return false;
3329 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3330 return false;
3331 bool MadeChange = false;
3332 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3333 BasicBlock *BB = I++;
3334
3335 // Does this BB end with the following?
3336 // %andVal = and %val, #single-bit-set
3337 // %icmpVal = icmp %andResult, 0
3338 // br i1 %cmpVal label %dest1, label %dest2"
3339 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3340 if (!Brcc || !Brcc->isConditional())
3341 continue;
3342 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3343 if (!Cmp || Cmp->getParent() != BB)
3344 continue;
3345 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3346 if (!Zero || !Zero->isZero())
3347 continue;
3348 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3349 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3350 continue;
3351 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3352 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3353 continue;
3354 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3355
3356 // Push the "and; icmp" for any users that are conditional branches.
3357 // Since there can only be one branch use per BB, we don't need to keep
3358 // track of which BBs we insert into.
3359 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3360 UI != E; ) {
3361 Use &TheUse = *UI;
3362 // Find brcc use.
3363 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3364 ++UI;
3365 if (!BrccUser || !BrccUser->isConditional())
3366 continue;
3367 BasicBlock *UserBB = BrccUser->getParent();
3368 if (UserBB == BB) continue;
3369 DEBUG(dbgs() << "found Brcc use\n");
3370
3371 // Sink the "and; icmp" to use.
3372 MadeChange = true;
3373 BinaryOperator *NewAnd =
3374 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3375 BrccUser);
3376 CmpInst *NewCmp =
3377 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3378 "", BrccUser);
3379 TheUse = NewCmp;
3380 ++NumAndCmpsMoved;
3381 DEBUG(BrccUser->getParent()->dump());
3382 }
3383 }
3384 return MadeChange;
3385}