blob: bea75a2f2ad3ff7d5916876d14520f4c9f124019 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000022#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InlineAsm.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000033#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000034#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000035#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000036#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000037#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000038#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000040#include "llvm/Target/TargetLibraryInfo.h"
41#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000042#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000045#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000049
Chandler Carruth1b9dde02014-04-22 02:02:50 +000050#define DEBUG_TYPE "codegenprepare"
51
Cameron Zwarichced753f2011-01-05 17:27:27 +000052STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000053STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000055STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
56 "sunken Cmps");
57STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
58 "of sunken Casts");
59STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000061STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000064STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000065STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000066STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000067STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000068
Cameron Zwarich338d3622011-03-11 21:52:04 +000069static cl::opt<bool> DisableBranchOpts(
70 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
71 cl::desc("Disable branch optimizations in CodeGenPrepare"));
72
Benjamin Kramer3d38c172012-05-06 14:25:16 +000073static cl::opt<bool> DisableSelectToBranch(
74 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
75 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000076
Hal Finkelc3998302014-04-12 00:59:48 +000077static cl::opt<bool> AddrSinkUsingGEPs(
78 "addr-sink-using-gep", cl::Hidden, cl::init(false),
79 cl::desc("Address sinking in CGP using GEPs."));
80
Tim Northovercea0abb2014-03-29 08:22:29 +000081static cl::opt<bool> EnableAndCmpSinking(
82 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
83 cl::desc("Enable sinkinig and/cmp into branches."));
84
Quentin Colombetc32615d2014-10-31 17:52:53 +000085static cl::opt<bool> DisableStoreExtract(
86 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
87 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
88
89static cl::opt<bool> StressStoreExtract(
90 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
91 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
92
Eric Christopherc1ea1492008-09-24 05:32:41 +000093namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000094typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
95typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
96
Chris Lattner2dd09db2009-09-02 06:11:42 +000097 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000098 /// TLI - Keep a pointer of a TargetLowering to consult for determining
99 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000100 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000101 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000102 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000103 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +0000104 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +0000105
Chris Lattner7a277142011-01-15 07:14:54 +0000106 /// CurInstIterator - As we scan instructions optimizing them, this is the
107 /// next instruction to optimize. Xforms that can invalidate this should
108 /// update it.
109 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000110
Evan Cheng0663f232011-03-21 01:19:09 +0000111 /// Keeps track of non-local addresses that have been sunk into a block.
112 /// This allows us to avoid inserting duplicate code for blocks with
113 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000114 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000115
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000116 /// Keeps track of all truncates inserted for the current function.
117 SetOfInstrs InsertedTruncsSet;
118 /// Keeps track of the type of the related instruction before their
119 /// promotion for the current function.
120 InstrToOrigTy PromotedInsts;
121
Devang Patel8f606d72011-03-24 15:35:25 +0000122 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000123 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000124 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000125
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000126 /// OptSize - True if optimizing for size.
127 bool OptSize;
128
Chris Lattnerf2836d12007-03-31 04:06:36 +0000129 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000130 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000131 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Quentin Colombetc32615d2014-10-31 17:52:53 +0000132 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000133 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
134 }
Craig Topper4584cd52014-03-07 09:26:03 +0000135 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000136
Craig Topper4584cd52014-03-07 09:26:03 +0000137 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000138
Craig Topper4584cd52014-03-07 09:26:03 +0000139 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000140 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000141 AU.addRequired<TargetLibraryInfo>();
Quentin Colombetc32615d2014-10-31 17:52:53 +0000142 AU.addRequired<TargetTransformInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000143 }
144
Chris Lattnerf2836d12007-03-31 04:06:36 +0000145 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000146 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000147 bool EliminateMostlyEmptyBlocks(Function &F);
148 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
149 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000150 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000151 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000152 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000153 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000154 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000155 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000156 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000157 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000158 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000159 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000160 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000161 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000162 bool sinkAndCmp(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000163 };
164}
Devang Patel09f162c2007-05-01 21:15:47 +0000165
Devang Patel8c78a0b2007-05-03 01:11:54 +0000166char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000167INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
168 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000169
Bill Wendling7a639ea2013-06-19 21:07:11 +0000170FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
171 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000172}
173
Chris Lattnerf2836d12007-03-31 04:06:36 +0000174bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000175 if (skipOptnoneFunction(F))
176 return false;
177
Chris Lattnerf2836d12007-03-31 04:06:36 +0000178 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000179 // Clear per function information.
180 InsertedTruncsSet.clear();
181 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000182
Devang Patel8f606d72011-03-24 15:35:25 +0000183 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000184 if (TM)
185 TLI = TM->getSubtargetImpl()->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000186 TLInfo = &getAnalysis<TargetLibraryInfo>();
Quentin Colombetc32615d2014-10-31 17:52:53 +0000187 TTI = &getAnalysis<TargetTransformInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000188 DominatorTreeWrapperPass *DTWP =
189 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000190 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Bill Wendling698e84f2012-12-30 10:32:01 +0000191 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
192 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000193
Preston Gurdcdf540d2012-09-04 18:22:17 +0000194 /// This optimization identifies DIV instructions that can be
195 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000196 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000197 const DenseMap<unsigned int, unsigned int> &BypassWidths =
198 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000199 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000200 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000201 }
202
203 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000204 // unconditional branch.
205 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000206
Devang Patel53771ba2011-08-18 00:50:51 +0000207 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000208 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000209 // find a node corresponding to the value.
210 EverMadeChange |= PlaceDbgValues(F);
211
Tim Northovercea0abb2014-03-29 08:22:29 +0000212 // If there is a mask, compare against zero, and branch that can be combined
213 // into a single target instruction, push the mask and compare into branch
214 // users. Do this before OptimizeBlock -> OptimizeInst ->
215 // OptimizeCmpExpression, which perturbs the pattern being searched for.
216 if (!DisableBranchOpts)
217 EverMadeChange |= sinkAndCmp(F);
218
Chris Lattnerc3748562007-04-02 01:35:34 +0000219 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000220 while (MadeChange) {
221 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000222 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000223 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000224 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000225 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000226 EverMadeChange |= MadeChange;
227 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000228
229 SunkAddrs.clear();
230
Cameron Zwarich338d3622011-03-11 21:52:04 +0000231 if (!DisableBranchOpts) {
232 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000233 SmallPtrSet<BasicBlock*, 8> WorkList;
234 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
235 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000236 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000237 if (!MadeChange) continue;
238
239 for (SmallVectorImpl<BasicBlock*>::iterator
240 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
241 if (pred_begin(*II) == pred_end(*II))
242 WorkList.insert(*II);
243 }
244
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000245 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000246 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000247 while (!WorkList.empty()) {
248 BasicBlock *BB = *WorkList.begin();
249 WorkList.erase(BB);
250 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
251
252 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000253
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000254 for (SmallVectorImpl<BasicBlock*>::iterator
255 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
256 if (pred_begin(*II) == pred_end(*II))
257 WorkList.insert(*II);
258 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000259
Nadav Rotem70409992012-08-14 05:19:07 +0000260 // Merge pairs of basic blocks with unconditional branches, connected by
261 // a single edge.
262 if (EverMadeChange || MadeChange)
263 MadeChange |= EliminateFallThrough(F);
264
Evan Cheng0663f232011-03-21 01:19:09 +0000265 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000266 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000267 EverMadeChange |= MadeChange;
268 }
269
Devang Patel8f606d72011-03-24 15:35:25 +0000270 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000271 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000272
Chris Lattnerf2836d12007-03-31 04:06:36 +0000273 return EverMadeChange;
274}
275
Nadav Rotem70409992012-08-14 05:19:07 +0000276/// EliminateFallThrough - Merge basic blocks which are connected
277/// by a single edge, where one of the basic blocks has a single successor
278/// pointing to the other basic block, which has a single predecessor.
279bool CodeGenPrepare::EliminateFallThrough(Function &F) {
280 bool Changed = false;
281 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000282 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000283 BasicBlock *BB = I++;
284 // If the destination block has a single pred, then this is a trivial
285 // edge, just collapse it.
286 BasicBlock *SinglePred = BB->getSinglePredecessor();
287
Evan Cheng64a223a2012-09-28 23:58:57 +0000288 // Don't merge if BB's address is taken.
289 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000290
291 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
292 if (Term && !Term->isConditional()) {
293 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000294 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000295 // Remember if SinglePred was the entry block of the function.
296 // If so, we will need to move BB back to the entry position.
297 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
298 MergeBasicBlockIntoOnlyPred(BB, this);
299
300 if (isEntry && BB != &BB->getParent()->getEntryBlock())
301 BB->moveBefore(&BB->getParent()->getEntryBlock());
302
303 // We have erased a block. Update the iterator.
304 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000305 }
306 }
307 return Changed;
308}
309
Dale Johannesen4026b042009-03-27 01:13:37 +0000310/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
311/// debug info directives, and an unconditional branch. Passes before isel
312/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
313/// isel. Start by eliminating these blocks so we can split them the way we
314/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000315bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
316 bool MadeChange = false;
317 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000318 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000319 BasicBlock *BB = I++;
320
321 // If this block doesn't end with an uncond branch, ignore it.
322 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
323 if (!BI || !BI->isUnconditional())
324 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000325
Dale Johannesen4026b042009-03-27 01:13:37 +0000326 // If the instruction before the branch (skipping debug info) isn't a phi
327 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000328 BasicBlock::iterator BBI = BI;
329 if (BBI != BB->begin()) {
330 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000331 while (isa<DbgInfoIntrinsic>(BBI)) {
332 if (BBI == BB->begin())
333 break;
334 --BBI;
335 }
336 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
337 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000338 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000339
Chris Lattnerc3748562007-04-02 01:35:34 +0000340 // Do not break infinite loops.
341 BasicBlock *DestBB = BI->getSuccessor(0);
342 if (DestBB == BB)
343 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000344
Chris Lattnerc3748562007-04-02 01:35:34 +0000345 if (!CanMergeBlocks(BB, DestBB))
346 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000347
Chris Lattnerc3748562007-04-02 01:35:34 +0000348 EliminateMostlyEmptyBlock(BB);
349 MadeChange = true;
350 }
351 return MadeChange;
352}
353
354/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
355/// single uncond branch between them, and BB contains no other non-phi
356/// instructions.
357bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
358 const BasicBlock *DestBB) const {
359 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
360 // the successor. If there are more complex condition (e.g. preheaders),
361 // don't mess around with them.
362 BasicBlock::const_iterator BBI = BB->begin();
363 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000364 for (const User *U : PN->users()) {
365 const Instruction *UI = cast<Instruction>(U);
366 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000367 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000368 // If User is inside DestBB block and it is a PHINode then check
369 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000370 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000371 if (UI->getParent() == DestBB) {
372 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000373 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
374 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
375 if (Insn && Insn->getParent() == BB &&
376 Insn->getParent() != UPN->getIncomingBlock(I))
377 return false;
378 }
379 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000380 }
381 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000382
Chris Lattnerc3748562007-04-02 01:35:34 +0000383 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
384 // and DestBB may have conflicting incoming values for the block. If so, we
385 // can't merge the block.
386 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
387 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000388
Chris Lattnerc3748562007-04-02 01:35:34 +0000389 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000390 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000391 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
392 // It is faster to get preds from a PHI than with pred_iterator.
393 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
394 BBPreds.insert(BBPN->getIncomingBlock(i));
395 } else {
396 BBPreds.insert(pred_begin(BB), pred_end(BB));
397 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000398
Chris Lattnerc3748562007-04-02 01:35:34 +0000399 // Walk the preds of DestBB.
400 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
401 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
402 if (BBPreds.count(Pred)) { // Common predecessor?
403 BBI = DestBB->begin();
404 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
405 const Value *V1 = PN->getIncomingValueForBlock(Pred);
406 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000407
Chris Lattnerc3748562007-04-02 01:35:34 +0000408 // If V2 is a phi node in BB, look up what the mapped value will be.
409 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
410 if (V2PN->getParent() == BB)
411 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000412
Chris Lattnerc3748562007-04-02 01:35:34 +0000413 // If there is a conflict, bail out.
414 if (V1 != V2) return false;
415 }
416 }
417 }
418
419 return true;
420}
421
422
423/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
424/// an unconditional branch in it.
425void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
426 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
427 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000428
David Greene74e2d492010-01-05 01:27:11 +0000429 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000430
Chris Lattnerc3748562007-04-02 01:35:34 +0000431 // If the destination block has a single pred, then this is a trivial edge,
432 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000433 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000434 if (SinglePred != DestBB) {
435 // Remember if SinglePred was the entry block of the function. If so, we
436 // will need to move BB back to the entry position.
437 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000438 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000439
Chris Lattner8a172da2008-11-28 19:54:49 +0000440 if (isEntry && BB != &BB->getParent()->getEntryBlock())
441 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000442
David Greene74e2d492010-01-05 01:27:11 +0000443 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000444 return;
445 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000446 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000447
Chris Lattnerc3748562007-04-02 01:35:34 +0000448 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
449 // to handle the new incoming edges it is about to have.
450 PHINode *PN;
451 for (BasicBlock::iterator BBI = DestBB->begin();
452 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
453 // Remove the incoming value for BB, and remember it.
454 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000455
Chris Lattnerc3748562007-04-02 01:35:34 +0000456 // Two options: either the InVal is a phi node defined in BB or it is some
457 // value that dominates BB.
458 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
459 if (InValPhi && InValPhi->getParent() == BB) {
460 // Add all of the input values of the input PHI as inputs of this phi.
461 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
462 PN->addIncoming(InValPhi->getIncomingValue(i),
463 InValPhi->getIncomingBlock(i));
464 } else {
465 // Otherwise, add one instance of the dominating value for each edge that
466 // we will be adding.
467 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
468 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
469 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
470 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000471 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
472 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000473 }
474 }
475 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000476
Chris Lattnerc3748562007-04-02 01:35:34 +0000477 // The PHIs are now updated, change everything that refers to BB to use
478 // DestBB and remove BB.
479 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000480 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000481 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
482 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
483 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
484 DT->changeImmediateDominator(DestBB, NewIDom);
485 DT->eraseNode(BB);
486 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000487 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000488 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000489
David Greene74e2d492010-01-05 01:27:11 +0000490 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000491}
492
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000493/// SinkCast - Sink the specified cast instruction into its user blocks
494static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000495 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000496
Chris Lattnerf2836d12007-03-31 04:06:36 +0000497 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000498 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000499
Chris Lattnerf2836d12007-03-31 04:06:36 +0000500 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000501 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000502 UI != E; ) {
503 Use &TheUse = UI.getUse();
504 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000505
Chris Lattnerf2836d12007-03-31 04:06:36 +0000506 // Figure out which BB this cast is used in. For PHI's this is the
507 // appropriate predecessor block.
508 BasicBlock *UserBB = User->getParent();
509 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000510 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000511 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000512
Chris Lattnerf2836d12007-03-31 04:06:36 +0000513 // Preincrement use iterator so we don't invalidate it.
514 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000515
Chris Lattnerf2836d12007-03-31 04:06:36 +0000516 // If this user is in the same block as the cast, don't change the cast.
517 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000518
Chris Lattnerf2836d12007-03-31 04:06:36 +0000519 // If we have already inserted a cast into this block, use it.
520 CastInst *&InsertedCast = InsertedCasts[UserBB];
521
522 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000523 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000524 InsertedCast =
525 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000526 InsertPt);
527 MadeChange = true;
528 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000529
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000530 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000531 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000532 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000533 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000534
Chris Lattnerf2836d12007-03-31 04:06:36 +0000535 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000536 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000537 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000538 MadeChange = true;
539 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000540
Chris Lattnerf2836d12007-03-31 04:06:36 +0000541 return MadeChange;
542}
543
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000544/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
545/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
546/// sink it into user blocks to reduce the number of virtual
547/// registers that must be created and coalesced.
548///
549/// Return true if any changes are made.
550///
551static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
552 // If this is a noop copy,
553 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
554 EVT DstVT = TLI.getValueType(CI->getType());
555
556 // This is an fp<->int conversion?
557 if (SrcVT.isInteger() != DstVT.isInteger())
558 return false;
559
560 // If this is an extension, it will be a zero or sign extension, which
561 // isn't a noop.
562 if (SrcVT.bitsLT(DstVT)) return false;
563
564 // If these values will be promoted, find out what they will be promoted
565 // to. This helps us consider truncates on PPC as noop copies when they
566 // are.
567 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
568 TargetLowering::TypePromoteInteger)
569 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
570 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
571 TargetLowering::TypePromoteInteger)
572 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
573
574 // If, after promotion, these are the same types, this is a noop copy.
575 if (SrcVT != DstVT)
576 return false;
577
578 return SinkCast(CI);
579}
580
Eric Christopherc1ea1492008-09-24 05:32:41 +0000581/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000582/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000583/// a clear win except on targets with multiple condition code registers
584/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000585///
586/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000587static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000588 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000589
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000590 /// InsertedCmp - Only insert a cmp in each block once.
591 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000592
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000593 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000594 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000595 UI != E; ) {
596 Use &TheUse = UI.getUse();
597 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000598
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000599 // Preincrement use iterator so we don't invalidate it.
600 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000601
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000602 // Don't bother for PHI nodes.
603 if (isa<PHINode>(User))
604 continue;
605
606 // Figure out which BB this cmp is used in.
607 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000608
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000609 // If this user is in the same block as the cmp, don't change the cmp.
610 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000611
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000612 // If we have already inserted a cmp into this block, use it.
613 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
614
615 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000616 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000617 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000618 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000619 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000620 CI->getOperand(1), "", InsertPt);
621 MadeChange = true;
622 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000623
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000624 // Replace a use of the cmp with a use of the new cmp.
625 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000626 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000627 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000628
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000629 // If we removed all uses, nuke the cmp.
630 if (CI->use_empty())
631 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000632
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000633 return MadeChange;
634}
635
Yi Jiangd069f632014-04-21 19:34:27 +0000636/// isExtractBitsCandidateUse - Check if the candidates could
637/// be combined with shift instruction, which includes:
638/// 1. Truncate instruction
639/// 2. And instruction and the imm is a mask of the low bits:
640/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000641static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000642 if (!isa<TruncInst>(User)) {
643 if (User->getOpcode() != Instruction::And ||
644 !isa<ConstantInt>(User->getOperand(1)))
645 return false;
646
Quentin Colombetd4f44692014-04-22 01:20:34 +0000647 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000648
Quentin Colombetd4f44692014-04-22 01:20:34 +0000649 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000650 return false;
651 }
652 return true;
653}
654
655/// SinkShiftAndTruncate - sink both shift and truncate instruction
656/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000657static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000658SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
659 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
660 const TargetLowering &TLI) {
661 BasicBlock *UserBB = User->getParent();
662 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
663 TruncInst *TruncI = dyn_cast<TruncInst>(User);
664 bool MadeChange = false;
665
666 for (Value::user_iterator TruncUI = TruncI->user_begin(),
667 TruncE = TruncI->user_end();
668 TruncUI != TruncE;) {
669
670 Use &TruncTheUse = TruncUI.getUse();
671 Instruction *TruncUser = cast<Instruction>(*TruncUI);
672 // Preincrement use iterator so we don't invalidate it.
673
674 ++TruncUI;
675
676 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
677 if (!ISDOpcode)
678 continue;
679
Tim Northovere2239ff2014-07-29 10:20:22 +0000680 // If the use is actually a legal node, there will not be an
681 // implicit truncate.
682 // FIXME: always querying the result type is just an
683 // approximation; some nodes' legality is determined by the
684 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000685 if (TLI.isOperationLegalOrCustom(
686 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000687 continue;
688
689 // Don't bother for PHI nodes.
690 if (isa<PHINode>(TruncUser))
691 continue;
692
693 BasicBlock *TruncUserBB = TruncUser->getParent();
694
695 if (UserBB == TruncUserBB)
696 continue;
697
698 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
699 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
700
701 if (!InsertedShift && !InsertedTrunc) {
702 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
703 // Sink the shift
704 if (ShiftI->getOpcode() == Instruction::AShr)
705 InsertedShift =
706 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
707 else
708 InsertedShift =
709 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
710
711 // Sink the trunc
712 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
713 TruncInsertPt++;
714
715 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
716 TruncI->getType(), "", TruncInsertPt);
717
718 MadeChange = true;
719
720 TruncTheUse = InsertedTrunc;
721 }
722 }
723 return MadeChange;
724}
725
726/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
727/// the uses could potentially be combined with this shift instruction and
728/// generate BitExtract instruction. It will only be applied if the architecture
729/// supports BitExtract instruction. Here is an example:
730/// BB1:
731/// %x.extract.shift = lshr i64 %arg1, 32
732/// BB2:
733/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
734/// ==>
735///
736/// BB2:
737/// %x.extract.shift.1 = lshr i64 %arg1, 32
738/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
739///
740/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
741/// instruction.
742/// Return true if any changes are made.
743static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
744 const TargetLowering &TLI) {
745 BasicBlock *DefBB = ShiftI->getParent();
746
747 /// Only insert instructions in each block once.
748 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
749
750 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
751
752 bool MadeChange = false;
753 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
754 UI != E;) {
755 Use &TheUse = UI.getUse();
756 Instruction *User = cast<Instruction>(*UI);
757 // Preincrement use iterator so we don't invalidate it.
758 ++UI;
759
760 // Don't bother for PHI nodes.
761 if (isa<PHINode>(User))
762 continue;
763
764 if (!isExtractBitsCandidateUse(User))
765 continue;
766
767 BasicBlock *UserBB = User->getParent();
768
769 if (UserBB == DefBB) {
770 // If the shift and truncate instruction are in the same BB. The use of
771 // the truncate(TruncUse) may still introduce another truncate if not
772 // legal. In this case, we would like to sink both shift and truncate
773 // instruction to the BB of TruncUse.
774 // for example:
775 // BB1:
776 // i64 shift.result = lshr i64 opnd, imm
777 // trunc.result = trunc shift.result to i16
778 //
779 // BB2:
780 // ----> We will have an implicit truncate here if the architecture does
781 // not have i16 compare.
782 // cmp i16 trunc.result, opnd2
783 //
784 if (isa<TruncInst>(User) && shiftIsLegal
785 // If the type of the truncate is legal, no trucate will be
786 // introduced in other basic blocks.
787 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
788 MadeChange =
789 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
790
791 continue;
792 }
793 // If we have already inserted a shift into this block, use it.
794 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
795
796 if (!InsertedShift) {
797 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
798
799 if (ShiftI->getOpcode() == Instruction::AShr)
800 InsertedShift =
801 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
802 else
803 InsertedShift =
804 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
805
806 MadeChange = true;
807 }
808
809 // Replace a use of the shift with a use of the new shift.
810 TheUse = InsertedShift;
811 }
812
813 // If we removed all uses, nuke the shift.
814 if (ShiftI->use_empty())
815 ShiftI->eraseFromParent();
816
817 return MadeChange;
818}
819
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000820namespace {
821class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
822protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000823 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000824 CI->replaceAllUsesWith(With);
825 CI->eraseFromParent();
826 }
Craig Topper4584cd52014-03-07 09:26:03 +0000827 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000828 if (ConstantInt *SizeCI =
829 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
830 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000831 return false;
832 }
833};
834} // end anonymous namespace
835
Eric Christopher4b7948e2010-03-11 02:41:03 +0000836bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000837 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000838
Chris Lattner7a277142011-01-15 07:14:54 +0000839 // Lower inline assembly if we can.
840 // If we found an inline asm expession, and if the target knows how to
841 // lower it to normal LLVM code, do so now.
842 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
843 if (TLI->ExpandInlineAsm(CI)) {
844 // Avoid invalidating the iterator.
845 CurInstIterator = BB->begin();
846 // Avoid processing instructions out of order, which could cause
847 // reuse before a value is defined.
848 SunkAddrs.clear();
849 return true;
850 }
851 // Sink address computing for memory operands into the block.
852 if (OptimizeInlineAsmInst(CI))
853 return true;
854 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000855
Eric Christopher4b7948e2010-03-11 02:41:03 +0000856 // Lower all uses of llvm.objectsize.*
857 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
858 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000859 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000860 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000861 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
862
Chris Lattner1b93be52011-01-15 07:25:29 +0000863 // Substituting this can cause recursive simplifications, which can
864 // invalidate our iterator. Use a WeakVH to hold onto it in case this
865 // happens.
866 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000867
Craig Topperc0196b12014-04-14 00:51:57 +0000868 replaceAndRecursivelySimplify(CI, RetVal,
869 TLI ? TLI->getDataLayout() : nullptr,
870 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000871
872 // If the iterator instruction was recursively deleted, start over at the
873 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000874 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000875 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000876 SunkAddrs.clear();
877 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000878 return true;
879 }
880
Pete Cooper615fd892012-03-13 20:59:56 +0000881 if (II && TLI) {
882 SmallVector<Value*, 2> PtrOps;
883 Type *AccessTy;
884 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
885 while (!PtrOps.empty())
886 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
887 return true;
888 }
889
Eric Christopher4b7948e2010-03-11 02:41:03 +0000890 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +0000891 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000892
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000893 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +0000894 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000895 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000896
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000897 // Lower all default uses of _chk calls. This is very similar
898 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000899 // that have the default "don't know" as the objectsize. Anything else
900 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000901 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000902 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000903}
Chris Lattner1b93be52011-01-15 07:25:29 +0000904
Evan Cheng0663f232011-03-21 01:19:09 +0000905/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
906/// instructions to the predecessor to enable tail call optimizations. The
907/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000908/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000909/// bb0:
910/// %tmp0 = tail call i32 @f0()
911/// br label %return
912/// bb1:
913/// %tmp1 = tail call i32 @f1()
914/// br label %return
915/// bb2:
916/// %tmp2 = tail call i32 @f2()
917/// br label %return
918/// return:
919/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
920/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000921/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000922///
923/// =>
924///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000925/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000926/// bb0:
927/// %tmp0 = tail call i32 @f0()
928/// ret i32 %tmp0
929/// bb1:
930/// %tmp1 = tail call i32 @f1()
931/// ret i32 %tmp1
932/// bb2:
933/// %tmp2 = tail call i32 @f2()
934/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000935/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000936bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000937 if (!TLI)
938 return false;
939
Benjamin Kramer455fa352012-11-23 19:17:06 +0000940 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
941 if (!RI)
942 return false;
943
Craig Topperc0196b12014-04-14 00:51:57 +0000944 PHINode *PN = nullptr;
945 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +0000946 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000947 if (V) {
948 BCI = dyn_cast<BitCastInst>(V);
949 if (BCI)
950 V = BCI->getOperand(0);
951
952 PN = dyn_cast<PHINode>(V);
953 if (!PN)
954 return false;
955 }
Evan Cheng0663f232011-03-21 01:19:09 +0000956
Cameron Zwarich4649f172011-03-24 04:52:10 +0000957 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000958 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000959
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000960 // It's not safe to eliminate the sign / zero extension of the return value.
961 // See llvm::isInTailCallPosition().
962 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000963 AttributeSet CallerAttrs = F->getAttributes();
964 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
965 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000966 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000967
Cameron Zwarich4649f172011-03-24 04:52:10 +0000968 // Make sure there are no instructions between the PHI and return, or that the
969 // return is the first instruction in the block.
970 if (PN) {
971 BasicBlock::iterator BI = BB->begin();
972 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000973 if (&*BI == BCI)
974 // Also skip over the bitcast.
975 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000976 if (&*BI != RI)
977 return false;
978 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000979 BasicBlock::iterator BI = BB->begin();
980 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
981 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000982 return false;
983 }
Evan Cheng0663f232011-03-21 01:19:09 +0000984
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000985 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
986 /// call.
987 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000988 if (PN) {
989 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
990 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
991 // Make sure the phi value is indeed produced by the tail call.
992 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
993 TLI->mayBeEmittedAsTailCall(CI))
994 TailCalls.push_back(CI);
995 }
996 } else {
997 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000998 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
999 if (!VisitedBBs.insert(*PI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001000 continue;
1001
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001002 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001003 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1004 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001005 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1006 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001007 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001008
Cameron Zwarich4649f172011-03-24 04:52:10 +00001009 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001010 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001011 TailCalls.push_back(CI);
1012 }
Evan Cheng0663f232011-03-21 01:19:09 +00001013 }
1014
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001015 bool Changed = false;
1016 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1017 CallInst *CI = TailCalls[i];
1018 CallSite CS(CI);
1019
1020 // Conservatively require the attributes of the call to match those of the
1021 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001022 AttributeSet CalleeAttrs = CS.getAttributes();
1023 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001024 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001025 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001026 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001027 continue;
1028
1029 // Make sure the call instruction is followed by an unconditional branch to
1030 // the return block.
1031 BasicBlock *CallBB = CI->getParent();
1032 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1033 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1034 continue;
1035
1036 // Duplicate the return into CallBB.
1037 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001038 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001039 ++NumRetsDup;
1040 }
1041
1042 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001043 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001044 BB->eraseFromParent();
1045
1046 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001047}
1048
Chris Lattner728f9022008-11-25 07:09:13 +00001049//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001050// Memory Optimization
1051//===----------------------------------------------------------------------===//
1052
Chandler Carruthc8925912013-01-05 02:09:22 +00001053namespace {
1054
1055/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1056/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001057struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001058 Value *BaseReg;
1059 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001060 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001061 void print(raw_ostream &OS) const;
1062 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001063
Chandler Carruthc8925912013-01-05 02:09:22 +00001064 bool operator==(const ExtAddrMode& O) const {
1065 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1066 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1067 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1068 }
1069};
1070
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001071#ifndef NDEBUG
1072static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1073 AM.print(OS);
1074 return OS;
1075}
1076#endif
1077
Chandler Carruthc8925912013-01-05 02:09:22 +00001078void ExtAddrMode::print(raw_ostream &OS) const {
1079 bool NeedPlus = false;
1080 OS << "[";
1081 if (BaseGV) {
1082 OS << (NeedPlus ? " + " : "")
1083 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001084 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001085 NeedPlus = true;
1086 }
1087
Richard Trieuc0f91212014-05-30 03:15:17 +00001088 if (BaseOffs) {
1089 OS << (NeedPlus ? " + " : "")
1090 << BaseOffs;
1091 NeedPlus = true;
1092 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001093
1094 if (BaseReg) {
1095 OS << (NeedPlus ? " + " : "")
1096 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001097 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001098 NeedPlus = true;
1099 }
1100 if (Scale) {
1101 OS << (NeedPlus ? " + " : "")
1102 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001103 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001104 }
1105
1106 OS << ']';
1107}
1108
1109#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1110void ExtAddrMode::dump() const {
1111 print(dbgs());
1112 dbgs() << '\n';
1113}
1114#endif
1115
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001116/// \brief This class provides transaction based operation on the IR.
1117/// Every change made through this class is recorded in the internal state and
1118/// can be undone (rollback) until commit is called.
1119class TypePromotionTransaction {
1120
1121 /// \brief This represents the common interface of the individual transaction.
1122 /// Each class implements the logic for doing one specific modification on
1123 /// the IR via the TypePromotionTransaction.
1124 class TypePromotionAction {
1125 protected:
1126 /// The Instruction modified.
1127 Instruction *Inst;
1128
1129 public:
1130 /// \brief Constructor of the action.
1131 /// The constructor performs the related action on the IR.
1132 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1133
1134 virtual ~TypePromotionAction() {}
1135
1136 /// \brief Undo the modification done by this action.
1137 /// When this method is called, the IR must be in the same state as it was
1138 /// before this action was applied.
1139 /// \pre Undoing the action works if and only if the IR is in the exact same
1140 /// state as it was directly after this action was applied.
1141 virtual void undo() = 0;
1142
1143 /// \brief Advocate every change made by this action.
1144 /// When the results on the IR of the action are to be kept, it is important
1145 /// to call this function, otherwise hidden information may be kept forever.
1146 virtual void commit() {
1147 // Nothing to be done, this action is not doing anything.
1148 }
1149 };
1150
1151 /// \brief Utility to remember the position of an instruction.
1152 class InsertionHandler {
1153 /// Position of an instruction.
1154 /// Either an instruction:
1155 /// - Is the first in a basic block: BB is used.
1156 /// - Has a previous instructon: PrevInst is used.
1157 union {
1158 Instruction *PrevInst;
1159 BasicBlock *BB;
1160 } Point;
1161 /// Remember whether or not the instruction had a previous instruction.
1162 bool HasPrevInstruction;
1163
1164 public:
1165 /// \brief Record the position of \p Inst.
1166 InsertionHandler(Instruction *Inst) {
1167 BasicBlock::iterator It = Inst;
1168 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1169 if (HasPrevInstruction)
1170 Point.PrevInst = --It;
1171 else
1172 Point.BB = Inst->getParent();
1173 }
1174
1175 /// \brief Insert \p Inst at the recorded position.
1176 void insert(Instruction *Inst) {
1177 if (HasPrevInstruction) {
1178 if (Inst->getParent())
1179 Inst->removeFromParent();
1180 Inst->insertAfter(Point.PrevInst);
1181 } else {
1182 Instruction *Position = Point.BB->getFirstInsertionPt();
1183 if (Inst->getParent())
1184 Inst->moveBefore(Position);
1185 else
1186 Inst->insertBefore(Position);
1187 }
1188 }
1189 };
1190
1191 /// \brief Move an instruction before another.
1192 class InstructionMoveBefore : public TypePromotionAction {
1193 /// Original position of the instruction.
1194 InsertionHandler Position;
1195
1196 public:
1197 /// \brief Move \p Inst before \p Before.
1198 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1199 : TypePromotionAction(Inst), Position(Inst) {
1200 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1201 Inst->moveBefore(Before);
1202 }
1203
1204 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001205 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001206 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1207 Position.insert(Inst);
1208 }
1209 };
1210
1211 /// \brief Set the operand of an instruction with a new value.
1212 class OperandSetter : public TypePromotionAction {
1213 /// Original operand of the instruction.
1214 Value *Origin;
1215 /// Index of the modified instruction.
1216 unsigned Idx;
1217
1218 public:
1219 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1220 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1221 : TypePromotionAction(Inst), Idx(Idx) {
1222 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1223 << "for:" << *Inst << "\n"
1224 << "with:" << *NewVal << "\n");
1225 Origin = Inst->getOperand(Idx);
1226 Inst->setOperand(Idx, NewVal);
1227 }
1228
1229 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001230 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001231 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1232 << "for: " << *Inst << "\n"
1233 << "with: " << *Origin << "\n");
1234 Inst->setOperand(Idx, Origin);
1235 }
1236 };
1237
1238 /// \brief Hide the operands of an instruction.
1239 /// Do as if this instruction was not using any of its operands.
1240 class OperandsHider : public TypePromotionAction {
1241 /// The list of original operands.
1242 SmallVector<Value *, 4> OriginalValues;
1243
1244 public:
1245 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1246 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1247 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1248 unsigned NumOpnds = Inst->getNumOperands();
1249 OriginalValues.reserve(NumOpnds);
1250 for (unsigned It = 0; It < NumOpnds; ++It) {
1251 // Save the current operand.
1252 Value *Val = Inst->getOperand(It);
1253 OriginalValues.push_back(Val);
1254 // Set a dummy one.
1255 // We could use OperandSetter here, but that would implied an overhead
1256 // that we are not willing to pay.
1257 Inst->setOperand(It, UndefValue::get(Val->getType()));
1258 }
1259 }
1260
1261 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001262 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001263 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1264 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1265 Inst->setOperand(It, OriginalValues[It]);
1266 }
1267 };
1268
1269 /// \brief Build a truncate instruction.
1270 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001271 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001272 public:
1273 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1274 /// result.
1275 /// trunc Opnd to Ty.
1276 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1277 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001278 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1279 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001280 }
1281
Quentin Colombetac55b152014-09-16 22:36:07 +00001282 /// \brief Get the built value.
1283 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001284
1285 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001286 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001287 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1288 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1289 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001290 }
1291 };
1292
1293 /// \brief Build a sign extension instruction.
1294 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001295 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001296 public:
1297 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1298 /// result.
1299 /// sext Opnd to Ty.
1300 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001301 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001302 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001303 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1304 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001305 }
1306
Quentin Colombetac55b152014-09-16 22:36:07 +00001307 /// \brief Get the built value.
1308 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001309
1310 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001311 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001312 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1313 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1314 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001315 }
1316 };
1317
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001318 /// \brief Build a zero extension instruction.
1319 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001320 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001321 public:
1322 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1323 /// result.
1324 /// zext Opnd to Ty.
1325 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001326 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001327 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001328 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1329 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001330 }
1331
Quentin Colombetac55b152014-09-16 22:36:07 +00001332 /// \brief Get the built value.
1333 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001334
1335 /// \brief Remove the built instruction.
1336 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001337 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1338 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1339 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001340 }
1341 };
1342
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001343 /// \brief Mutate an instruction to another type.
1344 class TypeMutator : public TypePromotionAction {
1345 /// Record the original type.
1346 Type *OrigTy;
1347
1348 public:
1349 /// \brief Mutate the type of \p Inst into \p NewTy.
1350 TypeMutator(Instruction *Inst, Type *NewTy)
1351 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1352 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1353 << "\n");
1354 Inst->mutateType(NewTy);
1355 }
1356
1357 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001358 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001359 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1360 << "\n");
1361 Inst->mutateType(OrigTy);
1362 }
1363 };
1364
1365 /// \brief Replace the uses of an instruction by another instruction.
1366 class UsesReplacer : public TypePromotionAction {
1367 /// Helper structure to keep track of the replaced uses.
1368 struct InstructionAndIdx {
1369 /// The instruction using the instruction.
1370 Instruction *Inst;
1371 /// The index where this instruction is used for Inst.
1372 unsigned Idx;
1373 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1374 : Inst(Inst), Idx(Idx) {}
1375 };
1376
1377 /// Keep track of the original uses (pair Instruction, Index).
1378 SmallVector<InstructionAndIdx, 4> OriginalUses;
1379 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1380
1381 public:
1382 /// \brief Replace all the use of \p Inst by \p New.
1383 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1384 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1385 << "\n");
1386 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001387 for (Use &U : Inst->uses()) {
1388 Instruction *UserI = cast<Instruction>(U.getUser());
1389 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001390 }
1391 // Now, we can replace the uses.
1392 Inst->replaceAllUsesWith(New);
1393 }
1394
1395 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001396 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001397 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1398 for (use_iterator UseIt = OriginalUses.begin(),
1399 EndIt = OriginalUses.end();
1400 UseIt != EndIt; ++UseIt) {
1401 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1402 }
1403 }
1404 };
1405
1406 /// \brief Remove an instruction from the IR.
1407 class InstructionRemover : public TypePromotionAction {
1408 /// Original position of the instruction.
1409 InsertionHandler Inserter;
1410 /// Helper structure to hide all the link to the instruction. In other
1411 /// words, this helps to do as if the instruction was removed.
1412 OperandsHider Hider;
1413 /// Keep track of the uses replaced, if any.
1414 UsesReplacer *Replacer;
1415
1416 public:
1417 /// \brief Remove all reference of \p Inst and optinally replace all its
1418 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001419 /// \pre If !Inst->use_empty(), then New != nullptr
1420 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001421 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001422 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001423 if (New)
1424 Replacer = new UsesReplacer(Inst, New);
1425 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1426 Inst->removeFromParent();
1427 }
1428
1429 ~InstructionRemover() { delete Replacer; }
1430
1431 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001432 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001433
1434 /// \brief Resurrect the instruction and reassign it to the proper uses if
1435 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001436 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001437 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1438 Inserter.insert(Inst);
1439 if (Replacer)
1440 Replacer->undo();
1441 Hider.undo();
1442 }
1443 };
1444
1445public:
1446 /// Restoration point.
1447 /// The restoration point is a pointer to an action instead of an iterator
1448 /// because the iterator may be invalidated but not the pointer.
1449 typedef const TypePromotionAction *ConstRestorationPt;
1450 /// Advocate every changes made in that transaction.
1451 void commit();
1452 /// Undo all the changes made after the given point.
1453 void rollback(ConstRestorationPt Point);
1454 /// Get the current restoration point.
1455 ConstRestorationPt getRestorationPoint() const;
1456
1457 /// \name API for IR modification with state keeping to support rollback.
1458 /// @{
1459 /// Same as Instruction::setOperand.
1460 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1461 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001462 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001463 /// Same as Value::replaceAllUsesWith.
1464 void replaceAllUsesWith(Instruction *Inst, Value *New);
1465 /// Same as Value::mutateType.
1466 void mutateType(Instruction *Inst, Type *NewTy);
1467 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00001468 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001469 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001470 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001471 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00001472 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001473 /// Same as Instruction::moveBefore.
1474 void moveBefore(Instruction *Inst, Instruction *Before);
1475 /// @}
1476
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001477private:
1478 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001479 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1480 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001481};
1482
1483void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1484 Value *NewVal) {
1485 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001486 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001487}
1488
1489void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1490 Value *NewVal) {
1491 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001492 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001493}
1494
1495void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1496 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001497 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001498}
1499
1500void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001501 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001502}
1503
Quentin Colombetac55b152014-09-16 22:36:07 +00001504Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1505 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001506 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001507 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001508 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001509 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001510}
1511
Quentin Colombetac55b152014-09-16 22:36:07 +00001512Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1513 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001514 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001515 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00001516 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001517 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001518}
1519
Quentin Colombetac55b152014-09-16 22:36:07 +00001520Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1521 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001522 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00001523 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001524 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00001525 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001526}
1527
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001528void TypePromotionTransaction::moveBefore(Instruction *Inst,
1529 Instruction *Before) {
1530 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001531 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001532}
1533
1534TypePromotionTransaction::ConstRestorationPt
1535TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00001536 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001537}
1538
1539void TypePromotionTransaction::commit() {
1540 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00001541 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001542 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001543 Actions.clear();
1544}
1545
1546void TypePromotionTransaction::rollback(
1547 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00001548 while (!Actions.empty() && Point != Actions.back().get()) {
1549 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001550 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001551 }
1552}
1553
Chandler Carruthc8925912013-01-05 02:09:22 +00001554/// \brief A helper class for matching addressing modes.
1555///
1556/// This encapsulates the logic for matching the target-legal addressing modes.
1557class AddressingModeMatcher {
1558 SmallVectorImpl<Instruction*> &AddrModeInsts;
1559 const TargetLowering &TLI;
1560
1561 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1562 /// the memory instruction that we're computing this address for.
1563 Type *AccessTy;
1564 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001565
Chandler Carruthc8925912013-01-05 02:09:22 +00001566 /// AddrMode - This is the addressing mode that we're building up. This is
1567 /// part of the return value of this addressing mode matching stuff.
1568 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001569
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001570 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1571 const SetOfInstrs &InsertedTruncs;
1572 /// A map from the instructions to their type before promotion.
1573 InstrToOrigTy &PromotedInsts;
1574 /// The ongoing transaction where every action should be registered.
1575 TypePromotionTransaction &TPT;
1576
Chandler Carruthc8925912013-01-05 02:09:22 +00001577 /// IgnoreProfitability - This is set to true when we should not do
1578 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1579 /// always returns true.
1580 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001581
Chandler Carruthc8925912013-01-05 02:09:22 +00001582 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1583 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001584 Instruction *MI, ExtAddrMode &AM,
1585 const SetOfInstrs &InsertedTruncs,
1586 InstrToOrigTy &PromotedInsts,
1587 TypePromotionTransaction &TPT)
1588 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1589 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001590 IgnoreProfitability = false;
1591 }
1592public:
Stephen Lin837bba12013-07-15 17:55:02 +00001593
Chandler Carruthc8925912013-01-05 02:09:22 +00001594 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1595 /// give an access type of AccessTy. This returns a list of involved
1596 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001597 /// \p InsertedTruncs The truncate instruction inserted by other
1598 /// CodeGenPrepare
1599 /// optimizations.
1600 /// \p PromotedInsts maps the instructions to their type before promotion.
1601 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001602 static ExtAddrMode Match(Value *V, Type *AccessTy,
1603 Instruction *MemoryInst,
1604 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001605 const TargetLowering &TLI,
1606 const SetOfInstrs &InsertedTruncs,
1607 InstrToOrigTy &PromotedInsts,
1608 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001609 ExtAddrMode Result;
1610
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001611 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1612 MemoryInst, Result, InsertedTruncs,
1613 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001614 (void)Success; assert(Success && "Couldn't select *anything*?");
1615 return Result;
1616 }
1617private:
1618 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1619 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001620 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00001621 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00001622 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1623 ExtAddrMode &AMBefore,
1624 ExtAddrMode &AMAfter);
1625 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001626 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1627 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001628};
1629
1630/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1631/// Return true and update AddrMode if this addr mode is legal for the target,
1632/// false if not.
1633bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1634 unsigned Depth) {
1635 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1636 // mode. Just process that directly.
1637 if (Scale == 1)
1638 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001639
Chandler Carruthc8925912013-01-05 02:09:22 +00001640 // If the scale is 0, it takes nothing to add this.
1641 if (Scale == 0)
1642 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001643
Chandler Carruthc8925912013-01-05 02:09:22 +00001644 // If we already have a scale of this value, we can add to it, otherwise, we
1645 // need an available scale field.
1646 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1647 return false;
1648
1649 ExtAddrMode TestAddrMode = AddrMode;
1650
1651 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1652 // [A+B + A*7] -> [B+A*8].
1653 TestAddrMode.Scale += Scale;
1654 TestAddrMode.ScaledReg = ScaleReg;
1655
1656 // If the new address isn't legal, bail out.
1657 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1658 return false;
1659
1660 // It was legal, so commit it.
1661 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001662
Chandler Carruthc8925912013-01-05 02:09:22 +00001663 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1664 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1665 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00001666 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00001667 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1668 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1669 TestAddrMode.ScaledReg = AddLHS;
1670 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001671
Chandler Carruthc8925912013-01-05 02:09:22 +00001672 // If this addressing mode is legal, commit it and remember that we folded
1673 // this instruction.
1674 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1675 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1676 AddrMode = TestAddrMode;
1677 return true;
1678 }
1679 }
1680
1681 // Otherwise, not (x+c)*scale, just return what we have.
1682 return true;
1683}
1684
1685/// MightBeFoldableInst - This is a little filter, which returns true if an
1686/// addressing computation involving I might be folded into a load/store
1687/// accessing it. This doesn't need to be perfect, but needs to accept at least
1688/// the set of instructions that MatchOperationAddr can.
1689static bool MightBeFoldableInst(Instruction *I) {
1690 switch (I->getOpcode()) {
1691 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00001692 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00001693 // Don't touch identity bitcasts.
1694 if (I->getType() == I->getOperand(0)->getType())
1695 return false;
1696 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1697 case Instruction::PtrToInt:
1698 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1699 return true;
1700 case Instruction::IntToPtr:
1701 // We know the input is intptr_t, so this is foldable.
1702 return true;
1703 case Instruction::Add:
1704 return true;
1705 case Instruction::Mul:
1706 case Instruction::Shl:
1707 // Can only handle X*C and X << C.
1708 return isa<ConstantInt>(I->getOperand(1));
1709 case Instruction::GetElementPtr:
1710 return true;
1711 default:
1712 return false;
1713 }
1714}
1715
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001716/// \brief Hepler class to perform type promotion.
1717class TypePromotionHelper {
1718 /// \brief Utility function to check whether or not a sign extension of
1719 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1720 /// using the operands of \p Inst or promoting \p Inst.
1721 /// In other words, check if:
1722 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1723 /// #1 Promotion applies:
1724 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1725 /// #2 Operand reuses:
1726 /// sext opnd1 to ConsideredSExtType.
1727 /// \p PromotedInsts maps the instructions to their type before promotion.
1728 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1729 const InstrToOrigTy &PromotedInsts);
1730
1731 /// \brief Utility function to determine if \p OpIdx should be promoted when
1732 /// promoting \p Inst.
1733 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1734 if (isa<SelectInst>(Inst) && OpIdx == 0)
1735 return false;
1736 return true;
1737 }
1738
1739 /// \brief Utility function to promote the operand of \p SExt when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001740 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001741 /// \p PromotedInsts maps the instructions to their type before promotion.
1742 /// \p CreatedInsts[out] contains how many non-free instructions have been
1743 /// created to promote the operand of SExt.
1744 /// Should never be called directly.
1745 /// \return The promoted value which is used instead of SExt.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001746 static Value *promoteOperandForTruncAndAnyExt(Instruction *SExt,
1747 TypePromotionTransaction &TPT,
1748 InstrToOrigTy &PromotedInsts,
1749 unsigned &CreatedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001750
1751 /// \brief Utility function to promote the operand of \p SExt when this
1752 /// operand is promotable and is not a supported trunc or sext.
1753 /// \p PromotedInsts maps the instructions to their type before promotion.
1754 /// \p CreatedInsts[out] contains how many non-free instructions have been
1755 /// created to promote the operand of SExt.
1756 /// Should never be called directly.
1757 /// \return The promoted value which is used instead of SExt.
1758 static Value *promoteOperandForOther(Instruction *SExt,
1759 TypePromotionTransaction &TPT,
1760 InstrToOrigTy &PromotedInsts,
1761 unsigned &CreatedInsts);
1762
1763public:
1764 /// Type for the utility function that promotes the operand of SExt.
1765 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1766 InstrToOrigTy &PromotedInsts,
1767 unsigned &CreatedInsts);
1768 /// \brief Given a sign extend instruction \p SExt, return the approriate
1769 /// action to promote the operand of \p SExt instead of using SExt.
1770 /// \return NULL if no promotable action is possible with the current
1771 /// sign extension.
1772 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1773 /// the others CodeGenPrepare optimizations. This information is important
1774 /// because we do not want to promote these instructions as CodeGenPrepare
1775 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1776 /// \p PromotedInsts maps the instructions to their type before promotion.
1777 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1778 const TargetLowering &TLI,
1779 const InstrToOrigTy &PromotedInsts);
1780};
1781
1782bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1783 Type *ConsideredSExtType,
1784 const InstrToOrigTy &PromotedInsts) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001785 // We can always get through sext or zext.
1786 if (isa<SExtInst>(Inst) || isa<ZExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001787 return true;
1788
1789 // We can get through binary operator, if it is legal. In other words, the
1790 // binary operator must have a nuw or nsw flag.
1791 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1792 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1793 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1794 return true;
1795
1796 // Check if we can do the following simplification.
1797 // sext(trunc(sext)) --> sext
1798 if (!isa<TruncInst>(Inst))
1799 return false;
1800
1801 Value *OpndVal = Inst->getOperand(0);
1802 // Check if we can use this operand in the sext.
1803 // If the type is larger than the result type of the sign extension,
1804 // we cannot.
1805 if (OpndVal->getType()->getIntegerBitWidth() >
1806 ConsideredSExtType->getIntegerBitWidth())
1807 return false;
1808
1809 // If the operand of the truncate is not an instruction, we will not have
1810 // any information on the dropped bits.
1811 // (Actually we could for constant but it is not worth the extra logic).
1812 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1813 if (!Opnd)
1814 return false;
1815
1816 // Check if the source of the type is narrow enough.
1817 // I.e., check that trunc just drops sign extended bits.
1818 // #1 get the type of the operand.
1819 const Type *OpndType;
1820 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1821 if (It != PromotedInsts.end())
1822 OpndType = It->second;
1823 else if (isa<SExtInst>(Opnd))
1824 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1825 else
1826 return false;
1827
1828 // #2 check that the truncate just drop sign extended bits.
1829 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1830 return true;
1831
1832 return false;
1833}
1834
1835TypePromotionHelper::Action TypePromotionHelper::getAction(
1836 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1837 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1838 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1839 Type *SExtTy = SExt->getType();
1840 // If the operand of the sign extension is not an instruction, we cannot
1841 // get through.
1842 // If it, check we can get through.
1843 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
Craig Topperc0196b12014-04-14 00:51:57 +00001844 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001845
1846 // Do not promote if the operand has been added by codegenprepare.
1847 // Otherwise, it means we are undoing an optimization that is likely to be
1848 // redone, thus causing potential infinite loop.
1849 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00001850 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001851
1852 // SExt or Trunc instructions.
1853 // Return the related handler.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001854 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd) ||
1855 isa<ZExtInst>(SExtOpnd))
1856 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001857
1858 // Regular instruction.
1859 // Abort early if we will have to insert non-free instructions.
1860 if (!SExtOpnd->hasOneUse() &&
1861 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00001862 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001863 return promoteOperandForOther;
1864}
1865
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001866Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001867 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1868 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1869 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1870 // get through it and this method should not be called.
1871 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00001872 Value *ExtVal = SExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001873 if (isa<ZExtInst>(SExtOpnd)) {
1874 // Replace sext(zext(opnd))
1875 // => zext(opnd).
Quentin Colombetac55b152014-09-16 22:36:07 +00001876 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001877 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1878 TPT.replaceAllUsesWith(SExt, ZExt);
1879 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001880 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001881 } else {
1882 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1883 // => sext(opnd).
1884 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1885 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001886 CreatedInsts = 0;
1887
1888 // Remove dead code.
1889 if (SExtOpnd->use_empty())
1890 TPT.eraseInstruction(SExtOpnd);
1891
Quentin Colombet9dcb7242014-09-15 18:26:58 +00001892 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00001893 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1894 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
1895 return ExtVal;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001896
Quentin Colombet9dcb7242014-09-15 18:26:58 +00001897 // At this point we have: ext ty opnd to ty.
1898 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1899 Value *NextVal = ExtInst->getOperand(0);
1900 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001901 return NextVal;
1902}
1903
1904Value *
1905TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1906 TypePromotionTransaction &TPT,
1907 InstrToOrigTy &PromotedInsts,
1908 unsigned &CreatedInsts) {
1909 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1910 // get through it and this method should not be called.
1911 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1912 CreatedInsts = 0;
1913 if (!SExtOpnd->hasOneUse()) {
1914 // SExtOpnd will be promoted.
1915 // All its uses, but SExt, will need to use a truncated value of the
1916 // promoted version.
1917 // Create the truncate now.
Quentin Colombetac55b152014-09-16 22:36:07 +00001918 Value *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1919 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
1920 ITrunc->removeFromParent();
1921 // Insert it just after the definition.
1922 ITrunc->insertAfter(SExtOpnd);
1923 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001924
1925 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1926 // Restore the operand of SExt (which has been replace by the previous call
1927 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1928 TPT.setOperand(SExt, 0, SExtOpnd);
1929 }
1930
1931 // Get through the Instruction:
1932 // 1. Update its type.
1933 // 2. Replace the uses of SExt by Inst.
1934 // 3. Sign extend each operand that needs to be sign extended.
1935
1936 // Remember the original type of the instruction before promotion.
1937 // This is useful to know that the high bits are sign extended bits.
1938 PromotedInsts.insert(
1939 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1940 // Step #1.
1941 TPT.mutateType(SExtOpnd, SExt->getType());
1942 // Step #2.
1943 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1944 // Step #3.
1945 Instruction *SExtForOpnd = SExt;
1946
1947 DEBUG(dbgs() << "Propagate SExt to operands\n");
1948 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1949 ++OpIdx) {
1950 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1951 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1952 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1953 DEBUG(dbgs() << "No need to propagate\n");
1954 continue;
1955 }
1956 // Check if we can statically sign extend the operand.
1957 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1958 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1959 DEBUG(dbgs() << "Statically sign extend\n");
1960 TPT.setOperand(
1961 SExtOpnd, OpIdx,
1962 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1963 continue;
1964 }
1965 // UndefValue are typed, so we have to statically sign extend them.
1966 if (isa<UndefValue>(Opnd)) {
1967 DEBUG(dbgs() << "Statically sign extend\n");
1968 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1969 continue;
1970 }
1971
1972 // Otherwise we have to explicity sign extend the operand.
1973 // Check if SExt was reused to sign extend an operand.
1974 if (!SExtForOpnd) {
1975 // If yes, create a new one.
1976 DEBUG(dbgs() << "More operands to sext\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00001977 SExtForOpnd =
1978 cast<Instruction>(TPT.createSExt(SExt, Opnd, SExt->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001979 ++CreatedInsts;
1980 }
1981
1982 TPT.setOperand(SExtForOpnd, 0, Opnd);
1983
1984 // Move the sign extension before the insertion point.
1985 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1986 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1987 // If more sext are required, new instructions will have to be created.
Craig Topperc0196b12014-04-14 00:51:57 +00001988 SExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001989 }
1990 if (SExtForOpnd == SExt) {
1991 DEBUG(dbgs() << "Sign extension is useless now\n");
1992 TPT.eraseInstruction(SExt);
1993 }
1994 return SExtOpnd;
1995}
1996
Quentin Colombet867c5502014-02-14 22:23:22 +00001997/// IsPromotionProfitable - Check whether or not promoting an instruction
1998/// to a wider type was profitable.
1999/// \p MatchedSize gives the number of instructions that have been matched
2000/// in the addressing mode after the promotion was applied.
2001/// \p SizeWithPromotion gives the number of created instructions for
2002/// the promotion plus the number of instructions that have been
2003/// matched in the addressing mode before the promotion.
2004/// \p PromotedOperand is the value that has been promoted.
2005/// \return True if the promotion is profitable, false otherwise.
2006bool
2007AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2008 unsigned SizeWithPromotion,
2009 Value *PromotedOperand) const {
2010 // We folded less instructions than what we created to promote the operand.
2011 // This is not profitable.
2012 if (MatchedSize < SizeWithPromotion)
2013 return false;
2014 if (MatchedSize > SizeWithPromotion)
2015 return true;
2016 // The promotion is neutral but it may help folding the sign extension in
2017 // loads for instance.
2018 // Check that we did not create an illegal instruction.
2019 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2020 if (!PromotedInst)
2021 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00002022 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2023 // If the ISDOpcode is undefined, it was undefined before the promotion.
2024 if (!ISDOpcode)
2025 return true;
2026 // Otherwise, check if the promoted instruction is legal or not.
2027 return TLI.isOperationLegalOrCustom(ISDOpcode,
Quentin Colombet867c5502014-02-14 22:23:22 +00002028 EVT::getEVT(PromotedInst->getType()));
2029}
2030
Chandler Carruthc8925912013-01-05 02:09:22 +00002031/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2032/// fold the operation into the addressing mode. If so, update the addressing
2033/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002034/// If \p MovedAway is not NULL, it contains the information of whether or
2035/// not AddrInst has to be folded into the addressing mode on success.
2036/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2037/// because it has been moved away.
2038/// Thus AddrInst must not be added in the matched instructions.
2039/// This state can happen when AddrInst is a sext, since it may be moved away.
2040/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2041/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002042bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002043 unsigned Depth,
2044 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002045 // Avoid exponential behavior on extremely deep expression trees.
2046 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002047
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002048 // By default, all matched instructions stay in place.
2049 if (MovedAway)
2050 *MovedAway = false;
2051
Chandler Carruthc8925912013-01-05 02:09:22 +00002052 switch (Opcode) {
2053 case Instruction::PtrToInt:
2054 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2055 return MatchAddr(AddrInst->getOperand(0), Depth);
2056 case Instruction::IntToPtr:
2057 // This inttoptr is a no-op if the integer type is pointer sized.
2058 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002059 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00002060 return MatchAddr(AddrInst->getOperand(0), Depth);
2061 return false;
2062 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002063 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002064 // BitCast is always a noop, and we can handle it as long as it is
2065 // int->int or pointer->pointer (we don't want int<->fp or something).
2066 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2067 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2068 // Don't touch identity bitcasts. These were probably put here by LSR,
2069 // and we don't want to mess around with them. Assume it knows what it
2070 // is doing.
2071 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2072 return MatchAddr(AddrInst->getOperand(0), Depth);
2073 return false;
2074 case Instruction::Add: {
2075 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2076 ExtAddrMode BackupAddrMode = AddrMode;
2077 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002078 // Start a transaction at this point.
2079 // The LHS may match but not the RHS.
2080 // Therefore, we need a higher level restoration point to undo partially
2081 // matched operation.
2082 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2083 TPT.getRestorationPoint();
2084
Chandler Carruthc8925912013-01-05 02:09:22 +00002085 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2086 MatchAddr(AddrInst->getOperand(0), Depth+1))
2087 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002088
Chandler Carruthc8925912013-01-05 02:09:22 +00002089 // Restore the old addr mode info.
2090 AddrMode = BackupAddrMode;
2091 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002092 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002093
Chandler Carruthc8925912013-01-05 02:09:22 +00002094 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2095 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2096 MatchAddr(AddrInst->getOperand(1), Depth+1))
2097 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002098
Chandler Carruthc8925912013-01-05 02:09:22 +00002099 // Otherwise we definitely can't merge the ADD in.
2100 AddrMode = BackupAddrMode;
2101 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002102 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002103 break;
2104 }
2105 //case Instruction::Or:
2106 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2107 //break;
2108 case Instruction::Mul:
2109 case Instruction::Shl: {
2110 // Can only handle X*C and X << C.
2111 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002112 if (!RHS)
2113 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002114 int64_t Scale = RHS->getSExtValue();
2115 if (Opcode == Instruction::Shl)
2116 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002117
Chandler Carruthc8925912013-01-05 02:09:22 +00002118 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2119 }
2120 case Instruction::GetElementPtr: {
2121 // Scan the GEP. We check it if it contains constant offsets and at most
2122 // one variable offset.
2123 int VariableOperand = -1;
2124 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002125
Chandler Carruthc8925912013-01-05 02:09:22 +00002126 int64_t ConstantOffset = 0;
2127 const DataLayout *TD = TLI.getDataLayout();
2128 gep_type_iterator GTI = gep_type_begin(AddrInst);
2129 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2130 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2131 const StructLayout *SL = TD->getStructLayout(STy);
2132 unsigned Idx =
2133 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2134 ConstantOffset += SL->getElementOffset(Idx);
2135 } else {
2136 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2137 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2138 ConstantOffset += CI->getSExtValue()*TypeSize;
2139 } else if (TypeSize) { // Scales of zero don't do anything.
2140 // We only allow one variable index at the moment.
2141 if (VariableOperand != -1)
2142 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002143
Chandler Carruthc8925912013-01-05 02:09:22 +00002144 // Remember the variable index.
2145 VariableOperand = i;
2146 VariableScale = TypeSize;
2147 }
2148 }
2149 }
Stephen Lin837bba12013-07-15 17:55:02 +00002150
Chandler Carruthc8925912013-01-05 02:09:22 +00002151 // A common case is for the GEP to only do a constant offset. In this case,
2152 // just add it to the disp field and check validity.
2153 if (VariableOperand == -1) {
2154 AddrMode.BaseOffs += ConstantOffset;
2155 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2156 // Check to see if we can fold the base pointer in too.
2157 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2158 return true;
2159 }
2160 AddrMode.BaseOffs -= ConstantOffset;
2161 return false;
2162 }
2163
2164 // Save the valid addressing mode in case we can't match.
2165 ExtAddrMode BackupAddrMode = AddrMode;
2166 unsigned OldSize = AddrModeInsts.size();
2167
2168 // See if the scale and offset amount is valid for this target.
2169 AddrMode.BaseOffs += ConstantOffset;
2170
2171 // Match the base operand of the GEP.
2172 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2173 // If it couldn't be matched, just stuff the value in a register.
2174 if (AddrMode.HasBaseReg) {
2175 AddrMode = BackupAddrMode;
2176 AddrModeInsts.resize(OldSize);
2177 return false;
2178 }
2179 AddrMode.HasBaseReg = true;
2180 AddrMode.BaseReg = AddrInst->getOperand(0);
2181 }
2182
2183 // Match the remaining variable portion of the GEP.
2184 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2185 Depth)) {
2186 // If it couldn't be matched, try stuffing the base into a register
2187 // instead of matching it, and retrying the match of the scale.
2188 AddrMode = BackupAddrMode;
2189 AddrModeInsts.resize(OldSize);
2190 if (AddrMode.HasBaseReg)
2191 return false;
2192 AddrMode.HasBaseReg = true;
2193 AddrMode.BaseReg = AddrInst->getOperand(0);
2194 AddrMode.BaseOffs += ConstantOffset;
2195 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2196 VariableScale, Depth)) {
2197 // If even that didn't work, bail.
2198 AddrMode = BackupAddrMode;
2199 AddrModeInsts.resize(OldSize);
2200 return false;
2201 }
2202 }
2203
2204 return true;
2205 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002206 case Instruction::SExt: {
Sanjay Patelab60d042014-07-16 21:08:10 +00002207 Instruction *SExt = dyn_cast<Instruction>(AddrInst);
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002208 if (!SExt)
2209 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002210
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002211 // Try to move this sext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002212 // Ask for a method for doing so.
2213 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
2214 SExt, InsertedTruncs, TLI, PromotedInsts);
2215 if (!TPH)
2216 return false;
2217
2218 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2219 TPT.getRestorationPoint();
2220 unsigned CreatedInsts = 0;
2221 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
2222 // SExt has been moved away.
2223 // Thus either it will be rematched later in the recursive calls or it is
2224 // gone. Anyway, we must not fold it into the addressing mode at this point.
2225 // E.g.,
2226 // op = add opnd, 1
2227 // idx = sext op
2228 // addr = gep base, idx
2229 // is now:
2230 // promotedOpnd = sext opnd <- no match here
2231 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2232 // addr = gep base, op <- match
2233 if (MovedAway)
2234 *MovedAway = true;
2235
2236 assert(PromotedOperand &&
2237 "TypePromotionHelper should have filtered out those cases");
2238
2239 ExtAddrMode BackupAddrMode = AddrMode;
2240 unsigned OldSize = AddrModeInsts.size();
2241
2242 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002243 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2244 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002245 AddrMode = BackupAddrMode;
2246 AddrModeInsts.resize(OldSize);
2247 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2248 TPT.rollback(LastKnownGood);
2249 return false;
2250 }
2251 return true;
2252 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002253 }
2254 return false;
2255}
2256
2257/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2258/// addressing mode. If Addr can't be added to AddrMode this returns false and
2259/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2260/// or intptr_t for the target.
2261///
2262bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002263 // Start a transaction at this point that we will rollback if the matching
2264 // fails.
2265 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2266 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002267 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2268 // Fold in immediates if legal for the target.
2269 AddrMode.BaseOffs += CI->getSExtValue();
2270 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2271 return true;
2272 AddrMode.BaseOffs -= CI->getSExtValue();
2273 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2274 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002275 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002276 AddrMode.BaseGV = GV;
2277 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2278 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002279 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002280 }
2281 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2282 ExtAddrMode BackupAddrMode = AddrMode;
2283 unsigned OldSize = AddrModeInsts.size();
2284
2285 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002286 bool MovedAway = false;
2287 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2288 // This instruction may have been move away. If so, there is nothing
2289 // to check here.
2290 if (MovedAway)
2291 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002292 // Okay, it's possible to fold this. Check to see if it is actually
2293 // *profitable* to do so. We use a simple cost model to avoid increasing
2294 // register pressure too much.
2295 if (I->hasOneUse() ||
2296 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2297 AddrModeInsts.push_back(I);
2298 return true;
2299 }
Stephen Lin837bba12013-07-15 17:55:02 +00002300
Chandler Carruthc8925912013-01-05 02:09:22 +00002301 // It isn't profitable to do this, roll back.
2302 //cerr << "NOT FOLDING: " << *I;
2303 AddrMode = BackupAddrMode;
2304 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002305 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002306 }
2307 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2308 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2309 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002310 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002311 } else if (isa<ConstantPointerNull>(Addr)) {
2312 // Null pointer gets folded without affecting the addressing mode.
2313 return true;
2314 }
2315
2316 // Worse case, the target should support [reg] addressing modes. :)
2317 if (!AddrMode.HasBaseReg) {
2318 AddrMode.HasBaseReg = true;
2319 AddrMode.BaseReg = Addr;
2320 // Still check for legality in case the target supports [imm] but not [i+r].
2321 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2322 return true;
2323 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002324 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002325 }
2326
2327 // If the base register is already taken, see if we can do [r+r].
2328 if (AddrMode.Scale == 0) {
2329 AddrMode.Scale = 1;
2330 AddrMode.ScaledReg = Addr;
2331 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2332 return true;
2333 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002334 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002335 }
2336 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002337 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002338 return false;
2339}
2340
2341/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2342/// inline asm call are due to memory operands. If so, return true, otherwise
2343/// return false.
2344static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2345 const TargetLowering &TLI) {
2346 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2347 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2348 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002349
Chandler Carruthc8925912013-01-05 02:09:22 +00002350 // Compute the constraint code and ConstraintType to use.
2351 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2352
2353 // If this asm operand is our Value*, and if it isn't an indirect memory
2354 // operand, we can't fold it!
2355 if (OpInfo.CallOperandVal == OpVal &&
2356 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2357 !OpInfo.isIndirect))
2358 return false;
2359 }
2360
2361 return true;
2362}
2363
2364/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2365/// memory use. If we find an obviously non-foldable instruction, return true.
2366/// Add the ultimately found memory instructions to MemoryUses.
2367static bool FindAllMemoryUses(Instruction *I,
2368 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Craig Topper71b7b682014-08-21 05:55:13 +00002369 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
Chandler Carruthc8925912013-01-05 02:09:22 +00002370 const TargetLowering &TLI) {
2371 // If we already considered this instruction, we're done.
2372 if (!ConsideredInsts.insert(I))
2373 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002374
Chandler Carruthc8925912013-01-05 02:09:22 +00002375 // If this is an obviously unfoldable instruction, bail out.
2376 if (!MightBeFoldableInst(I))
2377 return true;
2378
2379 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002380 for (Use &U : I->uses()) {
2381 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002382
Chandler Carruthcdf47882014-03-09 03:16:01 +00002383 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2384 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002385 continue;
2386 }
Stephen Lin837bba12013-07-15 17:55:02 +00002387
Chandler Carruthcdf47882014-03-09 03:16:01 +00002388 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2389 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002390 if (opNo == 0) return true; // Storing addr, not into addr.
2391 MemoryUses.push_back(std::make_pair(SI, opNo));
2392 continue;
2393 }
Stephen Lin837bba12013-07-15 17:55:02 +00002394
Chandler Carruthcdf47882014-03-09 03:16:01 +00002395 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002396 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2397 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002398
Chandler Carruthc8925912013-01-05 02:09:22 +00002399 // If this is a memory operand, we're cool, otherwise bail out.
2400 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2401 return true;
2402 continue;
2403 }
Stephen Lin837bba12013-07-15 17:55:02 +00002404
Chandler Carruthcdf47882014-03-09 03:16:01 +00002405 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002406 return true;
2407 }
2408
2409 return false;
2410}
2411
2412/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2413/// the use site that we're folding it into. If so, there is no cost to
2414/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2415/// that we know are live at the instruction already.
2416bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2417 Value *KnownLive2) {
2418 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002419 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002420 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002421
Chandler Carruthc8925912013-01-05 02:09:22 +00002422 // All values other than instructions and arguments (e.g. constants) are live.
2423 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002424
Chandler Carruthc8925912013-01-05 02:09:22 +00002425 // If Val is a constant sized alloca in the entry block, it is live, this is
2426 // true because it is just a reference to the stack/frame pointer, which is
2427 // live for the whole function.
2428 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2429 if (AI->isStaticAlloca())
2430 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002431
Chandler Carruthc8925912013-01-05 02:09:22 +00002432 // Check to see if this value is already used in the memory instruction's
2433 // block. If so, it's already live into the block at the very least, so we
2434 // can reasonably fold it.
2435 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2436}
2437
2438/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2439/// mode of the machine to fold the specified instruction into a load or store
2440/// that ultimately uses it. However, the specified instruction has multiple
2441/// uses. Given this, it may actually increase register pressure to fold it
2442/// into the load. For example, consider this code:
2443///
2444/// X = ...
2445/// Y = X+1
2446/// use(Y) -> nonload/store
2447/// Z = Y+1
2448/// load Z
2449///
2450/// In this case, Y has multiple uses, and can be folded into the load of Z
2451/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2452/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2453/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2454/// number of computations either.
2455///
2456/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2457/// X was live across 'load Z' for other reasons, we actually *would* want to
2458/// fold the addressing mode in the Z case. This would make Y die earlier.
2459bool AddressingModeMatcher::
2460IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2461 ExtAddrMode &AMAfter) {
2462 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002463
Chandler Carruthc8925912013-01-05 02:09:22 +00002464 // AMBefore is the addressing mode before this instruction was folded into it,
2465 // and AMAfter is the addressing mode after the instruction was folded. Get
2466 // the set of registers referenced by AMAfter and subtract out those
2467 // referenced by AMBefore: this is the set of values which folding in this
2468 // address extends the lifetime of.
2469 //
2470 // Note that there are only two potential values being referenced here,
2471 // BaseReg and ScaleReg (global addresses are always available, as are any
2472 // folded immediates).
2473 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002474
Chandler Carruthc8925912013-01-05 02:09:22 +00002475 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2476 // lifetime wasn't extended by adding this instruction.
2477 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002478 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002479 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002480 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002481
2482 // If folding this instruction (and it's subexprs) didn't extend any live
2483 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002484 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002485 return true;
2486
2487 // If all uses of this instruction are ultimately load/store/inlineasm's,
2488 // check to see if their addressing modes will include this instruction. If
2489 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2490 // uses.
2491 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2492 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2493 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2494 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002495
Chandler Carruthc8925912013-01-05 02:09:22 +00002496 // Now that we know that all uses of this instruction are part of a chain of
2497 // computation involving only operations that could theoretically be folded
2498 // into a memory use, loop over each of these uses and see if they could
2499 // *actually* fold the instruction.
2500 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2501 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2502 Instruction *User = MemoryUses[i].first;
2503 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002504
Chandler Carruthc8925912013-01-05 02:09:22 +00002505 // Get the access type of this use. If the use isn't a pointer, we don't
2506 // know what it accesses.
2507 Value *Address = User->getOperand(OpNo);
2508 if (!Address->getType()->isPointerTy())
2509 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002510 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002511
Chandler Carruthc8925912013-01-05 02:09:22 +00002512 // Do a match against the root of this address, ignoring profitability. This
2513 // will tell us if the addressing mode for the memory operation will
2514 // *actually* cover the shared instruction.
2515 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002516 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2517 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002518 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002519 MemoryInst, Result, InsertedTruncs,
2520 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002521 Matcher.IgnoreProfitability = true;
2522 bool Success = Matcher.MatchAddr(Address, 0);
2523 (void)Success; assert(Success && "Couldn't select *anything*?");
2524
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002525 // The match was to check the profitability, the changes made are not
2526 // part of the original matcher. Therefore, they should be dropped
2527 // otherwise the original matcher will not present the right state.
2528 TPT.rollback(LastKnownGood);
2529
Chandler Carruthc8925912013-01-05 02:09:22 +00002530 // If the match didn't cover I, then it won't be shared by it.
2531 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2532 I) == MatchedAddrModeInsts.end())
2533 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002534
Chandler Carruthc8925912013-01-05 02:09:22 +00002535 MatchedAddrModeInsts.clear();
2536 }
Stephen Lin837bba12013-07-15 17:55:02 +00002537
Chandler Carruthc8925912013-01-05 02:09:22 +00002538 return true;
2539}
2540
2541} // end anonymous namespace
2542
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002543/// IsNonLocalValue - Return true if the specified values are defined in a
2544/// different basic block than BB.
2545static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2546 if (Instruction *I = dyn_cast<Instruction>(V))
2547 return I->getParent() != BB;
2548 return false;
2549}
2550
Bob Wilson53bdae32009-12-03 21:47:07 +00002551/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002552/// addressing modes that can do significant amounts of computation. As such,
2553/// instruction selection will try to get the load or store to do as much
2554/// computation as possible for the program. The problem is that isel can only
2555/// see within a single block. As such, we sink as much legal addressing mode
2556/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002557///
2558/// This method is used to optimize both load/store and inline asms with memory
2559/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002560bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002561 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002562 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002563
2564 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002565 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002566 SmallVector<Value*, 8> worklist;
2567 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002568 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002569
Owen Anderson8ba5f392010-11-27 08:15:55 +00002570 // Use a worklist to iteratively look through PHI nodes, and ensure that
2571 // the addressing mode obtained from the non-PHI roots of the graph
2572 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00002573 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002574 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002575 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002576 SmallVector<Instruction*, 16> AddrModeInsts;
2577 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002578 TypePromotionTransaction TPT;
2579 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2580 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002581 while (!worklist.empty()) {
2582 Value *V = worklist.back();
2583 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002584
Owen Anderson8ba5f392010-11-27 08:15:55 +00002585 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002586 if (!Visited.insert(V)) {
Craig Topperc0196b12014-04-14 00:51:57 +00002587 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002588 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002589 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002590
Owen Anderson8ba5f392010-11-27 08:15:55 +00002591 // For a PHI node, push all of its incoming values.
2592 if (PHINode *P = dyn_cast<PHINode>(V)) {
2593 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2594 worklist.push_back(P->getIncomingValue(i));
2595 continue;
2596 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002597
Owen Anderson8ba5f392010-11-27 08:15:55 +00002598 // For non-PHIs, determine the addressing mode being computed.
2599 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002600 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2601 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2602 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002603
2604 // This check is broken into two cases with very similar code to avoid using
2605 // getNumUses() as much as possible. Some values have a lot of uses, so
2606 // calling getNumUses() unconditionally caused a significant compile-time
2607 // regression.
2608 if (!Consensus) {
2609 Consensus = V;
2610 AddrMode = NewAddrMode;
2611 AddrModeInsts = NewAddrModeInsts;
2612 continue;
2613 } else if (NewAddrMode == AddrMode) {
2614 if (!IsNumUsesConsensusValid) {
2615 NumUsesConsensus = Consensus->getNumUses();
2616 IsNumUsesConsensusValid = true;
2617 }
2618
2619 // Ensure that the obtained addressing mode is equivalent to that obtained
2620 // for all other roots of the PHI traversal. Also, when choosing one
2621 // such root as representative, select the one with the most uses in order
2622 // to keep the cost modeling heuristics in AddressingModeMatcher
2623 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002624 unsigned NumUses = V->getNumUses();
2625 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002626 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002627 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002628 AddrModeInsts = NewAddrModeInsts;
2629 }
2630 continue;
2631 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002632
Craig Topperc0196b12014-04-14 00:51:57 +00002633 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002634 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002635 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002636
Owen Anderson8ba5f392010-11-27 08:15:55 +00002637 // If the addressing mode couldn't be determined, or if multiple different
2638 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002639 if (!Consensus) {
2640 TPT.rollback(LastKnownGood);
2641 return false;
2642 }
2643 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002644
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002645 // Check to see if any of the instructions supersumed by this addr mode are
2646 // non-local to I's BB.
2647 bool AnyNonLocal = false;
2648 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002649 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002650 AnyNonLocal = true;
2651 break;
2652 }
2653 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002654
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002655 // If all the instructions matched are already in this BB, don't do anything.
2656 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002657 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002658 return false;
2659 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002660
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002661 // Insert this computation right after this user. Since our caller is
2662 // scanning from the top of the BB to the bottom, reuse of the expr are
2663 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002664 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002665
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002666 // Now that we determined the addressing expression we want to use and know
2667 // that we have to sink it into this block. Check to see if we have already
2668 // done this for some other load/store instr in this block. If so, reuse the
2669 // computation.
2670 Value *&SunkAddr = SunkAddrs[Addr];
2671 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002672 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002673 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002674 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002675 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00002676 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2677 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2678 // By default, we use the GEP-based method when AA is used later. This
2679 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2680 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002681 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00002682 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002683 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002684
2685 // First, find the pointer.
2686 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2687 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002688 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002689 }
2690
2691 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2692 // We can't add more than one pointer together, nor can we scale a
2693 // pointer (both of which seem meaningless).
2694 if (ResultPtr || AddrMode.Scale != 1)
2695 return false;
2696
2697 ResultPtr = AddrMode.ScaledReg;
2698 AddrMode.Scale = 0;
2699 }
2700
2701 if (AddrMode.BaseGV) {
2702 if (ResultPtr)
2703 return false;
2704
2705 ResultPtr = AddrMode.BaseGV;
2706 }
2707
2708 // If the real base value actually came from an inttoptr, then the matcher
2709 // will look through it and provide only the integer value. In that case,
2710 // use it here.
2711 if (!ResultPtr && AddrMode.BaseReg) {
2712 ResultPtr =
2713 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00002714 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002715 } else if (!ResultPtr && AddrMode.Scale == 1) {
2716 ResultPtr =
2717 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2718 AddrMode.Scale = 0;
2719 }
2720
2721 if (!ResultPtr &&
2722 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2723 SunkAddr = Constant::getNullValue(Addr->getType());
2724 } else if (!ResultPtr) {
2725 return false;
2726 } else {
2727 Type *I8PtrTy =
2728 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2729
2730 // Start with the base register. Do this first so that subsequent address
2731 // matching finds it last, which will prevent it from trying to match it
2732 // as the scaled value in case it happens to be a mul. That would be
2733 // problematic if we've sunk a different mul for the scale, because then
2734 // we'd end up sinking both muls.
2735 if (AddrMode.BaseReg) {
2736 Value *V = AddrMode.BaseReg;
2737 if (V->getType() != IntPtrTy)
2738 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2739
2740 ResultIndex = V;
2741 }
2742
2743 // Add the scale value.
2744 if (AddrMode.Scale) {
2745 Value *V = AddrMode.ScaledReg;
2746 if (V->getType() == IntPtrTy) {
2747 // done.
2748 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2749 cast<IntegerType>(V->getType())->getBitWidth()) {
2750 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2751 } else {
2752 // It is only safe to sign extend the BaseReg if we know that the math
2753 // required to create it did not overflow before we extend it. Since
2754 // the original IR value was tossed in favor of a constant back when
2755 // the AddrMode was created we need to bail out gracefully if widths
2756 // do not match instead of extending it.
2757 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2758 if (I && (ResultIndex != AddrMode.BaseReg))
2759 I->eraseFromParent();
2760 return false;
2761 }
2762
2763 if (AddrMode.Scale != 1)
2764 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2765 "sunkaddr");
2766 if (ResultIndex)
2767 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2768 else
2769 ResultIndex = V;
2770 }
2771
2772 // Add in the Base Offset if present.
2773 if (AddrMode.BaseOffs) {
2774 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2775 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002776 // We need to add this separately from the scale above to help with
2777 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00002778 if (ResultPtr->getType() != I8PtrTy)
2779 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2780 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2781 }
2782
2783 ResultIndex = V;
2784 }
2785
2786 if (!ResultIndex) {
2787 SunkAddr = ResultPtr;
2788 } else {
2789 if (ResultPtr->getType() != I8PtrTy)
2790 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2791 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2792 }
2793
2794 if (SunkAddr->getType() != Addr->getType())
2795 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2796 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002797 } else {
David Greene74e2d492010-01-05 01:27:11 +00002798 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002799 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002800 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002801 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00002802
2803 // Start with the base register. Do this first so that subsequent address
2804 // matching finds it last, which will prevent it from trying to match it
2805 // as the scaled value in case it happens to be a mul. That would be
2806 // problematic if we've sunk a different mul for the scale, because then
2807 // we'd end up sinking both muls.
2808 if (AddrMode.BaseReg) {
2809 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002810 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002811 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002812 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002813 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002814 Result = V;
2815 }
2816
2817 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002818 if (AddrMode.Scale) {
2819 Value *V = AddrMode.ScaledReg;
2820 if (V->getType() == IntPtrTy) {
2821 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002822 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002823 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002824 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2825 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002826 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002827 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002828 // It is only safe to sign extend the BaseReg if we know that the math
2829 // required to create it did not overflow before we extend it. Since
2830 // the original IR value was tossed in favor of a constant back when
2831 // the AddrMode was created we need to bail out gracefully if widths
2832 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00002833 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00002834 if (I && (Result != AddrMode.BaseReg))
2835 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002836 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002837 }
2838 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002839 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2840 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002841 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002842 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002843 else
2844 Result = V;
2845 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002846
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002847 // Add in the BaseGV if present.
2848 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002849 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002850 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002851 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002852 else
2853 Result = V;
2854 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002855
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002856 // Add in the Base Offset if present.
2857 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002858 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002859 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002860 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002861 else
2862 Result = V;
2863 }
2864
Craig Topperc0196b12014-04-14 00:51:57 +00002865 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002866 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002867 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002868 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002869 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002870
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002871 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002872
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002873 // If we have no uses, recursively delete the value and all dead instructions
2874 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002875 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002876 // This can cause recursive deletion, which can invalidate our iterator.
2877 // Use a WeakVH to hold onto it in case this happens.
2878 WeakVH IterHandle(CurInstIterator);
2879 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002880
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002881 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002882
2883 if (IterHandle != CurInstIterator) {
2884 // If the iterator instruction was recursively deleted, start over at the
2885 // start of the block.
2886 CurInstIterator = BB->begin();
2887 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002888 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002889 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002890 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002891 return true;
2892}
2893
Evan Cheng1da25002008-02-26 02:42:37 +00002894/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002895/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002896/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002897bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002898 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002899
Nadav Rotem465834c2012-07-24 10:51:42 +00002900 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002901 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002902 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002903 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2904 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002905
Evan Cheng1da25002008-02-26 02:42:37 +00002906 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002907 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002908
Eli Friedman666bbe32008-02-26 18:37:49 +00002909 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2910 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002911 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002912 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002913 } else if (OpInfo.Type == InlineAsm::isInput)
2914 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002915 }
2916
2917 return MadeChange;
2918}
2919
Dan Gohman99429a02009-10-16 20:59:35 +00002920/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2921/// basic block as the load, unless conditions are unfavorable. This allows
2922/// SelectionDAG to fold the extend into the load.
2923///
2924bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2925 // Look for a load being extended.
2926 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2927 if (!LI) return false;
2928
2929 // If they're already in the same block, there's nothing to do.
2930 if (LI->getParent() == I->getParent())
2931 return false;
2932
2933 // If the load has other users and the truncate is not free, this probably
2934 // isn't worthwhile.
2935 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002936 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2937 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002938 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002939 return false;
2940
2941 // Check whether the target supports casts folded into loads.
2942 unsigned LType;
2943 if (isa<ZExtInst>(I))
2944 LType = ISD::ZEXTLOAD;
2945 else {
2946 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2947 LType = ISD::SEXTLOAD;
2948 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002949 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002950 return false;
2951
2952 // Move the extend into the same block as the load, so that SelectionDAG
2953 // can fold it.
2954 I->removeFromParent();
2955 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002956 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002957 return true;
2958}
2959
Evan Chengd3d80172007-12-05 23:58:20 +00002960bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2961 BasicBlock *DefBB = I->getParent();
2962
Bob Wilsonff714f92010-09-21 21:44:14 +00002963 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002964 // other uses of the source with result of extension.
2965 Value *Src = I->getOperand(0);
2966 if (Src->hasOneUse())
2967 return false;
2968
Evan Cheng2011df42007-12-13 07:50:36 +00002969 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002970 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002971 return false;
2972
Evan Cheng7bc89422007-12-12 00:51:06 +00002973 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002974 // this block.
2975 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002976 return false;
2977
Evan Chengd3d80172007-12-05 23:58:20 +00002978 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002979 for (User *U : I->users()) {
2980 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00002981
2982 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002983 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00002984 if (UserBB == DefBB) continue;
2985 DefIsLiveOut = true;
2986 break;
2987 }
2988 if (!DefIsLiveOut)
2989 return false;
2990
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002991 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002992 for (User *U : Src->users()) {
2993 Instruction *UI = cast<Instruction>(U);
2994 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00002995 if (UserBB == DefBB) continue;
2996 // Be conservative. We don't want this xform to end up introducing
2997 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002998 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002999 return false;
3000 }
3001
Evan Chengd3d80172007-12-05 23:58:20 +00003002 // InsertedTruncs - Only insert one trunc in each block once.
3003 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3004
3005 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003006 for (Use &U : Src->uses()) {
3007 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003008
3009 // Figure out which BB this ext is used in.
3010 BasicBlock *UserBB = User->getParent();
3011 if (UserBB == DefBB) continue;
3012
3013 // Both src and def are live in this block. Rewrite the use.
3014 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3015
3016 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003017 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003018 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003019 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003020 }
3021
3022 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003023 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003024 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003025 MadeChange = true;
3026 }
3027
3028 return MadeChange;
3029}
3030
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003031/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3032/// turned into an explicit branch.
3033static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3034 // FIXME: This should use the same heuristics as IfConversion to determine
3035 // whether a select is better represented as a branch. This requires that
3036 // branch probability metadata is preserved for the select, which is not the
3037 // case currently.
3038
3039 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3040
3041 // If the branch is predicted right, an out of order CPU can avoid blocking on
3042 // the compare. Emit cmovs on compares with a memory operand as branches to
3043 // avoid stalls on the load from memory. If the compare has more than one use
3044 // there's probably another cmov or setcc around so it's not worth emitting a
3045 // branch.
3046 if (!Cmp)
3047 return false;
3048
3049 Value *CmpOp0 = Cmp->getOperand(0);
3050 Value *CmpOp1 = Cmp->getOperand(1);
3051
3052 // We check that the memory operand has one use to avoid uses of the loaded
3053 // value directly after the compare, making branches unprofitable.
3054 return Cmp->hasOneUse() &&
3055 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3056 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3057}
3058
3059
Nadav Rotem9d832022012-09-02 12:10:19 +00003060/// If we have a SelectInst that will likely profit from branch prediction,
3061/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003062bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003063 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3064
3065 // Can we convert the 'select' to CF ?
3066 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003067 return false;
3068
Nadav Rotem9d832022012-09-02 12:10:19 +00003069 TargetLowering::SelectSupportKind SelectKind;
3070 if (VectorCond)
3071 SelectKind = TargetLowering::VectorMaskSelect;
3072 else if (SI->getType()->isVectorTy())
3073 SelectKind = TargetLowering::ScalarCondVectorVal;
3074 else
3075 SelectKind = TargetLowering::ScalarValSelect;
3076
3077 // Do we have efficient codegen support for this kind of 'selects' ?
3078 if (TLI->isSelectSupported(SelectKind)) {
3079 // We have efficient codegen support for the select instruction.
3080 // Check if it is profitable to keep this 'select'.
3081 if (!TLI->isPredictableSelectExpensive() ||
3082 !isFormingBranchFromSelectProfitable(SI))
3083 return false;
3084 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003085
3086 ModifiedDT = true;
3087
3088 // First, we split the block containing the select into 2 blocks.
3089 BasicBlock *StartBlock = SI->getParent();
3090 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3091 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3092
3093 // Create a new block serving as the landing pad for the branch.
3094 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3095 NextBlock->getParent(), NextBlock);
3096
3097 // Move the unconditional branch from the block with the select in it into our
3098 // landing pad block.
3099 StartBlock->getTerminator()->eraseFromParent();
3100 BranchInst::Create(NextBlock, SmallBlock);
3101
3102 // Insert the real conditional branch based on the original condition.
3103 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3104
3105 // The select itself is replaced with a PHI Node.
3106 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3107 PN->takeName(SI);
3108 PN->addIncoming(SI->getTrueValue(), StartBlock);
3109 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3110 SI->replaceAllUsesWith(PN);
3111 SI->eraseFromParent();
3112
3113 // Instruct OptimizeBlock to skip to the next block.
3114 CurInstIterator = StartBlock->end();
3115 ++NumSelectsExpanded;
3116 return true;
3117}
3118
Benjamin Kramer573ff362014-03-01 17:24:40 +00003119static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003120 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3121 int SplatElem = -1;
3122 for (unsigned i = 0; i < Mask.size(); ++i) {
3123 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3124 return false;
3125 SplatElem = Mask[i];
3126 }
3127
3128 return true;
3129}
3130
3131/// Some targets have expensive vector shifts if the lanes aren't all the same
3132/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3133/// it's often worth sinking a shufflevector splat down to its use so that
3134/// codegen can spot all lanes are identical.
3135bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3136 BasicBlock *DefBB = SVI->getParent();
3137
3138 // Only do this xform if variable vector shifts are particularly expensive.
3139 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3140 return false;
3141
3142 // We only expect better codegen by sinking a shuffle if we can recognise a
3143 // constant splat.
3144 if (!isBroadcastShuffle(SVI))
3145 return false;
3146
3147 // InsertedShuffles - Only insert a shuffle in each block once.
3148 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3149
3150 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003151 for (User *U : SVI->users()) {
3152 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003153
3154 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003155 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003156 if (UserBB == DefBB) continue;
3157
3158 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003159 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003160
3161 // Everything checks out, sink the shuffle if the user's block doesn't
3162 // already have a copy.
3163 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3164
3165 if (!InsertedShuffle) {
3166 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3167 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3168 SVI->getOperand(1),
3169 SVI->getOperand(2), "", InsertPt);
3170 }
3171
Chandler Carruthcdf47882014-03-09 03:16:01 +00003172 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003173 MadeChange = true;
3174 }
3175
3176 // If we removed all uses, nuke the shuffle.
3177 if (SVI->use_empty()) {
3178 SVI->eraseFromParent();
3179 MadeChange = true;
3180 }
3181
3182 return MadeChange;
3183}
3184
Quentin Colombetc32615d2014-10-31 17:52:53 +00003185namespace {
3186/// \brief Helper class to promote a scalar operation to a vector one.
3187/// This class is used to move downward extractelement transition.
3188/// E.g.,
3189/// a = vector_op <2 x i32>
3190/// b = extractelement <2 x i32> a, i32 0
3191/// c = scalar_op b
3192/// store c
3193///
3194/// =>
3195/// a = vector_op <2 x i32>
3196/// c = vector_op a (equivalent to scalar_op on the related lane)
3197/// * d = extractelement <2 x i32> c, i32 0
3198/// * store d
3199/// Assuming both extractelement and store can be combine, we get rid of the
3200/// transition.
3201class VectorPromoteHelper {
3202 /// Used to perform some checks on the legality of vector operations.
3203 const TargetLowering &TLI;
3204
3205 /// Used to estimated the cost of the promoted chain.
3206 const TargetTransformInfo &TTI;
3207
3208 /// The transition being moved downwards.
3209 Instruction *Transition;
3210 /// The sequence of instructions to be promoted.
3211 SmallVector<Instruction *, 4> InstsToBePromoted;
3212 /// Cost of combining a store and an extract.
3213 unsigned StoreExtractCombineCost;
3214 /// Instruction that will be combined with the transition.
3215 Instruction *CombineInst;
3216
3217 /// \brief The instruction that represents the current end of the transition.
3218 /// Since we are faking the promotion until we reach the end of the chain
3219 /// of computation, we need a way to get the current end of the transition.
3220 Instruction *getEndOfTransition() const {
3221 if (InstsToBePromoted.empty())
3222 return Transition;
3223 return InstsToBePromoted.back();
3224 }
3225
3226 /// \brief Return the index of the original value in the transition.
3227 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3228 /// c, is at index 0.
3229 unsigned getTransitionOriginalValueIdx() const {
3230 assert(isa<ExtractElementInst>(Transition) &&
3231 "Other kind of transitions are not supported yet");
3232 return 0;
3233 }
3234
3235 /// \brief Return the index of the index in the transition.
3236 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3237 /// is at index 1.
3238 unsigned getTransitionIdx() const {
3239 assert(isa<ExtractElementInst>(Transition) &&
3240 "Other kind of transitions are not supported yet");
3241 return 1;
3242 }
3243
3244 /// \brief Get the type of the transition.
3245 /// This is the type of the original value.
3246 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3247 /// transition is <2 x i32>.
3248 Type *getTransitionType() const {
3249 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3250 }
3251
3252 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3253 /// I.e., we have the following sequence:
3254 /// Def = Transition <ty1> a to <ty2>
3255 /// b = ToBePromoted <ty2> Def, ...
3256 /// =>
3257 /// b = ToBePromoted <ty1> a, ...
3258 /// Def = Transition <ty1> ToBePromoted to <ty2>
3259 void promoteImpl(Instruction *ToBePromoted);
3260
3261 /// \brief Check whether or not it is profitable to promote all the
3262 /// instructions enqueued to be promoted.
3263 bool isProfitableToPromote() {
3264 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3265 unsigned Index = isa<ConstantInt>(ValIdx)
3266 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3267 : -1;
3268 Type *PromotedType = getTransitionType();
3269
3270 StoreInst *ST = cast<StoreInst>(CombineInst);
3271 unsigned AS = ST->getPointerAddressSpace();
3272 unsigned Align = ST->getAlignment();
3273 // Check if this store is supported.
3274 if (!TLI.allowsMisalignedMemoryAccesses(
3275 EVT::getEVT(ST->getValueOperand()->getType()), AS, Align)) {
3276 // If this is not supported, there is no way we can combine
3277 // the extract with the store.
3278 return false;
3279 }
3280
3281 // The scalar chain of computation has to pay for the transition
3282 // scalar to vector.
3283 // The vector chain has to account for the combining cost.
3284 uint64_t ScalarCost =
3285 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3286 uint64_t VectorCost = StoreExtractCombineCost;
3287 for (const auto &Inst : InstsToBePromoted) {
3288 // Compute the cost.
3289 // By construction, all instructions being promoted are arithmetic ones.
3290 // Moreover, one argument is a constant that can be viewed as a splat
3291 // constant.
3292 Value *Arg0 = Inst->getOperand(0);
3293 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3294 isa<ConstantFP>(Arg0);
3295 TargetTransformInfo::OperandValueKind Arg0OVK =
3296 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3297 : TargetTransformInfo::OK_AnyValue;
3298 TargetTransformInfo::OperandValueKind Arg1OVK =
3299 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3300 : TargetTransformInfo::OK_AnyValue;
3301 ScalarCost += TTI.getArithmeticInstrCost(
3302 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3303 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3304 Arg0OVK, Arg1OVK);
3305 }
3306 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3307 << ScalarCost << "\nVector: " << VectorCost << '\n');
3308 return ScalarCost > VectorCost;
3309 }
3310
3311 /// \brief Generate a constant vector with \p Val with the same
3312 /// number of elements as the transition.
3313 /// \p UseSplat defines whether or not \p Val should be replicated
3314 /// accross the whole vector.
3315 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3316 /// otherwise we generate a vector with as many undef as possible:
3317 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3318 /// used at the index of the extract.
3319 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3320 unsigned ExtractIdx = UINT_MAX;
3321 if (!UseSplat) {
3322 // If we cannot determine where the constant must be, we have to
3323 // use a splat constant.
3324 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3325 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3326 ExtractIdx = CstVal->getSExtValue();
3327 else
3328 UseSplat = true;
3329 }
3330
3331 unsigned End = getTransitionType()->getVectorNumElements();
3332 if (UseSplat)
3333 return ConstantVector::getSplat(End, Val);
3334
3335 SmallVector<Constant *, 4> ConstVec;
3336 UndefValue *UndefVal = UndefValue::get(Val->getType());
3337 for (unsigned Idx = 0; Idx != End; ++Idx) {
3338 if (Idx == ExtractIdx)
3339 ConstVec.push_back(Val);
3340 else
3341 ConstVec.push_back(UndefVal);
3342 }
3343 return ConstantVector::get(ConstVec);
3344 }
3345
3346 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3347 /// in \p Use can trigger undefined behavior.
3348 static bool canCauseUndefinedBehavior(const Instruction *Use,
3349 unsigned OperandIdx) {
3350 // This is not safe to introduce undef when the operand is on
3351 // the right hand side of a division-like instruction.
3352 if (OperandIdx != 1)
3353 return false;
3354 switch (Use->getOpcode()) {
3355 default:
3356 return false;
3357 case Instruction::SDiv:
3358 case Instruction::UDiv:
3359 case Instruction::SRem:
3360 case Instruction::URem:
3361 return true;
3362 case Instruction::FDiv:
3363 case Instruction::FRem:
3364 return !Use->hasNoNaNs();
3365 }
3366 llvm_unreachable(nullptr);
3367 }
3368
3369public:
3370 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3371 Instruction *Transition, unsigned CombineCost)
3372 : TLI(TLI), TTI(TTI), Transition(Transition),
3373 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3374 assert(Transition && "Do not know how to promote null");
3375 }
3376
3377 /// \brief Check if we can promote \p ToBePromoted to \p Type.
3378 bool canPromote(const Instruction *ToBePromoted) const {
3379 // We could support CastInst too.
3380 return isa<BinaryOperator>(ToBePromoted);
3381 }
3382
3383 /// \brief Check if it is profitable to promote \p ToBePromoted
3384 /// by moving downward the transition through.
3385 bool shouldPromote(const Instruction *ToBePromoted) const {
3386 // Promote only if all the operands can be statically expanded.
3387 // Indeed, we do not want to introduce any new kind of transitions.
3388 for (const Use &U : ToBePromoted->operands()) {
3389 const Value *Val = U.get();
3390 if (Val == getEndOfTransition()) {
3391 // If the use is a division and the transition is on the rhs,
3392 // we cannot promote the operation, otherwise we may create a
3393 // division by zero.
3394 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3395 return false;
3396 continue;
3397 }
3398 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3399 !isa<ConstantFP>(Val))
3400 return false;
3401 }
3402 // Check that the resulting operation is legal.
3403 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3404 if (!ISDOpcode)
3405 return false;
3406 return StressStoreExtract ||
3407 TLI.isOperationLegalOrCustom(ISDOpcode,
3408 EVT::getEVT(getTransitionType(), true));
3409 }
3410
3411 /// \brief Check whether or not \p Use can be combined
3412 /// with the transition.
3413 /// I.e., is it possible to do Use(Transition) => AnotherUse?
3414 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3415
3416 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3417 void enqueueForPromotion(Instruction *ToBePromoted) {
3418 InstsToBePromoted.push_back(ToBePromoted);
3419 }
3420
3421 /// \brief Set the instruction that will be combined with the transition.
3422 void recordCombineInstruction(Instruction *ToBeCombined) {
3423 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3424 CombineInst = ToBeCombined;
3425 }
3426
3427 /// \brief Promote all the instructions enqueued for promotion if it is
3428 /// is profitable.
3429 /// \return True if the promotion happened, false otherwise.
3430 bool promote() {
3431 // Check if there is something to promote.
3432 // Right now, if we do not have anything to combine with,
3433 // we assume the promotion is not profitable.
3434 if (InstsToBePromoted.empty() || !CombineInst)
3435 return false;
3436
3437 // Check cost.
3438 if (!StressStoreExtract && !isProfitableToPromote())
3439 return false;
3440
3441 // Promote.
3442 for (auto &ToBePromoted : InstsToBePromoted)
3443 promoteImpl(ToBePromoted);
3444 InstsToBePromoted.clear();
3445 return true;
3446 }
3447};
3448} // End of anonymous namespace.
3449
3450void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3451 // At this point, we know that all the operands of ToBePromoted but Def
3452 // can be statically promoted.
3453 // For Def, we need to use its parameter in ToBePromoted:
3454 // b = ToBePromoted ty1 a
3455 // Def = Transition ty1 b to ty2
3456 // Move the transition down.
3457 // 1. Replace all uses of the promoted operation by the transition.
3458 // = ... b => = ... Def.
3459 assert(ToBePromoted->getType() == Transition->getType() &&
3460 "The type of the result of the transition does not match "
3461 "the final type");
3462 ToBePromoted->replaceAllUsesWith(Transition);
3463 // 2. Update the type of the uses.
3464 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3465 Type *TransitionTy = getTransitionType();
3466 ToBePromoted->mutateType(TransitionTy);
3467 // 3. Update all the operands of the promoted operation with promoted
3468 // operands.
3469 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3470 for (Use &U : ToBePromoted->operands()) {
3471 Value *Val = U.get();
3472 Value *NewVal = nullptr;
3473 if (Val == Transition)
3474 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3475 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3476 isa<ConstantFP>(Val)) {
3477 // Use a splat constant if it is not safe to use undef.
3478 NewVal = getConstantVector(
3479 cast<Constant>(Val),
3480 isa<UndefValue>(Val) ||
3481 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3482 } else
3483 assert(0 && "Did you modified shouldPromote and forgot to update this?");
3484 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3485 }
3486 Transition->removeFromParent();
3487 Transition->insertAfter(ToBePromoted);
3488 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3489}
3490
3491/// Some targets can do store(extractelement) with one instruction.
3492/// Try to push the extractelement towards the stores when the target
3493/// has this feature and this is profitable.
3494bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
3495 unsigned CombineCost = UINT_MAX;
3496 if (DisableStoreExtract || !TLI ||
3497 (!StressStoreExtract &&
3498 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
3499 Inst->getOperand(1), CombineCost)))
3500 return false;
3501
3502 // At this point we know that Inst is a vector to scalar transition.
3503 // Try to move it down the def-use chain, until:
3504 // - We can combine the transition with its single use
3505 // => we got rid of the transition.
3506 // - We escape the current basic block
3507 // => we would need to check that we are moving it at a cheaper place and
3508 // we do not do that for now.
3509 BasicBlock *Parent = Inst->getParent();
3510 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
3511 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
3512 // If the transition has more than one use, assume this is not going to be
3513 // beneficial.
3514 while (Inst->hasOneUse()) {
3515 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
3516 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
3517
3518 if (ToBePromoted->getParent() != Parent) {
3519 DEBUG(dbgs() << "Instruction to promote is in a different block ("
3520 << ToBePromoted->getParent()->getName()
3521 << ") than the transition (" << Parent->getName() << ").\n");
3522 return false;
3523 }
3524
3525 if (VPH.canCombine(ToBePromoted)) {
3526 DEBUG(dbgs() << "Assume " << *Inst << '\n'
3527 << "will be combined with: " << *ToBePromoted << '\n');
3528 VPH.recordCombineInstruction(ToBePromoted);
3529 bool Changed = VPH.promote();
3530 NumStoreExtractExposed += Changed;
3531 return Changed;
3532 }
3533
3534 DEBUG(dbgs() << "Try promoting.\n");
3535 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
3536 return false;
3537
3538 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
3539
3540 VPH.enqueueForPromotion(ToBePromoted);
3541 Inst = ToBePromoted;
3542 }
3543 return false;
3544}
3545
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003546bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003547 if (PHINode *P = dyn_cast<PHINode>(I)) {
3548 // It is possible for very late stage optimizations (such as SimplifyCFG)
3549 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3550 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00003551 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00003552 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003553 P->replaceAllUsesWith(V);
3554 P->eraseFromParent();
3555 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00003556 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003557 }
Chris Lattneree588de2011-01-15 07:29:01 +00003558 return false;
3559 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003560
Chris Lattneree588de2011-01-15 07:29:01 +00003561 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003562 // If the source of the cast is a constant, then this should have
3563 // already been constant folded. The only reason NOT to constant fold
3564 // it is if something (e.g. LSR) was careful to place the constant
3565 // evaluation in a block other than then one that uses it (e.g. to hoist
3566 // the address of globals out of a loop). If this is the case, we don't
3567 // want to forward-subst the cast.
3568 if (isa<Constant>(CI->getOperand(0)))
3569 return false;
3570
Chris Lattneree588de2011-01-15 07:29:01 +00003571 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3572 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003573
Chris Lattneree588de2011-01-15 07:29:01 +00003574 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00003575 /// Sink a zext or sext into its user blocks if the target type doesn't
3576 /// fit in one register
3577 if (TLI && TLI->getTypeAction(CI->getContext(),
3578 TLI->getValueType(CI->getType())) ==
3579 TargetLowering::TypeExpandInteger) {
3580 return SinkCast(CI);
3581 } else {
3582 bool MadeChange = MoveExtToFormExtLoad(I);
3583 return MadeChange | OptimizeExtUses(I);
3584 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003585 }
Chris Lattneree588de2011-01-15 07:29:01 +00003586 return false;
3587 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003588
Chris Lattneree588de2011-01-15 07:29:01 +00003589 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00003590 if (!TLI || !TLI->hasMultipleConditionRegisters())
3591 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00003592
Chris Lattneree588de2011-01-15 07:29:01 +00003593 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003594 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00003595 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3596 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00003597 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003598
Chris Lattneree588de2011-01-15 07:29:01 +00003599 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003600 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00003601 return OptimizeMemoryInst(I, SI->getOperand(1),
3602 SI->getOperand(0)->getType());
3603 return false;
3604 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003605
Yi Jiangd069f632014-04-21 19:34:27 +00003606 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3607
3608 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3609 BinOp->getOpcode() == Instruction::LShr)) {
3610 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3611 if (TLI && CI && TLI->hasExtractBitsInsn())
3612 return OptimizeExtractBits(BinOp, CI, *TLI);
3613
3614 return false;
3615 }
3616
Chris Lattneree588de2011-01-15 07:29:01 +00003617 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003618 if (GEPI->hasAllZeroIndices()) {
3619 /// The GEP operand must be a pointer, so must its result -> BitCast
3620 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3621 GEPI->getName(), GEPI);
3622 GEPI->replaceAllUsesWith(NC);
3623 GEPI->eraseFromParent();
3624 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003625 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00003626 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003627 }
Chris Lattneree588de2011-01-15 07:29:01 +00003628 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003629 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003630
Chris Lattneree588de2011-01-15 07:29:01 +00003631 if (CallInst *CI = dyn_cast<CallInst>(I))
3632 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003633
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003634 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3635 return OptimizeSelectInst(SI);
3636
Tim Northoveraeb8e062014-02-19 10:02:43 +00003637 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3638 return OptimizeShuffleVectorInst(SVI);
3639
Quentin Colombetc32615d2014-10-31 17:52:53 +00003640 if (isa<ExtractElementInst>(I))
3641 return OptimizeExtractElementInst(I);
3642
Chris Lattneree588de2011-01-15 07:29:01 +00003643 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003644}
3645
Chris Lattnerf2836d12007-03-31 04:06:36 +00003646// In this pass we look for GEP and cast instructions that are used
3647// across basic blocks and rewrite them to improve basic-block-at-a-time
3648// selection.
3649bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00003650 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00003651 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00003652
Chris Lattner7a277142011-01-15 07:14:54 +00003653 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00003654 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00003655 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003656
Benjamin Kramer455fa352012-11-23 19:17:06 +00003657 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3658
Chris Lattnerf2836d12007-03-31 04:06:36 +00003659 return MadeChange;
3660}
Devang Patel53771ba2011-08-18 00:50:51 +00003661
3662// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00003663// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00003664// find a node corresponding to the value.
3665bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3666 bool MadeChange = false;
3667 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
Craig Topperc0196b12014-04-14 00:51:57 +00003668 Instruction *PrevNonDbgInst = nullptr;
Devang Patel53771ba2011-08-18 00:50:51 +00003669 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3670 Instruction *Insn = BI; ++BI;
3671 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00003672 // Leave dbg.values that refer to an alloca alone. These
3673 // instrinsics describe the address of a variable (= the alloca)
3674 // being taken. They should not be moved next to the alloca
3675 // (and to the beginning of the scope), but rather stay close to
3676 // where said address is used.
3677 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00003678 PrevNonDbgInst = Insn;
3679 continue;
3680 }
3681
3682 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3683 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3684 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3685 DVI->removeFromParent();
3686 if (isa<PHINode>(VI))
3687 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3688 else
3689 DVI->insertAfter(VI);
3690 MadeChange = true;
3691 ++NumDbgValueMoved;
3692 }
3693 }
3694 }
3695 return MadeChange;
3696}
Tim Northovercea0abb2014-03-29 08:22:29 +00003697
3698// If there is a sequence that branches based on comparing a single bit
3699// against zero that can be combined into a single instruction, and the
3700// target supports folding these into a single instruction, sink the
3701// mask and compare into the branch uses. Do this before OptimizeBlock ->
3702// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3703// searched for.
3704bool CodeGenPrepare::sinkAndCmp(Function &F) {
3705 if (!EnableAndCmpSinking)
3706 return false;
3707 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3708 return false;
3709 bool MadeChange = false;
3710 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3711 BasicBlock *BB = I++;
3712
3713 // Does this BB end with the following?
3714 // %andVal = and %val, #single-bit-set
3715 // %icmpVal = icmp %andResult, 0
3716 // br i1 %cmpVal label %dest1, label %dest2"
3717 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3718 if (!Brcc || !Brcc->isConditional())
3719 continue;
3720 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3721 if (!Cmp || Cmp->getParent() != BB)
3722 continue;
3723 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3724 if (!Zero || !Zero->isZero())
3725 continue;
3726 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3727 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3728 continue;
3729 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3730 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3731 continue;
3732 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3733
3734 // Push the "and; icmp" for any users that are conditional branches.
3735 // Since there can only be one branch use per BB, we don't need to keep
3736 // track of which BBs we insert into.
3737 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3738 UI != E; ) {
3739 Use &TheUse = *UI;
3740 // Find brcc use.
3741 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3742 ++UI;
3743 if (!BrccUser || !BrccUser->isConditional())
3744 continue;
3745 BasicBlock *UserBB = BrccUser->getParent();
3746 if (UserBB == BB) continue;
3747 DEBUG(dbgs() << "found Brcc use\n");
3748
3749 // Sink the "and; icmp" to use.
3750 MadeChange = true;
3751 BinaryOperator *NewAnd =
3752 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3753 BrccUser);
3754 CmpInst *NewCmp =
3755 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3756 "", BrccUser);
3757 TheUse = NewCmp;
3758 ++NumAndCmpsMoved;
3759 DEBUG(BrccUser->getParent()->dump());
3760 }
3761 }
3762 return MadeChange;
3763}