blob: 8d20848b3e2b5855e1333114d281ec0091de59e1 [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-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 Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Stephen Hines36b56882014-04-23 16:57:46 -070016#include "llvm/CodeGen/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Stephen Hines37ed9c12014-12-01 14:51:49 -080021#include "llvm/Analysis/TargetTransformInfo.h"
Stephen Hines36b56882014-04-23 16:57:46 -070022#include "llvm/IR/CallSite.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
Stephen Hines36b56882014-04-23 16:57:46 -070026#include "llvm/IR/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000027#include "llvm/IR/Function.h"
Stephen Hines36b56882014-04-23 16:57:46 -070028#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth0b8c9a82013-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"
Stephen Hines36b56882014-04-23 16:57:46 -070033#include "llvm/IR/PatternMatch.h"
34#include "llvm/IR/ValueHandle.h"
35#include "llvm/IR/ValueMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000036#include "llvm/Pass.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000037#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000038#include "llvm/Support/Debug.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000040#include "llvm/Target/TargetLibraryInfo.h"
41#include "llvm/Target/TargetLowering.h"
Stephen Hinesdce4a402014-05-29 02:49:00 -070042#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurd2e2efd92012-09-04 18:22:17 +000045#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049
Stephen Hinesdce4a402014-05-29 02:49:00 -070050#define DEBUG_TYPE "codegenprepare"
51
Cameron Zwarich31ff1332011-01-05 17:27:27 +000052STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000053STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-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 Cheng485fafc2011-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 Patelf56ea612011-08-18 00:50:51 +000064STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer59957502012-05-05 12:49:22 +000065STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Stephen Hines36b56882014-04-23 16:57:46 -070066STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Stephen Hines37ed9c12014-12-01 14:51:49 -080067STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000068
Cameron Zwarich899eaa32011-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 Kramer77c4ef82012-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 Kramer59957502012-05-05 12:49:22 +000076
Stephen Hinesdce4a402014-05-29 02:49:00 -070077static cl::opt<bool> AddrSinkUsingGEPs(
78 "addr-sink-using-gep", cl::Hidden, cl::init(false),
79 cl::desc("Address sinking in CGP using GEPs."));
80
Stephen Hines36b56882014-04-23 16:57:46 -070081static cl::opt<bool> EnableAndCmpSinking(
82 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
83 cl::desc("Enable sinkinig and/cmp into branches."));
84
Stephen Hines37ed9c12014-12-01 14:51:49 -080085static 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 Christopher692bf6b2008-09-24 05:32:41 +000093namespace {
Stephen Hines36b56882014-04-23 16:57:46 -070094typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Stephen Hines37ed9c12014-12-01 14:51:49 -080095struct TypeIsSExt {
96 Type *Ty;
97 bool IsSExt;
98 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
99};
100typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Stephen Hines36b56882014-04-23 16:57:46 -0700101
Chris Lattner3e8b6632009-09-02 06:11:42 +0000102 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000103 /// TLI - Keep a pointer of a TargetLowering to consult for determining
104 /// transformation profitability.
Bill Wendlingf9fd58a2013-06-19 21:07:11 +0000105 const TargetMachine *TM;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000106 const TargetLowering *TLI;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800107 const TargetTransformInfo *TTI;
Chad Rosier618c1db2011-12-01 03:08:23 +0000108 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000109 DominatorTree *DT;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000110
Chris Lattner75796092011-01-15 07:14:54 +0000111 /// CurInstIterator - As we scan instructions optimizing them, this is the
112 /// next instruction to optimize. Xforms that can invalidate this should
113 /// update it.
114 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +0000115
Evan Cheng485fafc2011-03-21 01:19:09 +0000116 /// Keeps track of non-local addresses that have been sunk into a block.
117 /// This allows us to avoid inserting duplicate code for blocks with
118 /// multiple load/stores of the same address.
Nick Lewyckyae9f07e2013-05-08 09:00:10 +0000119 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000120
Stephen Hines36b56882014-04-23 16:57:46 -0700121 /// Keeps track of all truncates inserted for the current function.
122 SetOfInstrs InsertedTruncsSet;
123 /// Keeps track of the type of the related instruction before their
124 /// promotion for the current function.
125 InstrToOrigTy PromotedInsts;
126
Devang Patel52e37df2011-03-24 15:35:25 +0000127 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +0000128 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +0000129 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +0000130
Benjamin Kramer59957502012-05-05 12:49:22 +0000131 /// OptSize - True if optimizing for size.
132 bool OptSize;
133
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000134 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000135 static char ID; // Pass identification, replacement for typeid
Stephen Hinesdce4a402014-05-29 02:49:00 -0700136 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Stephen Hines37ed9c12014-12-01 14:51:49 -0800137 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000138 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
139 }
Stephen Hines36b56882014-04-23 16:57:46 -0700140 bool runOnFunction(Function &F) override;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000141
Stephen Hines36b56882014-04-23 16:57:46 -0700142 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Chenga16422f2012-12-21 01:48:14 +0000143
Stephen Hines36b56882014-04-23 16:57:46 -0700144 void getAnalysisUsage(AnalysisUsage &AU) const override {
145 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000146 AU.addRequired<TargetLibraryInfo>();
Stephen Hines37ed9c12014-12-01 14:51:49 -0800147 AU.addRequired<TargetTransformInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000148 }
149
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000150 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000151 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000152 bool EliminateMostlyEmptyBlocks(Function &F);
153 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
154 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000155 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000156 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000157 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000158 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000159 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000160 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000161 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000162 bool OptimizeSelectInst(SelectInst *SI);
Stephen Hines36b56882014-04-23 16:57:46 -0700163 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800164 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000165 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patelf56ea612011-08-18 00:50:51 +0000166 bool PlaceDbgValues(Function &F);
Stephen Hines36b56882014-04-23 16:57:46 -0700167 bool sinkAndCmp(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000168 };
169}
Devang Patel794fd752007-05-01 21:15:47 +0000170
Devang Patel19974732007-05-03 01:11:54 +0000171char CodeGenPrepare::ID = 0;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700172INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
173 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000174
Bill Wendlingf9fd58a2013-06-19 21:07:11 +0000175FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
176 return new CodeGenPrepare(TM);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000177}
178
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000179bool CodeGenPrepare::runOnFunction(Function &F) {
Stephen Hines36b56882014-04-23 16:57:46 -0700180 if (skipOptnoneFunction(F))
181 return false;
182
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000183 bool EverMadeChange = false;
Stephen Hines36b56882014-04-23 16:57:46 -0700184 // Clear per function information.
185 InsertedTruncsSet.clear();
186 PromotedInsts.clear();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000187
Devang Patel52e37df2011-03-24 15:35:25 +0000188 ModifiedDT = false;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800189 if (TM)
190 TLI = TM->getSubtargetImpl()->getTargetLowering();
Chad Rosier618c1db2011-12-01 03:08:23 +0000191 TLInfo = &getAnalysis<TargetLibraryInfo>();
Stephen Hines37ed9c12014-12-01 14:51:49 -0800192 TTI = &getAnalysis<TargetTransformInfo>();
Stephen Hines36b56882014-04-23 16:57:46 -0700193 DominatorTreeWrapperPass *DTWP =
194 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700195 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Bill Wendling831737d2012-12-30 10:32:01 +0000196 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
197 Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000198
Preston Gurd2e2efd92012-09-04 18:22:17 +0000199 /// This optimization identifies DIV instructions that can be
200 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd9a2cfff2013-03-04 18:13:57 +0000201 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd8d662b52012-10-04 21:33:40 +0000202 const DenseMap<unsigned int, unsigned int> &BypassWidths =
203 TLI->getBypassSlowDivWidths();
Evan Cheng911908d2012-09-14 21:25:34 +0000204 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd8d662b52012-10-04 21:33:40 +0000205 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000206 }
207
208 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000209 // unconditional branch.
210 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000211
Devang Patelf56ea612011-08-18 00:50:51 +0000212 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000213 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000214 // find a node corresponding to the value.
215 EverMadeChange |= PlaceDbgValues(F);
216
Stephen Hines36b56882014-04-23 16:57:46 -0700217 // If there is a mask, compare against zero, and branch that can be combined
218 // into a single target instruction, push the mask and compare into branch
219 // users. Do this before OptimizeBlock -> OptimizeInst ->
220 // OptimizeCmpExpression, which perturbs the pattern being searched for.
221 if (!DisableBranchOpts)
222 EverMadeChange |= sinkAndCmp(F);
223
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000224 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000225 while (MadeChange) {
226 MadeChange = false;
Hans Wennborg93ba1332012-09-19 07:48:16 +0000227 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng485fafc2011-03-21 01:19:09 +0000228 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000229 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000230 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000231 EverMadeChange |= MadeChange;
232 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000233
234 SunkAddrs.clear();
235
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000236 if (!DisableBranchOpts) {
237 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000238 SmallPtrSet<BasicBlock*, 8> WorkList;
239 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
240 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000241 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000242 if (!MadeChange) continue;
243
244 for (SmallVectorImpl<BasicBlock*>::iterator
245 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
246 if (pred_begin(*II) == pred_end(*II))
247 WorkList.insert(*II);
248 }
249
Bill Wendlingbf2ad732012-11-28 23:23:48 +0000250 // Delete the dead blocks and any of their dead successors.
Bill Wendling1c211642012-12-06 00:30:20 +0000251 MadeChange |= !WorkList.empty();
Bill Wendlingbf2ad732012-11-28 23:23:48 +0000252 while (!WorkList.empty()) {
253 BasicBlock *BB = *WorkList.begin();
254 WorkList.erase(BB);
255 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
256
257 DeleteDeadBlock(BB);
Stephen Linf7b6f552013-07-15 17:55:02 +0000258
Bill Wendlingbf2ad732012-11-28 23:23:48 +0000259 for (SmallVectorImpl<BasicBlock*>::iterator
260 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
261 if (pred_begin(*II) == pred_end(*II))
262 WorkList.insert(*II);
263 }
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000264
Nadav Rotem3e883732012-08-14 05:19:07 +0000265 // Merge pairs of basic blocks with unconditional branches, connected by
266 // a single edge.
267 if (EverMadeChange || MadeChange)
268 MadeChange |= EliminateFallThrough(F);
269
Evan Cheng485fafc2011-03-21 01:19:09 +0000270 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000271 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000272 EverMadeChange |= MadeChange;
273 }
274
Devang Patel52e37df2011-03-24 15:35:25 +0000275 if (ModifiedDT && DT)
Stephen Hines36b56882014-04-23 16:57:46 -0700276 DT->recalculate(F);
Evan Cheng485fafc2011-03-21 01:19:09 +0000277
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000278 return EverMadeChange;
279}
280
Nadav Rotem3e883732012-08-14 05:19:07 +0000281/// EliminateFallThrough - Merge basic blocks which are connected
282/// by a single edge, where one of the basic blocks has a single successor
283/// pointing to the other basic block, which has a single predecessor.
284bool CodeGenPrepare::EliminateFallThrough(Function &F) {
285 bool Changed = false;
286 // Scan all of the blocks in the function, except for the entry block.
Stephen Hines36b56882014-04-23 16:57:46 -0700287 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem3e883732012-08-14 05:19:07 +0000288 BasicBlock *BB = I++;
289 // If the destination block has a single pred, then this is a trivial
290 // edge, just collapse it.
291 BasicBlock *SinglePred = BB->getSinglePredecessor();
292
Evan Cheng46597072012-09-28 23:58:57 +0000293 // Don't merge if BB's address is taken.
294 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem3e883732012-08-14 05:19:07 +0000295
296 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
297 if (Term && !Term->isConditional()) {
298 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000299 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000300 // Remember if SinglePred was the entry block of the function.
301 // If so, we will need to move BB back to the entry position.
302 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
303 MergeBasicBlockIntoOnlyPred(BB, this);
304
305 if (isEntry && BB != &BB->getParent()->getEntryBlock())
306 BB->moveBefore(&BB->getParent()->getEntryBlock());
307
308 // We have erased a block. Update the iterator.
309 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000310 }
311 }
312 return Changed;
313}
314
Dale Johannesen2d697242009-03-27 01:13:37 +0000315/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
316/// debug info directives, and an unconditional branch. Passes before isel
317/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
318/// isel. Start by eliminating these blocks so we can split them the way we
319/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000320bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
321 bool MadeChange = false;
322 // Note that this intentionally skips the entry block.
Stephen Hines36b56882014-04-23 16:57:46 -0700323 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000324 BasicBlock *BB = I++;
325
326 // If this block doesn't end with an uncond branch, ignore it.
327 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
328 if (!BI || !BI->isUnconditional())
329 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000330
Dale Johannesen2d697242009-03-27 01:13:37 +0000331 // If the instruction before the branch (skipping debug info) isn't a phi
332 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000333 BasicBlock::iterator BBI = BI;
334 if (BBI != BB->begin()) {
335 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000336 while (isa<DbgInfoIntrinsic>(BBI)) {
337 if (BBI == BB->begin())
338 break;
339 --BBI;
340 }
341 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
342 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000343 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000344
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000345 // Do not break infinite loops.
346 BasicBlock *DestBB = BI->getSuccessor(0);
347 if (DestBB == BB)
348 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000349
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000350 if (!CanMergeBlocks(BB, DestBB))
351 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000352
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000353 EliminateMostlyEmptyBlock(BB);
354 MadeChange = true;
355 }
356 return MadeChange;
357}
358
359/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
360/// single uncond branch between them, and BB contains no other non-phi
361/// instructions.
362bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
363 const BasicBlock *DestBB) const {
364 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
365 // the successor. If there are more complex condition (e.g. preheaders),
366 // don't mess around with them.
367 BasicBlock::const_iterator BBI = BB->begin();
368 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Stephen Hines36b56882014-04-23 16:57:46 -0700369 for (const User *U : PN->users()) {
370 const Instruction *UI = cast<Instruction>(U);
371 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000372 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000373 // If User is inside DestBB block and it is a PHINode then check
374 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000375 // a complex condition (e.g. preheaders) we want to avoid here.
Stephen Hines36b56882014-04-23 16:57:46 -0700376 if (UI->getParent() == DestBB) {
377 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Patel75abc1e2007-04-25 00:37:04 +0000378 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
379 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
380 if (Insn && Insn->getParent() == BB &&
381 Insn->getParent() != UPN->getIncomingBlock(I))
382 return false;
383 }
384 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000385 }
386 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000387
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000388 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
389 // and DestBB may have conflicting incoming values for the block. If so, we
390 // can't merge the block.
391 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
392 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000393
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000394 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000395 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000396 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
397 // It is faster to get preds from a PHI than with pred_iterator.
398 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
399 BBPreds.insert(BBPN->getIncomingBlock(i));
400 } else {
401 BBPreds.insert(pred_begin(BB), pred_end(BB));
402 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000403
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000404 // Walk the preds of DestBB.
405 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
406 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
407 if (BBPreds.count(Pred)) { // Common predecessor?
408 BBI = DestBB->begin();
409 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
410 const Value *V1 = PN->getIncomingValueForBlock(Pred);
411 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000412
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000413 // If V2 is a phi node in BB, look up what the mapped value will be.
414 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
415 if (V2PN->getParent() == BB)
416 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000417
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000418 // If there is a conflict, bail out.
419 if (V1 != V2) return false;
420 }
421 }
422 }
423
424 return true;
425}
426
427
428/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
429/// an unconditional branch in it.
430void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
431 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
432 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
David Greene68d67fd2010-01-05 01:27:11 +0000434 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000436 // If the destination block has a single pred, then this is a trivial edge,
437 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000438 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000439 if (SinglePred != DestBB) {
440 // Remember if SinglePred was the entry block of the function. If so, we
441 // will need to move BB back to the entry position.
442 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000443 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000444
Chris Lattnerf5102a02008-11-28 19:54:49 +0000445 if (isEntry && BB != &BB->getParent()->getEntryBlock())
446 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000447
David Greene68d67fd2010-01-05 01:27:11 +0000448 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000449 return;
450 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000451 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000453 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
454 // to handle the new incoming edges it is about to have.
455 PHINode *PN;
456 for (BasicBlock::iterator BBI = DestBB->begin();
457 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
458 // Remove the incoming value for BB, and remember it.
459 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000460
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000461 // Two options: either the InVal is a phi node defined in BB or it is some
462 // value that dominates BB.
463 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
464 if (InValPhi && InValPhi->getParent() == BB) {
465 // Add all of the input values of the input PHI as inputs of this phi.
466 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
467 PN->addIncoming(InValPhi->getIncomingValue(i),
468 InValPhi->getIncomingBlock(i));
469 } else {
470 // Otherwise, add one instance of the dominating value for each edge that
471 // we will be adding.
472 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
473 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
474 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
475 } else {
476 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
477 PN->addIncoming(InVal, *PI);
478 }
479 }
480 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000482 // The PHIs are now updated, change everything that refers to BB to use
483 // DestBB and remove BB.
484 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000485 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000486 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
487 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
488 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
489 DT->changeImmediateDominator(DestBB, NewIDom);
490 DT->eraseNode(BB);
491 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000492 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000493 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
David Greene68d67fd2010-01-05 01:27:11 +0000495 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000496}
497
Stephen Hines36b56882014-04-23 16:57:46 -0700498/// SinkCast - Sink the specified cast instruction into its user blocks
499static bool SinkCast(CastInst *CI) {
500 BasicBlock *DefBB = CI->getParent();
501
502 /// InsertedCasts - Only insert a cast in each block once.
503 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
504
505 bool MadeChange = false;
506 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
507 UI != E; ) {
508 Use &TheUse = UI.getUse();
509 Instruction *User = cast<Instruction>(*UI);
510
511 // Figure out which BB this cast is used in. For PHI's this is the
512 // appropriate predecessor block.
513 BasicBlock *UserBB = User->getParent();
514 if (PHINode *PN = dyn_cast<PHINode>(User)) {
515 UserBB = PN->getIncomingBlock(TheUse);
516 }
517
518 // Preincrement use iterator so we don't invalidate it.
519 ++UI;
520
521 // If this user is in the same block as the cast, don't change the cast.
522 if (UserBB == DefBB) continue;
523
524 // If we have already inserted a cast into this block, use it.
525 CastInst *&InsertedCast = InsertedCasts[UserBB];
526
527 if (!InsertedCast) {
528 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
529 InsertedCast =
530 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
531 InsertPt);
532 MadeChange = true;
533 }
534
535 // Replace a use of the cast with a use of the new cast.
536 TheUse = InsertedCast;
537 ++NumCastUses;
538 }
539
540 // If we removed all uses, nuke the cast.
541 if (CI->use_empty()) {
542 CI->eraseFromParent();
543 MadeChange = true;
544 }
545
546 return MadeChange;
547}
548
Chris Lattnerdd77df32007-04-13 20:30:56 +0000549/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000550/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
551/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000552/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000553///
554/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000555///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000556static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000557 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000558 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
559 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000560
Chris Lattnerdd77df32007-04-13 20:30:56 +0000561 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000562 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000563 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000564
Chris Lattnerdd77df32007-04-13 20:30:56 +0000565 // If this is an extension, it will be a zero or sign extension, which
566 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000567 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000568
Chris Lattnerdd77df32007-04-13 20:30:56 +0000569 // If these values will be promoted, find out what they will be promoted
570 // to. This helps us consider truncates on PPC as noop copies when they
571 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000572 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
573 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000574 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000575 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
576 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000577 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000578
Chris Lattnerdd77df32007-04-13 20:30:56 +0000579 // If, after promotion, these are the same types, this is a noop copy.
580 if (SrcVT != DstVT)
581 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000582
Stephen Hines36b56882014-04-23 16:57:46 -0700583 return SinkCast(CI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000584}
585
Eric Christopher692bf6b2008-09-24 05:32:41 +0000586/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000587/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000588/// a clear win except on targets with multiple condition code registers
589/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000590///
591/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000592static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000593 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000594
Dale Johannesence0b2372007-06-12 16:50:17 +0000595 /// InsertedCmp - Only insert a cmp in each block once.
596 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000597
Dale Johannesence0b2372007-06-12 16:50:17 +0000598 bool MadeChange = false;
Stephen Hines36b56882014-04-23 16:57:46 -0700599 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000600 UI != E; ) {
601 Use &TheUse = UI.getUse();
602 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000603
Dale Johannesence0b2372007-06-12 16:50:17 +0000604 // Preincrement use iterator so we don't invalidate it.
605 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000606
Dale Johannesence0b2372007-06-12 16:50:17 +0000607 // Don't bother for PHI nodes.
608 if (isa<PHINode>(User))
609 continue;
610
611 // Figure out which BB this cmp is used in.
612 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000613
Dale Johannesence0b2372007-06-12 16:50:17 +0000614 // If this user is in the same block as the cmp, don't change the cmp.
615 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000616
Dale Johannesence0b2372007-06-12 16:50:17 +0000617 // If we have already inserted a cmp into this block, use it.
618 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
619
620 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000621 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000622 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000623 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000624 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000625 CI->getOperand(1), "", InsertPt);
626 MadeChange = true;
627 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000628
Dale Johannesence0b2372007-06-12 16:50:17 +0000629 // Replace a use of the cmp with a use of the new cmp.
630 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000631 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000632 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000633
Dale Johannesence0b2372007-06-12 16:50:17 +0000634 // If we removed all uses, nuke the cmp.
635 if (CI->use_empty())
636 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000637
Dale Johannesence0b2372007-06-12 16:50:17 +0000638 return MadeChange;
639}
640
Stephen Hinesdce4a402014-05-29 02:49:00 -0700641/// isExtractBitsCandidateUse - Check if the candidates could
642/// be combined with shift instruction, which includes:
643/// 1. Truncate instruction
644/// 2. And instruction and the imm is a mask of the low bits:
645/// imm & (imm+1) == 0
646static bool isExtractBitsCandidateUse(Instruction *User) {
647 if (!isa<TruncInst>(User)) {
648 if (User->getOpcode() != Instruction::And ||
649 !isa<ConstantInt>(User->getOperand(1)))
650 return false;
651
652 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
653
654 if ((Cimm & (Cimm + 1)).getBoolValue())
655 return false;
656 }
657 return true;
658}
659
660/// SinkShiftAndTruncate - sink both shift and truncate instruction
661/// to the use of truncate's BB.
662static bool
663SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
664 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
665 const TargetLowering &TLI) {
666 BasicBlock *UserBB = User->getParent();
667 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
668 TruncInst *TruncI = dyn_cast<TruncInst>(User);
669 bool MadeChange = false;
670
671 for (Value::user_iterator TruncUI = TruncI->user_begin(),
672 TruncE = TruncI->user_end();
673 TruncUI != TruncE;) {
674
675 Use &TruncTheUse = TruncUI.getUse();
676 Instruction *TruncUser = cast<Instruction>(*TruncUI);
677 // Preincrement use iterator so we don't invalidate it.
678
679 ++TruncUI;
680
681 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
682 if (!ISDOpcode)
683 continue;
684
Stephen Hines37ed9c12014-12-01 14:51:49 -0800685 // If the use is actually a legal node, there will not be an
686 // implicit truncate.
687 // FIXME: always querying the result type is just an
688 // approximation; some nodes' legality is determined by the
689 // operand or other means. There's no good way to find out though.
690 if (TLI.isOperationLegalOrCustom(
691 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700692 continue;
693
694 // Don't bother for PHI nodes.
695 if (isa<PHINode>(TruncUser))
696 continue;
697
698 BasicBlock *TruncUserBB = TruncUser->getParent();
699
700 if (UserBB == TruncUserBB)
701 continue;
702
703 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
704 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
705
706 if (!InsertedShift && !InsertedTrunc) {
707 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
708 // Sink the shift
709 if (ShiftI->getOpcode() == Instruction::AShr)
710 InsertedShift =
711 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
712 else
713 InsertedShift =
714 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
715
716 // Sink the trunc
717 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
718 TruncInsertPt++;
719
720 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
721 TruncI->getType(), "", TruncInsertPt);
722
723 MadeChange = true;
724
725 TruncTheUse = InsertedTrunc;
726 }
727 }
728 return MadeChange;
729}
730
731/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
732/// the uses could potentially be combined with this shift instruction and
733/// generate BitExtract instruction. It will only be applied if the architecture
734/// supports BitExtract instruction. Here is an example:
735/// BB1:
736/// %x.extract.shift = lshr i64 %arg1, 32
737/// BB2:
738/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
739/// ==>
740///
741/// BB2:
742/// %x.extract.shift.1 = lshr i64 %arg1, 32
743/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
744///
745/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
746/// instruction.
747/// Return true if any changes are made.
748static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
749 const TargetLowering &TLI) {
750 BasicBlock *DefBB = ShiftI->getParent();
751
752 /// Only insert instructions in each block once.
753 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
754
755 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
756
757 bool MadeChange = false;
758 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
759 UI != E;) {
760 Use &TheUse = UI.getUse();
761 Instruction *User = cast<Instruction>(*UI);
762 // Preincrement use iterator so we don't invalidate it.
763 ++UI;
764
765 // Don't bother for PHI nodes.
766 if (isa<PHINode>(User))
767 continue;
768
769 if (!isExtractBitsCandidateUse(User))
770 continue;
771
772 BasicBlock *UserBB = User->getParent();
773
774 if (UserBB == DefBB) {
775 // If the shift and truncate instruction are in the same BB. The use of
776 // the truncate(TruncUse) may still introduce another truncate if not
777 // legal. In this case, we would like to sink both shift and truncate
778 // instruction to the BB of TruncUse.
779 // for example:
780 // BB1:
781 // i64 shift.result = lshr i64 opnd, imm
782 // trunc.result = trunc shift.result to i16
783 //
784 // BB2:
785 // ----> We will have an implicit truncate here if the architecture does
786 // not have i16 compare.
787 // cmp i16 trunc.result, opnd2
788 //
789 if (isa<TruncInst>(User) && shiftIsLegal
790 // If the type of the truncate is legal, no trucate will be
791 // introduced in other basic blocks.
792 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
793 MadeChange =
794 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
795
796 continue;
797 }
798 // If we have already inserted a shift into this block, use it.
799 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
800
801 if (!InsertedShift) {
802 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
803
804 if (ShiftI->getOpcode() == Instruction::AShr)
805 InsertedShift =
806 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
807 else
808 InsertedShift =
809 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
810
811 MadeChange = true;
812 }
813
814 // Replace a use of the shift with a use of the new shift.
815 TheUse = InsertedShift;
816 }
817
818 // If we removed all uses, nuke the shift.
819 if (ShiftI->use_empty())
820 ShiftI->eraseFromParent();
821
822 return MadeChange;
823}
824
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000825namespace {
826class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
827protected:
Stephen Hines36b56882014-04-23 16:57:46 -0700828 void replaceCall(Value *With) override {
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000829 CI->replaceAllUsesWith(With);
830 CI->eraseFromParent();
831 }
Stephen Hines36b56882014-04-23 16:57:46 -0700832 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000833 if (ConstantInt *SizeCI =
834 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
835 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000836 return false;
837 }
838};
839} // end anonymous namespace
840
Eric Christopher040056f2010-03-11 02:41:03 +0000841bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000842 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000843
Chris Lattner75796092011-01-15 07:14:54 +0000844 // Lower inline assembly if we can.
845 // If we found an inline asm expession, and if the target knows how to
846 // lower it to normal LLVM code, do so now.
847 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
848 if (TLI->ExpandInlineAsm(CI)) {
849 // Avoid invalidating the iterator.
850 CurInstIterator = BB->begin();
851 // Avoid processing instructions out of order, which could cause
852 // reuse before a value is defined.
853 SunkAddrs.clear();
854 return true;
855 }
856 // Sink address computing for memory operands into the block.
857 if (OptimizeInlineAsmInst(CI))
858 return true;
859 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000860
Eric Christopher040056f2010-03-11 02:41:03 +0000861 // Lower all uses of llvm.objectsize.*
862 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
863 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000864 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000865 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000866 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
867
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000868 // Substituting this can cause recursive simplifications, which can
869 // invalidate our iterator. Use a WeakVH to hold onto it in case this
870 // happens.
871 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000872
Stephen Hinesdce4a402014-05-29 02:49:00 -0700873 replaceAndRecursivelySimplify(CI, RetVal,
874 TLI ? TLI->getDataLayout() : nullptr,
875 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000876
877 // If the iterator instruction was recursively deleted, start over at the
878 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000879 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000880 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000881 SunkAddrs.clear();
882 }
Eric Christopher040056f2010-03-11 02:41:03 +0000883 return true;
884 }
885
Pete Cooperf210b682012-03-13 20:59:56 +0000886 if (II && TLI) {
887 SmallVector<Value*, 2> PtrOps;
888 Type *AccessTy;
889 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
890 while (!PtrOps.empty())
891 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
892 return true;
893 }
894
Eric Christopher040056f2010-03-11 02:41:03 +0000895 // From here on out we're working with named functions.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700896 if (!CI->getCalledFunction()) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000897
Micah Villmow3574eca2012-10-08 16:38:25 +0000898 // We'll need DataLayout from here on out.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700899 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher040056f2010-03-11 02:41:03 +0000900 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000901
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000902 // Lower all default uses of _chk calls. This is very similar
903 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000904 // that have the default "don't know" as the objectsize. Anything else
905 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000906 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000907 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000908}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000909
Evan Cheng485fafc2011-03-21 01:19:09 +0000910/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
911/// instructions to the predecessor to enable tail call optimizations. The
912/// case it is currently looking for is:
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000913/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000914/// bb0:
915/// %tmp0 = tail call i32 @f0()
916/// br label %return
917/// bb1:
918/// %tmp1 = tail call i32 @f1()
919/// br label %return
920/// bb2:
921/// %tmp2 = tail call i32 @f2()
922/// br label %return
923/// return:
924/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
925/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000926/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000927///
928/// =>
929///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000930/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000931/// bb0:
932/// %tmp0 = tail call i32 @f0()
933/// ret i32 %tmp0
934/// bb1:
935/// %tmp1 = tail call i32 @f1()
936/// ret i32 %tmp1
937/// bb2:
938/// %tmp2 = tail call i32 @f2()
939/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000940/// @endcode
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000941bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000942 if (!TLI)
943 return false;
944
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000945 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
946 if (!RI)
947 return false;
948
Stephen Hinesdce4a402014-05-29 02:49:00 -0700949 PHINode *PN = nullptr;
950 BitCastInst *BCI = nullptr;
Evan Cheng485fafc2011-03-21 01:19:09 +0000951 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000952 if (V) {
953 BCI = dyn_cast<BitCastInst>(V);
954 if (BCI)
955 V = BCI->getOperand(0);
956
957 PN = dyn_cast<PHINode>(V);
958 if (!PN)
959 return false;
960 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000961
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000962 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000963 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000964
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000965 // It's not safe to eliminate the sign / zero extension of the return value.
966 // See llvm::isInTailCallPosition().
967 const Function *F = BB->getParent();
Bill Wendling1b0c54f2013-01-18 21:53:16 +0000968 AttributeSet CallerAttrs = F->getAttributes();
969 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
970 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000971 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000972
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000973 // Make sure there are no instructions between the PHI and return, or that the
974 // return is the first instruction in the block.
975 if (PN) {
976 BasicBlock::iterator BI = BB->begin();
977 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000978 if (&*BI == BCI)
979 // Also skip over the bitcast.
980 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000981 if (&*BI != RI)
982 return false;
983 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000984 BasicBlock::iterator BI = BB->begin();
985 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
986 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000987 return false;
988 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000989
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000990 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
991 /// call.
992 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000993 if (PN) {
994 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
995 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
996 // Make sure the phi value is indeed produced by the tail call.
997 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
998 TLI->mayBeEmittedAsTailCall(CI))
999 TailCalls.push_back(CI);
1000 }
1001 } else {
1002 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1003 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001004 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +00001005 continue;
1006
1007 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1008 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1009 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +00001010 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1011 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +00001012 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +00001013
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +00001014 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +00001015 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +00001016 TailCalls.push_back(CI);
1017 }
Evan Cheng485fafc2011-03-21 01:19:09 +00001018 }
1019
Cameron Zwarich4bae5882011-03-24 04:52:07 +00001020 bool Changed = false;
1021 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1022 CallInst *CI = TailCalls[i];
1023 CallSite CS(CI);
1024
1025 // Conservatively require the attributes of the call to match those of the
1026 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling1b0c54f2013-01-18 21:53:16 +00001027 AttributeSet CalleeAttrs = CS.getAttributes();
1028 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling034b94b2012-12-19 07:18:57 +00001029 removeAttribute(Attribute::NoAlias) !=
Bill Wendling1b0c54f2013-01-18 21:53:16 +00001030 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling034b94b2012-12-19 07:18:57 +00001031 removeAttribute(Attribute::NoAlias))
Cameron Zwarich4bae5882011-03-24 04:52:07 +00001032 continue;
1033
1034 // Make sure the call instruction is followed by an unconditional branch to
1035 // the return block.
1036 BasicBlock *CallBB = CI->getParent();
1037 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1038 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1039 continue;
1040
1041 // Duplicate the return into CallBB.
1042 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +00001043 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +00001044 ++NumRetsDup;
1045 }
1046
1047 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng46597072012-09-28 23:58:57 +00001048 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich4bae5882011-03-24 04:52:07 +00001049 BB->eraseFromParent();
1050
1051 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +00001052}
1053
Chris Lattner88a5c832008-11-25 07:09:13 +00001054//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +00001055// Memory Optimization
1056//===----------------------------------------------------------------------===//
1057
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001058namespace {
1059
1060/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1061/// which holds actual Value*'s for register values.
Chandler Carruth56d433d2013-01-07 15:14:13 +00001062struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001063 Value *BaseReg;
1064 Value *ScaledReg;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001065 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001066 void print(raw_ostream &OS) const;
1067 void dump() const;
Stephen Linf7b6f552013-07-15 17:55:02 +00001068
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001069 bool operator==(const ExtAddrMode& O) const {
1070 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1071 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1072 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1073 }
1074};
1075
Eli Friedman5912a122013-09-10 23:09:24 +00001076#ifndef NDEBUG
1077static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1078 AM.print(OS);
1079 return OS;
1080}
1081#endif
1082
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001083void ExtAddrMode::print(raw_ostream &OS) const {
1084 bool NeedPlus = false;
1085 OS << "[";
1086 if (BaseGV) {
1087 OS << (NeedPlus ? " + " : "")
1088 << "GV:";
Stephen Hines36b56882014-04-23 16:57:46 -07001089 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001090 NeedPlus = true;
1091 }
1092
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -07001093 if (BaseOffs) {
1094 OS << (NeedPlus ? " + " : "")
1095 << BaseOffs;
1096 NeedPlus = true;
1097 }
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001098
1099 if (BaseReg) {
1100 OS << (NeedPlus ? " + " : "")
1101 << "Base:";
Stephen Hines36b56882014-04-23 16:57:46 -07001102 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001103 NeedPlus = true;
1104 }
1105 if (Scale) {
1106 OS << (NeedPlus ? " + " : "")
1107 << Scale << "*";
Stephen Hines36b56882014-04-23 16:57:46 -07001108 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001109 }
1110
1111 OS << ']';
1112}
1113
1114#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1115void ExtAddrMode::dump() const {
1116 print(dbgs());
1117 dbgs() << '\n';
1118}
1119#endif
1120
Stephen Hines36b56882014-04-23 16:57:46 -07001121/// \brief This class provides transaction based operation on the IR.
1122/// Every change made through this class is recorded in the internal state and
1123/// can be undone (rollback) until commit is called.
1124class TypePromotionTransaction {
1125
1126 /// \brief This represents the common interface of the individual transaction.
1127 /// Each class implements the logic for doing one specific modification on
1128 /// the IR via the TypePromotionTransaction.
1129 class TypePromotionAction {
1130 protected:
1131 /// The Instruction modified.
1132 Instruction *Inst;
1133
1134 public:
1135 /// \brief Constructor of the action.
1136 /// The constructor performs the related action on the IR.
1137 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1138
1139 virtual ~TypePromotionAction() {}
1140
1141 /// \brief Undo the modification done by this action.
1142 /// When this method is called, the IR must be in the same state as it was
1143 /// before this action was applied.
1144 /// \pre Undoing the action works if and only if the IR is in the exact same
1145 /// state as it was directly after this action was applied.
1146 virtual void undo() = 0;
1147
1148 /// \brief Advocate every change made by this action.
1149 /// When the results on the IR of the action are to be kept, it is important
1150 /// to call this function, otherwise hidden information may be kept forever.
1151 virtual void commit() {
1152 // Nothing to be done, this action is not doing anything.
1153 }
1154 };
1155
1156 /// \brief Utility to remember the position of an instruction.
1157 class InsertionHandler {
1158 /// Position of an instruction.
1159 /// Either an instruction:
1160 /// - Is the first in a basic block: BB is used.
1161 /// - Has a previous instructon: PrevInst is used.
1162 union {
1163 Instruction *PrevInst;
1164 BasicBlock *BB;
1165 } Point;
1166 /// Remember whether or not the instruction had a previous instruction.
1167 bool HasPrevInstruction;
1168
1169 public:
1170 /// \brief Record the position of \p Inst.
1171 InsertionHandler(Instruction *Inst) {
1172 BasicBlock::iterator It = Inst;
1173 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1174 if (HasPrevInstruction)
1175 Point.PrevInst = --It;
1176 else
1177 Point.BB = Inst->getParent();
1178 }
1179
1180 /// \brief Insert \p Inst at the recorded position.
1181 void insert(Instruction *Inst) {
1182 if (HasPrevInstruction) {
1183 if (Inst->getParent())
1184 Inst->removeFromParent();
1185 Inst->insertAfter(Point.PrevInst);
1186 } else {
1187 Instruction *Position = Point.BB->getFirstInsertionPt();
1188 if (Inst->getParent())
1189 Inst->moveBefore(Position);
1190 else
1191 Inst->insertBefore(Position);
1192 }
1193 }
1194 };
1195
1196 /// \brief Move an instruction before another.
1197 class InstructionMoveBefore : public TypePromotionAction {
1198 /// Original position of the instruction.
1199 InsertionHandler Position;
1200
1201 public:
1202 /// \brief Move \p Inst before \p Before.
1203 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1204 : TypePromotionAction(Inst), Position(Inst) {
1205 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1206 Inst->moveBefore(Before);
1207 }
1208
1209 /// \brief Move the instruction back to its original position.
1210 void undo() override {
1211 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1212 Position.insert(Inst);
1213 }
1214 };
1215
1216 /// \brief Set the operand of an instruction with a new value.
1217 class OperandSetter : public TypePromotionAction {
1218 /// Original operand of the instruction.
1219 Value *Origin;
1220 /// Index of the modified instruction.
1221 unsigned Idx;
1222
1223 public:
1224 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1225 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1226 : TypePromotionAction(Inst), Idx(Idx) {
1227 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1228 << "for:" << *Inst << "\n"
1229 << "with:" << *NewVal << "\n");
1230 Origin = Inst->getOperand(Idx);
1231 Inst->setOperand(Idx, NewVal);
1232 }
1233
1234 /// \brief Restore the original value of the instruction.
1235 void undo() override {
1236 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1237 << "for: " << *Inst << "\n"
1238 << "with: " << *Origin << "\n");
1239 Inst->setOperand(Idx, Origin);
1240 }
1241 };
1242
1243 /// \brief Hide the operands of an instruction.
1244 /// Do as if this instruction was not using any of its operands.
1245 class OperandsHider : public TypePromotionAction {
1246 /// The list of original operands.
1247 SmallVector<Value *, 4> OriginalValues;
1248
1249 public:
1250 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1251 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1252 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1253 unsigned NumOpnds = Inst->getNumOperands();
1254 OriginalValues.reserve(NumOpnds);
1255 for (unsigned It = 0; It < NumOpnds; ++It) {
1256 // Save the current operand.
1257 Value *Val = Inst->getOperand(It);
1258 OriginalValues.push_back(Val);
1259 // Set a dummy one.
1260 // We could use OperandSetter here, but that would implied an overhead
1261 // that we are not willing to pay.
1262 Inst->setOperand(It, UndefValue::get(Val->getType()));
1263 }
1264 }
1265
1266 /// \brief Restore the original list of uses.
1267 void undo() override {
1268 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1269 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1270 Inst->setOperand(It, OriginalValues[It]);
1271 }
1272 };
1273
1274 /// \brief Build a truncate instruction.
1275 class TruncBuilder : public TypePromotionAction {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001276 Value *Val;
Stephen Hines36b56882014-04-23 16:57:46 -07001277 public:
1278 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1279 /// result.
1280 /// trunc Opnd to Ty.
1281 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1282 IRBuilder<> Builder(Opnd);
Stephen Hines37ed9c12014-12-01 14:51:49 -08001283 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1284 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Stephen Hines36b56882014-04-23 16:57:46 -07001285 }
1286
Stephen Hines37ed9c12014-12-01 14:51:49 -08001287 /// \brief Get the built value.
1288 Value *getBuiltValue() { return Val; }
Stephen Hines36b56882014-04-23 16:57:46 -07001289
1290 /// \brief Remove the built instruction.
1291 void undo() override {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001292 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1293 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1294 IVal->eraseFromParent();
Stephen Hines36b56882014-04-23 16:57:46 -07001295 }
1296 };
1297
1298 /// \brief Build a sign extension instruction.
1299 class SExtBuilder : public TypePromotionAction {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001300 Value *Val;
Stephen Hines36b56882014-04-23 16:57:46 -07001301 public:
1302 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1303 /// result.
1304 /// sext Opnd to Ty.
1305 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Stephen Hines37ed9c12014-12-01 14:51:49 -08001306 : TypePromotionAction(InsertPt) {
Stephen Hines36b56882014-04-23 16:57:46 -07001307 IRBuilder<> Builder(InsertPt);
Stephen Hines37ed9c12014-12-01 14:51:49 -08001308 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1309 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Stephen Hines36b56882014-04-23 16:57:46 -07001310 }
1311
Stephen Hines37ed9c12014-12-01 14:51:49 -08001312 /// \brief Get the built value.
1313 Value *getBuiltValue() { return Val; }
Stephen Hines36b56882014-04-23 16:57:46 -07001314
1315 /// \brief Remove the built instruction.
1316 void undo() override {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001317 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1318 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1319 IVal->eraseFromParent();
1320 }
1321 };
1322
1323 /// \brief Build a zero extension instruction.
1324 class ZExtBuilder : public TypePromotionAction {
1325 Value *Val;
1326 public:
1327 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1328 /// result.
1329 /// zext Opnd to Ty.
1330 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1331 : TypePromotionAction(InsertPt) {
1332 IRBuilder<> Builder(InsertPt);
1333 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1334 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1335 }
1336
1337 /// \brief Get the built value.
1338 Value *getBuiltValue() { return Val; }
1339
1340 /// \brief Remove the built instruction.
1341 void undo() override {
1342 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1343 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1344 IVal->eraseFromParent();
Stephen Hines36b56882014-04-23 16:57:46 -07001345 }
1346 };
1347
1348 /// \brief Mutate an instruction to another type.
1349 class TypeMutator : public TypePromotionAction {
1350 /// Record the original type.
1351 Type *OrigTy;
1352
1353 public:
1354 /// \brief Mutate the type of \p Inst into \p NewTy.
1355 TypeMutator(Instruction *Inst, Type *NewTy)
1356 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1357 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1358 << "\n");
1359 Inst->mutateType(NewTy);
1360 }
1361
1362 /// \brief Mutate the instruction back to its original type.
1363 void undo() override {
1364 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1365 << "\n");
1366 Inst->mutateType(OrigTy);
1367 }
1368 };
1369
1370 /// \brief Replace the uses of an instruction by another instruction.
1371 class UsesReplacer : public TypePromotionAction {
1372 /// Helper structure to keep track of the replaced uses.
1373 struct InstructionAndIdx {
1374 /// The instruction using the instruction.
1375 Instruction *Inst;
1376 /// The index where this instruction is used for Inst.
1377 unsigned Idx;
1378 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1379 : Inst(Inst), Idx(Idx) {}
1380 };
1381
1382 /// Keep track of the original uses (pair Instruction, Index).
1383 SmallVector<InstructionAndIdx, 4> OriginalUses;
1384 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1385
1386 public:
1387 /// \brief Replace all the use of \p Inst by \p New.
1388 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1389 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1390 << "\n");
1391 // Record the original uses.
1392 for (Use &U : Inst->uses()) {
1393 Instruction *UserI = cast<Instruction>(U.getUser());
1394 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1395 }
1396 // Now, we can replace the uses.
1397 Inst->replaceAllUsesWith(New);
1398 }
1399
1400 /// \brief Reassign the original uses of Inst to Inst.
1401 void undo() override {
1402 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1403 for (use_iterator UseIt = OriginalUses.begin(),
1404 EndIt = OriginalUses.end();
1405 UseIt != EndIt; ++UseIt) {
1406 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1407 }
1408 }
1409 };
1410
1411 /// \brief Remove an instruction from the IR.
1412 class InstructionRemover : public TypePromotionAction {
1413 /// Original position of the instruction.
1414 InsertionHandler Inserter;
1415 /// Helper structure to hide all the link to the instruction. In other
1416 /// words, this helps to do as if the instruction was removed.
1417 OperandsHider Hider;
1418 /// Keep track of the uses replaced, if any.
1419 UsesReplacer *Replacer;
1420
1421 public:
1422 /// \brief Remove all reference of \p Inst and optinally replace all its
1423 /// uses with New.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001424 /// \pre If !Inst->use_empty(), then New != nullptr
1425 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Stephen Hines36b56882014-04-23 16:57:46 -07001426 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Stephen Hinesdce4a402014-05-29 02:49:00 -07001427 Replacer(nullptr) {
Stephen Hines36b56882014-04-23 16:57:46 -07001428 if (New)
1429 Replacer = new UsesReplacer(Inst, New);
1430 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1431 Inst->removeFromParent();
1432 }
1433
1434 ~InstructionRemover() { delete Replacer; }
1435
1436 /// \brief Really remove the instruction.
1437 void commit() override { delete Inst; }
1438
1439 /// \brief Resurrect the instruction and reassign it to the proper uses if
1440 /// new value was provided when build this action.
1441 void undo() override {
1442 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1443 Inserter.insert(Inst);
1444 if (Replacer)
1445 Replacer->undo();
1446 Hider.undo();
1447 }
1448 };
1449
1450public:
1451 /// Restoration point.
1452 /// The restoration point is a pointer to an action instead of an iterator
1453 /// because the iterator may be invalidated but not the pointer.
1454 typedef const TypePromotionAction *ConstRestorationPt;
1455 /// Advocate every changes made in that transaction.
1456 void commit();
1457 /// Undo all the changes made after the given point.
1458 void rollback(ConstRestorationPt Point);
1459 /// Get the current restoration point.
1460 ConstRestorationPt getRestorationPoint() const;
1461
1462 /// \name API for IR modification with state keeping to support rollback.
1463 /// @{
1464 /// Same as Instruction::setOperand.
1465 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1466 /// Same as Instruction::eraseFromParent.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001467 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Stephen Hines36b56882014-04-23 16:57:46 -07001468 /// Same as Value::replaceAllUsesWith.
1469 void replaceAllUsesWith(Instruction *Inst, Value *New);
1470 /// Same as Value::mutateType.
1471 void mutateType(Instruction *Inst, Type *NewTy);
1472 /// Same as IRBuilder::createTrunc.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001473 Value *createTrunc(Instruction *Opnd, Type *Ty);
Stephen Hines36b56882014-04-23 16:57:46 -07001474 /// Same as IRBuilder::createSExt.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001475 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1476 /// Same as IRBuilder::createZExt.
1477 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Stephen Hines36b56882014-04-23 16:57:46 -07001478 /// Same as Instruction::moveBefore.
1479 void moveBefore(Instruction *Inst, Instruction *Before);
1480 /// @}
1481
Stephen Hines36b56882014-04-23 16:57:46 -07001482private:
1483 /// The ordered list of actions made so far.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001484 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1485 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Stephen Hines36b56882014-04-23 16:57:46 -07001486};
1487
1488void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1489 Value *NewVal) {
1490 Actions.push_back(
Stephen Hinesdce4a402014-05-29 02:49:00 -07001491 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Stephen Hines36b56882014-04-23 16:57:46 -07001492}
1493
1494void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1495 Value *NewVal) {
1496 Actions.push_back(
Stephen Hinesdce4a402014-05-29 02:49:00 -07001497 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Stephen Hines36b56882014-04-23 16:57:46 -07001498}
1499
1500void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1501 Value *New) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001502 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Stephen Hines36b56882014-04-23 16:57:46 -07001503}
1504
1505void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001506 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Stephen Hines36b56882014-04-23 16:57:46 -07001507}
1508
Stephen Hines37ed9c12014-12-01 14:51:49 -08001509Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1510 Type *Ty) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001511 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Stephen Hines37ed9c12014-12-01 14:51:49 -08001512 Value *Val = Ptr->getBuiltValue();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001513 Actions.push_back(std::move(Ptr));
Stephen Hines37ed9c12014-12-01 14:51:49 -08001514 return Val;
Stephen Hines36b56882014-04-23 16:57:46 -07001515}
1516
Stephen Hines37ed9c12014-12-01 14:51:49 -08001517Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1518 Value *Opnd, Type *Ty) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001519 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Stephen Hines37ed9c12014-12-01 14:51:49 -08001520 Value *Val = Ptr->getBuiltValue();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001521 Actions.push_back(std::move(Ptr));
Stephen Hines37ed9c12014-12-01 14:51:49 -08001522 return Val;
1523}
1524
1525Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1526 Value *Opnd, Type *Ty) {
1527 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
1528 Value *Val = Ptr->getBuiltValue();
1529 Actions.push_back(std::move(Ptr));
1530 return Val;
Stephen Hines36b56882014-04-23 16:57:46 -07001531}
1532
1533void TypePromotionTransaction::moveBefore(Instruction *Inst,
1534 Instruction *Before) {
1535 Actions.push_back(
Stephen Hinesdce4a402014-05-29 02:49:00 -07001536 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Stephen Hines36b56882014-04-23 16:57:46 -07001537}
1538
1539TypePromotionTransaction::ConstRestorationPt
1540TypePromotionTransaction::getRestorationPoint() const {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001541 return !Actions.empty() ? Actions.back().get() : nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -07001542}
1543
1544void TypePromotionTransaction::commit() {
1545 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001546 ++It)
Stephen Hines36b56882014-04-23 16:57:46 -07001547 (*It)->commit();
Stephen Hines36b56882014-04-23 16:57:46 -07001548 Actions.clear();
1549}
1550
1551void TypePromotionTransaction::rollback(
1552 TypePromotionTransaction::ConstRestorationPt Point) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001553 while (!Actions.empty() && Point != Actions.back().get()) {
1554 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Stephen Hines36b56882014-04-23 16:57:46 -07001555 Curr->undo();
Stephen Hines36b56882014-04-23 16:57:46 -07001556 }
1557}
1558
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001559/// \brief A helper class for matching addressing modes.
1560///
1561/// This encapsulates the logic for matching the target-legal addressing modes.
1562class AddressingModeMatcher {
1563 SmallVectorImpl<Instruction*> &AddrModeInsts;
1564 const TargetLowering &TLI;
1565
1566 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1567 /// the memory instruction that we're computing this address for.
1568 Type *AccessTy;
1569 Instruction *MemoryInst;
Stephen Linf7b6f552013-07-15 17:55:02 +00001570
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001571 /// AddrMode - This is the addressing mode that we're building up. This is
1572 /// part of the return value of this addressing mode matching stuff.
1573 ExtAddrMode &AddrMode;
Stephen Linf7b6f552013-07-15 17:55:02 +00001574
Stephen Hines36b56882014-04-23 16:57:46 -07001575 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1576 const SetOfInstrs &InsertedTruncs;
1577 /// A map from the instructions to their type before promotion.
1578 InstrToOrigTy &PromotedInsts;
1579 /// The ongoing transaction where every action should be registered.
1580 TypePromotionTransaction &TPT;
1581
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001582 /// IgnoreProfitability - This is set to true when we should not do
1583 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1584 /// always returns true.
1585 bool IgnoreProfitability;
Stephen Linf7b6f552013-07-15 17:55:02 +00001586
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001587 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1588 const TargetLowering &T, Type *AT,
Stephen Hines36b56882014-04-23 16:57:46 -07001589 Instruction *MI, ExtAddrMode &AM,
1590 const SetOfInstrs &InsertedTruncs,
1591 InstrToOrigTy &PromotedInsts,
1592 TypePromotionTransaction &TPT)
1593 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1594 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001595 IgnoreProfitability = false;
1596 }
1597public:
Stephen Linf7b6f552013-07-15 17:55:02 +00001598
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001599 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1600 /// give an access type of AccessTy. This returns a list of involved
1601 /// instructions in AddrModeInsts.
Stephen Hines36b56882014-04-23 16:57:46 -07001602 /// \p InsertedTruncs The truncate instruction inserted by other
1603 /// CodeGenPrepare
1604 /// optimizations.
1605 /// \p PromotedInsts maps the instructions to their type before promotion.
1606 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001607 static ExtAddrMode Match(Value *V, Type *AccessTy,
1608 Instruction *MemoryInst,
1609 SmallVectorImpl<Instruction*> &AddrModeInsts,
Stephen Hines36b56882014-04-23 16:57:46 -07001610 const TargetLowering &TLI,
1611 const SetOfInstrs &InsertedTruncs,
1612 InstrToOrigTy &PromotedInsts,
1613 TypePromotionTransaction &TPT) {
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001614 ExtAddrMode Result;
1615
Stephen Hines36b56882014-04-23 16:57:46 -07001616 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1617 MemoryInst, Result, InsertedTruncs,
1618 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001619 (void)Success; assert(Success && "Couldn't select *anything*?");
1620 return Result;
1621 }
1622private:
1623 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1624 bool MatchAddr(Value *V, unsigned Depth);
Stephen Hines36b56882014-04-23 16:57:46 -07001625 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Stephen Hinesdce4a402014-05-29 02:49:00 -07001626 bool *MovedAway = nullptr);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001627 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1628 ExtAddrMode &AMBefore,
1629 ExtAddrMode &AMAfter);
1630 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Stephen Hines36b56882014-04-23 16:57:46 -07001631 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1632 Value *PromotedOperand) const;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001633};
1634
1635/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1636/// Return true and update AddrMode if this addr mode is legal for the target,
1637/// false if not.
1638bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1639 unsigned Depth) {
1640 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1641 // mode. Just process that directly.
1642 if (Scale == 1)
1643 return MatchAddr(ScaleReg, Depth);
Stephen Linf7b6f552013-07-15 17:55:02 +00001644
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001645 // If the scale is 0, it takes nothing to add this.
1646 if (Scale == 0)
1647 return true;
Stephen Linf7b6f552013-07-15 17:55:02 +00001648
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001649 // If we already have a scale of this value, we can add to it, otherwise, we
1650 // need an available scale field.
1651 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1652 return false;
1653
1654 ExtAddrMode TestAddrMode = AddrMode;
1655
1656 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1657 // [A+B + A*7] -> [B+A*8].
1658 TestAddrMode.Scale += Scale;
1659 TestAddrMode.ScaledReg = ScaleReg;
1660
1661 // If the new address isn't legal, bail out.
1662 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1663 return false;
1664
1665 // It was legal, so commit it.
1666 AddrMode = TestAddrMode;
Stephen Linf7b6f552013-07-15 17:55:02 +00001667
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001668 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1669 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1670 // X*Scale + C*Scale to addr mode.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001671 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001672 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1673 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1674 TestAddrMode.ScaledReg = AddLHS;
1675 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Linf7b6f552013-07-15 17:55:02 +00001676
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001677 // If this addressing mode is legal, commit it and remember that we folded
1678 // this instruction.
1679 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1680 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1681 AddrMode = TestAddrMode;
1682 return true;
1683 }
1684 }
1685
1686 // Otherwise, not (x+c)*scale, just return what we have.
1687 return true;
1688}
1689
1690/// MightBeFoldableInst - This is a little filter, which returns true if an
1691/// addressing computation involving I might be folded into a load/store
1692/// accessing it. This doesn't need to be perfect, but needs to accept at least
1693/// the set of instructions that MatchOperationAddr can.
1694static bool MightBeFoldableInst(Instruction *I) {
1695 switch (I->getOpcode()) {
1696 case Instruction::BitCast:
Stephen Hinesdce4a402014-05-29 02:49:00 -07001697 case Instruction::AddrSpaceCast:
Chandler Carruthb1a429f2013-01-05 02:09:22 +00001698 // Don't touch identity bitcasts.
1699 if (I->getType() == I->getOperand(0)->getType())
1700 return false;
1701 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1702 case Instruction::PtrToInt:
1703 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1704 return true;
1705 case Instruction::IntToPtr:
1706 // We know the input is intptr_t, so this is foldable.
1707 return true;
1708 case Instruction::Add:
1709 return true;
1710 case Instruction::Mul:
1711 case Instruction::Shl:
1712 // Can only handle X*C and X << C.
1713 return isa<ConstantInt>(I->getOperand(1));
1714 case Instruction::GetElementPtr:
1715 return true;
1716 default:
1717 return false;
1718 }
1719}
1720
Stephen Hines36b56882014-04-23 16:57:46 -07001721/// \brief Hepler class to perform type promotion.
1722class TypePromotionHelper {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001723 /// \brief Utility function to check whether or not a sign or zero extension
1724 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1725 /// either using the operands of \p Inst or promoting \p Inst.
1726 /// The type of the extension is defined by \p IsSExt.
Stephen Hines36b56882014-04-23 16:57:46 -07001727 /// In other words, check if:
Stephen Hines37ed9c12014-12-01 14:51:49 -08001728 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Stephen Hines36b56882014-04-23 16:57:46 -07001729 /// #1 Promotion applies:
Stephen Hines37ed9c12014-12-01 14:51:49 -08001730 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Stephen Hines36b56882014-04-23 16:57:46 -07001731 /// #2 Operand reuses:
Stephen Hines37ed9c12014-12-01 14:51:49 -08001732 /// ext opnd1 to ConsideredExtType.
Stephen Hines36b56882014-04-23 16:57:46 -07001733 /// \p PromotedInsts maps the instructions to their type before promotion.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001734 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
1735 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Stephen Hines36b56882014-04-23 16:57:46 -07001736
1737 /// \brief Utility function to determine if \p OpIdx should be promoted when
1738 /// promoting \p Inst.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001739 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Stephen Hines36b56882014-04-23 16:57:46 -07001740 if (isa<SelectInst>(Inst) && OpIdx == 0)
1741 return false;
1742 return true;
1743 }
1744
Stephen Hines37ed9c12014-12-01 14:51:49 -08001745 /// \brief Utility function to promote the operand of \p Ext when this
1746 /// operand is a promotable trunc or sext or zext.
Stephen Hines36b56882014-04-23 16:57:46 -07001747 /// \p PromotedInsts maps the instructions to their type before promotion.
1748 /// \p CreatedInsts[out] contains how many non-free instructions have been
Stephen Hines37ed9c12014-12-01 14:51:49 -08001749 /// created to promote the operand of Ext.
Stephen Hines36b56882014-04-23 16:57:46 -07001750 /// Should never be called directly.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001751 /// \return The promoted value which is used instead of Ext.
1752 static Value *promoteOperandForTruncAndAnyExt(Instruction *Ext,
1753 TypePromotionTransaction &TPT,
1754 InstrToOrigTy &PromotedInsts,
1755 unsigned &CreatedInsts);
Stephen Hines36b56882014-04-23 16:57:46 -07001756
Stephen Hines37ed9c12014-12-01 14:51:49 -08001757 /// \brief Utility function to promote the operand of \p Ext when this
Stephen Hines36b56882014-04-23 16:57:46 -07001758 /// operand is promotable and is not a supported trunc or sext.
1759 /// \p PromotedInsts maps the instructions to their type before promotion.
1760 /// \p CreatedInsts[out] contains how many non-free instructions have been
Stephen Hines37ed9c12014-12-01 14:51:49 -08001761 /// created to promote the operand of Ext.
Stephen Hines36b56882014-04-23 16:57:46 -07001762 /// Should never be called directly.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001763 /// \return The promoted value which is used instead of Ext.
1764 static Value *promoteOperandForOther(Instruction *Ext,
Stephen Hines36b56882014-04-23 16:57:46 -07001765 TypePromotionTransaction &TPT,
1766 InstrToOrigTy &PromotedInsts,
Stephen Hines37ed9c12014-12-01 14:51:49 -08001767 unsigned &CreatedInsts, bool IsSExt);
1768
1769 /// \see promoteOperandForOther.
1770 static Value *signExtendOperandForOther(Instruction *Ext,
1771 TypePromotionTransaction &TPT,
1772 InstrToOrigTy &PromotedInsts,
1773 unsigned &CreatedInsts) {
1774 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, true);
1775 }
1776
1777 /// \see promoteOperandForOther.
1778 static Value *zeroExtendOperandForOther(Instruction *Ext,
1779 TypePromotionTransaction &TPT,
1780 InstrToOrigTy &PromotedInsts,
1781 unsigned &CreatedInsts) {
1782 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, false);
1783 }
Stephen Hines36b56882014-04-23 16:57:46 -07001784
1785public:
Stephen Hines37ed9c12014-12-01 14:51:49 -08001786 /// Type for the utility function that promotes the operand of Ext.
1787 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Stephen Hines36b56882014-04-23 16:57:46 -07001788 InstrToOrigTy &PromotedInsts,
1789 unsigned &CreatedInsts);
Stephen Hines37ed9c12014-12-01 14:51:49 -08001790 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
1791 /// action to promote the operand of \p Ext instead of using Ext.
Stephen Hines36b56882014-04-23 16:57:46 -07001792 /// \return NULL if no promotable action is possible with the current
1793 /// sign extension.
1794 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1795 /// the others CodeGenPrepare optimizations. This information is important
1796 /// because we do not want to promote these instructions as CodeGenPrepare
1797 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1798 /// \p PromotedInsts maps the instructions to their type before promotion.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001799 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Stephen Hines36b56882014-04-23 16:57:46 -07001800 const TargetLowering &TLI,
1801 const InstrToOrigTy &PromotedInsts);
1802};
1803
1804bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Stephen Hines37ed9c12014-12-01 14:51:49 -08001805 Type *ConsideredExtType,
1806 const InstrToOrigTy &PromotedInsts,
1807 bool IsSExt) {
1808 // We can always get through zext.
1809 if (isa<ZExtInst>(Inst))
1810 return true;
1811
1812 // sext(sext) is ok too.
1813 if (IsSExt && isa<SExtInst>(Inst))
Stephen Hines36b56882014-04-23 16:57:46 -07001814 return true;
1815
1816 // We can get through binary operator, if it is legal. In other words, the
1817 // binary operator must have a nuw or nsw flag.
1818 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1819 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Stephen Hines37ed9c12014-12-01 14:51:49 -08001820 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
1821 (IsSExt && BinOp->hasNoSignedWrap())))
Stephen Hines36b56882014-04-23 16:57:46 -07001822 return true;
1823
1824 // Check if we can do the following simplification.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001825 // ext(trunc(opnd)) --> ext(opnd)
Stephen Hines36b56882014-04-23 16:57:46 -07001826 if (!isa<TruncInst>(Inst))
1827 return false;
1828
1829 Value *OpndVal = Inst->getOperand(0);
Stephen Hines37ed9c12014-12-01 14:51:49 -08001830 // Check if we can use this operand in the extension.
1831 // If the type is larger than the result type of the extension,
Stephen Hines36b56882014-04-23 16:57:46 -07001832 // we cannot.
1833 if (OpndVal->getType()->getIntegerBitWidth() >
Stephen Hines37ed9c12014-12-01 14:51:49 -08001834 ConsideredExtType->getIntegerBitWidth())
Stephen Hines36b56882014-04-23 16:57:46 -07001835 return false;
1836
1837 // If the operand of the truncate is not an instruction, we will not have
1838 // any information on the dropped bits.
1839 // (Actually we could for constant but it is not worth the extra logic).
1840 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1841 if (!Opnd)
1842 return false;
1843
1844 // Check if the source of the type is narrow enough.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001845 // I.e., check that trunc just drops extended bits of the same kind of
1846 // the extension.
1847 // #1 get the type of the operand and check the kind of the extended bits.
Stephen Hines36b56882014-04-23 16:57:46 -07001848 const Type *OpndType;
1849 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Stephen Hines37ed9c12014-12-01 14:51:49 -08001850 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
1851 OpndType = It->second.Ty;
1852 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
1853 OpndType = Opnd->getOperand(0)->getType();
Stephen Hines36b56882014-04-23 16:57:46 -07001854 else
1855 return false;
1856
Stephen Hines37ed9c12014-12-01 14:51:49 -08001857 // #2 check that the truncate just drop extended bits.
Stephen Hines36b56882014-04-23 16:57:46 -07001858 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1859 return true;
1860
1861 return false;
1862}
1863
1864TypePromotionHelper::Action TypePromotionHelper::getAction(
Stephen Hines37ed9c12014-12-01 14:51:49 -08001865 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
Stephen Hines36b56882014-04-23 16:57:46 -07001866 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001867 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
1868 "Unexpected instruction type");
1869 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
1870 Type *ExtTy = Ext->getType();
1871 bool IsSExt = isa<SExtInst>(Ext);
1872 // If the operand of the extension is not an instruction, we cannot
Stephen Hines36b56882014-04-23 16:57:46 -07001873 // get through.
1874 // If it, check we can get through.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001875 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Stephen Hinesdce4a402014-05-29 02:49:00 -07001876 return nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -07001877
1878 // Do not promote if the operand has been added by codegenprepare.
1879 // Otherwise, it means we are undoing an optimization that is likely to be
1880 // redone, thus causing potential infinite loop.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001881 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
Stephen Hinesdce4a402014-05-29 02:49:00 -07001882 return nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -07001883
1884 // SExt or Trunc instructions.
1885 // Return the related handler.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001886 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
1887 isa<ZExtInst>(ExtOpnd))
1888 return promoteOperandForTruncAndAnyExt;
Stephen Hines36b56882014-04-23 16:57:46 -07001889
1890 // Regular instruction.
1891 // Abort early if we will have to insert non-free instructions.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001892 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Stephen Hinesdce4a402014-05-29 02:49:00 -07001893 return nullptr;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001894 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Stephen Hines36b56882014-04-23 16:57:46 -07001895}
1896
Stephen Hines37ed9c12014-12-01 14:51:49 -08001897Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Stephen Hines36b56882014-04-23 16:57:46 -07001898 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1899 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1900 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1901 // get through it and this method should not be called.
1902 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Stephen Hines37ed9c12014-12-01 14:51:49 -08001903 Value *ExtVal = SExt;
1904 if (isa<ZExtInst>(SExtOpnd)) {
1905 // Replace s|zext(zext(opnd))
1906 // => zext(opnd).
1907 Value *ZExt =
1908 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1909 TPT.replaceAllUsesWith(SExt, ZExt);
1910 TPT.eraseInstruction(SExt);
1911 ExtVal = ZExt;
1912 } else {
1913 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
1914 // => z|sext(opnd).
1915 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1916 }
Stephen Hines36b56882014-04-23 16:57:46 -07001917 CreatedInsts = 0;
1918
1919 // Remove dead code.
1920 if (SExtOpnd->use_empty())
1921 TPT.eraseInstruction(SExtOpnd);
1922
Stephen Hines37ed9c12014-12-01 14:51:49 -08001923 // Check if the extension is still needed.
1924 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1925 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
1926 return ExtVal;
Stephen Hines36b56882014-04-23 16:57:46 -07001927
Stephen Hines37ed9c12014-12-01 14:51:49 -08001928 // At this point we have: ext ty opnd to ty.
1929 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1930 Value *NextVal = ExtInst->getOperand(0);
1931 TPT.eraseInstruction(ExtInst, NextVal);
Stephen Hines36b56882014-04-23 16:57:46 -07001932 return NextVal;
1933}
1934
Stephen Hines37ed9c12014-12-01 14:51:49 -08001935Value *TypePromotionHelper::promoteOperandForOther(
1936 Instruction *Ext, TypePromotionTransaction &TPT,
1937 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts, bool IsSExt) {
1938 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Stephen Hines36b56882014-04-23 16:57:46 -07001939 // get through it and this method should not be called.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001940 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Stephen Hines36b56882014-04-23 16:57:46 -07001941 CreatedInsts = 0;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001942 if (!ExtOpnd->hasOneUse()) {
1943 // ExtOpnd will be promoted.
1944 // All its uses, but Ext, will need to use a truncated value of the
Stephen Hines36b56882014-04-23 16:57:46 -07001945 // promoted version.
1946 // Create the truncate now.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001947 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
1948 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
1949 ITrunc->removeFromParent();
1950 // Insert it just after the definition.
1951 ITrunc->insertAfter(ExtOpnd);
1952 }
Stephen Hines36b56882014-04-23 16:57:46 -07001953
Stephen Hines37ed9c12014-12-01 14:51:49 -08001954 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
1955 // Restore the operand of Ext (which has been replace by the previous call
Stephen Hines36b56882014-04-23 16:57:46 -07001956 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001957 TPT.setOperand(Ext, 0, ExtOpnd);
Stephen Hines36b56882014-04-23 16:57:46 -07001958 }
1959
1960 // Get through the Instruction:
1961 // 1. Update its type.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001962 // 2. Replace the uses of Ext by Inst.
1963 // 3. Extend each operand that needs to be extended.
Stephen Hines36b56882014-04-23 16:57:46 -07001964
1965 // Remember the original type of the instruction before promotion.
1966 // This is useful to know that the high bits are sign extended bits.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001967 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
1968 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Stephen Hines36b56882014-04-23 16:57:46 -07001969 // Step #1.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001970 TPT.mutateType(ExtOpnd, Ext->getType());
Stephen Hines36b56882014-04-23 16:57:46 -07001971 // Step #2.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001972 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Stephen Hines36b56882014-04-23 16:57:46 -07001973 // Step #3.
Stephen Hines37ed9c12014-12-01 14:51:49 -08001974 Instruction *ExtForOpnd = Ext;
Stephen Hines36b56882014-04-23 16:57:46 -07001975
Stephen Hines37ed9c12014-12-01 14:51:49 -08001976 DEBUG(dbgs() << "Propagate Ext to operands\n");
1977 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Stephen Hines36b56882014-04-23 16:57:46 -07001978 ++OpIdx) {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001979 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
1980 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
1981 !shouldExtOperand(ExtOpnd, OpIdx)) {
Stephen Hines36b56882014-04-23 16:57:46 -07001982 DEBUG(dbgs() << "No need to propagate\n");
1983 continue;
1984 }
Stephen Hines37ed9c12014-12-01 14:51:49 -08001985 // Check if we can statically extend the operand.
1986 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Stephen Hines36b56882014-04-23 16:57:46 -07001987 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001988 DEBUG(dbgs() << "Statically extend\n");
1989 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
1990 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
1991 : Cst->getValue().zext(BitWidth);
1992 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Stephen Hines36b56882014-04-23 16:57:46 -07001993 continue;
1994 }
1995 // UndefValue are typed, so we have to statically sign extend them.
1996 if (isa<UndefValue>(Opnd)) {
Stephen Hines37ed9c12014-12-01 14:51:49 -08001997 DEBUG(dbgs() << "Statically extend\n");
1998 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Stephen Hines36b56882014-04-23 16:57:46 -07001999 continue;
2000 }
2001
2002 // Otherwise we have to explicity sign extend the operand.
Stephen Hines37ed9c12014-12-01 14:51:49 -08002003 // Check if Ext was reused to extend an operand.
2004 if (!ExtForOpnd) {
Stephen Hines36b56882014-04-23 16:57:46 -07002005 // If yes, create a new one.
Stephen Hines37ed9c12014-12-01 14:51:49 -08002006 DEBUG(dbgs() << "More operands to ext\n");
2007 ExtForOpnd =
2008 cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2009 : TPT.createZExt(Ext, Opnd, Ext->getType()));
Stephen Hines36b56882014-04-23 16:57:46 -07002010 ++CreatedInsts;
2011 }
2012
Stephen Hines37ed9c12014-12-01 14:51:49 -08002013 TPT.setOperand(ExtForOpnd, 0, Opnd);
Stephen Hines36b56882014-04-23 16:57:46 -07002014
2015 // Move the sign extension before the insertion point.
Stephen Hines37ed9c12014-12-01 14:51:49 -08002016 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2017 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Stephen Hines36b56882014-04-23 16:57:46 -07002018 // If more sext are required, new instructions will have to be created.
Stephen Hines37ed9c12014-12-01 14:51:49 -08002019 ExtForOpnd = nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -07002020 }
Stephen Hines37ed9c12014-12-01 14:51:49 -08002021 if (ExtForOpnd == Ext) {
2022 DEBUG(dbgs() << "Extension is useless now\n");
2023 TPT.eraseInstruction(Ext);
Stephen Hines36b56882014-04-23 16:57:46 -07002024 }
Stephen Hines37ed9c12014-12-01 14:51:49 -08002025 return ExtOpnd;
Stephen Hines36b56882014-04-23 16:57:46 -07002026}
2027
2028/// IsPromotionProfitable - Check whether or not promoting an instruction
2029/// to a wider type was profitable.
2030/// \p MatchedSize gives the number of instructions that have been matched
2031/// in the addressing mode after the promotion was applied.
2032/// \p SizeWithPromotion gives the number of created instructions for
2033/// the promotion plus the number of instructions that have been
2034/// matched in the addressing mode before the promotion.
2035/// \p PromotedOperand is the value that has been promoted.
2036/// \return True if the promotion is profitable, false otherwise.
2037bool
2038AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2039 unsigned SizeWithPromotion,
2040 Value *PromotedOperand) const {
2041 // We folded less instructions than what we created to promote the operand.
2042 // This is not profitable.
2043 if (MatchedSize < SizeWithPromotion)
2044 return false;
2045 if (MatchedSize > SizeWithPromotion)
2046 return true;
2047 // The promotion is neutral but it may help folding the sign extension in
2048 // loads for instance.
2049 // Check that we did not create an illegal instruction.
2050 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2051 if (!PromotedInst)
2052 return false;
2053 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2054 // If the ISDOpcode is undefined, it was undefined before the promotion.
2055 if (!ISDOpcode)
2056 return true;
2057 // Otherwise, check if the promoted instruction is legal or not.
Stephen Hines37ed9c12014-12-01 14:51:49 -08002058 return TLI.isOperationLegalOrCustom(
2059 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
Stephen Hines36b56882014-04-23 16:57:46 -07002060}
2061
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002062/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2063/// fold the operation into the addressing mode. If so, update the addressing
2064/// mode and return true, otherwise return false without modifying AddrMode.
Stephen Hines36b56882014-04-23 16:57:46 -07002065/// If \p MovedAway is not NULL, it contains the information of whether or
2066/// not AddrInst has to be folded into the addressing mode on success.
2067/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2068/// because it has been moved away.
2069/// Thus AddrInst must not be added in the matched instructions.
2070/// This state can happen when AddrInst is a sext, since it may be moved away.
2071/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2072/// not be referenced anymore.
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002073bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Stephen Hines36b56882014-04-23 16:57:46 -07002074 unsigned Depth,
2075 bool *MovedAway) {
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002076 // Avoid exponential behavior on extremely deep expression trees.
2077 if (Depth >= 5) return false;
Stephen Linf7b6f552013-07-15 17:55:02 +00002078
Stephen Hines36b56882014-04-23 16:57:46 -07002079 // By default, all matched instructions stay in place.
2080 if (MovedAway)
2081 *MovedAway = false;
2082
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002083 switch (Opcode) {
2084 case Instruction::PtrToInt:
2085 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2086 return MatchAddr(AddrInst->getOperand(0), Depth);
2087 case Instruction::IntToPtr:
2088 // This inttoptr is a no-op if the integer type is pointer sized.
2089 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenaultce8e4642013-09-06 00:18:43 +00002090 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002091 return MatchAddr(AddrInst->getOperand(0), Depth);
2092 return false;
2093 case Instruction::BitCast:
Stephen Hinesdce4a402014-05-29 02:49:00 -07002094 case Instruction::AddrSpaceCast:
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002095 // BitCast is always a noop, and we can handle it as long as it is
2096 // int->int or pointer->pointer (we don't want int<->fp or something).
2097 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2098 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2099 // Don't touch identity bitcasts. These were probably put here by LSR,
2100 // and we don't want to mess around with them. Assume it knows what it
2101 // is doing.
2102 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2103 return MatchAddr(AddrInst->getOperand(0), Depth);
2104 return false;
2105 case Instruction::Add: {
2106 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2107 ExtAddrMode BackupAddrMode = AddrMode;
2108 unsigned OldSize = AddrModeInsts.size();
Stephen Hines36b56882014-04-23 16:57:46 -07002109 // Start a transaction at this point.
2110 // The LHS may match but not the RHS.
2111 // Therefore, we need a higher level restoration point to undo partially
2112 // matched operation.
2113 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2114 TPT.getRestorationPoint();
2115
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002116 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2117 MatchAddr(AddrInst->getOperand(0), Depth+1))
2118 return true;
Stephen Linf7b6f552013-07-15 17:55:02 +00002119
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002120 // Restore the old addr mode info.
2121 AddrMode = BackupAddrMode;
2122 AddrModeInsts.resize(OldSize);
Stephen Hines36b56882014-04-23 16:57:46 -07002123 TPT.rollback(LastKnownGood);
Stephen Linf7b6f552013-07-15 17:55:02 +00002124
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002125 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2126 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2127 MatchAddr(AddrInst->getOperand(1), Depth+1))
2128 return true;
Stephen Linf7b6f552013-07-15 17:55:02 +00002129
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002130 // Otherwise we definitely can't merge the ADD in.
2131 AddrMode = BackupAddrMode;
2132 AddrModeInsts.resize(OldSize);
Stephen Hines36b56882014-04-23 16:57:46 -07002133 TPT.rollback(LastKnownGood);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002134 break;
2135 }
2136 //case Instruction::Or:
2137 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2138 //break;
2139 case Instruction::Mul:
2140 case Instruction::Shl: {
2141 // Can only handle X*C and X << C.
2142 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Stephen Hines37ed9c12014-12-01 14:51:49 -08002143 if (!RHS)
2144 return false;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002145 int64_t Scale = RHS->getSExtValue();
2146 if (Opcode == Instruction::Shl)
2147 Scale = 1LL << Scale;
Stephen Linf7b6f552013-07-15 17:55:02 +00002148
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002149 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2150 }
2151 case Instruction::GetElementPtr: {
2152 // Scan the GEP. We check it if it contains constant offsets and at most
2153 // one variable offset.
2154 int VariableOperand = -1;
2155 unsigned VariableScale = 0;
Stephen Linf7b6f552013-07-15 17:55:02 +00002156
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002157 int64_t ConstantOffset = 0;
2158 const DataLayout *TD = TLI.getDataLayout();
2159 gep_type_iterator GTI = gep_type_begin(AddrInst);
2160 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2161 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2162 const StructLayout *SL = TD->getStructLayout(STy);
2163 unsigned Idx =
2164 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2165 ConstantOffset += SL->getElementOffset(Idx);
2166 } else {
2167 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2168 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2169 ConstantOffset += CI->getSExtValue()*TypeSize;
2170 } else if (TypeSize) { // Scales of zero don't do anything.
2171 // We only allow one variable index at the moment.
2172 if (VariableOperand != -1)
2173 return false;
Stephen Linf7b6f552013-07-15 17:55:02 +00002174
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002175 // Remember the variable index.
2176 VariableOperand = i;
2177 VariableScale = TypeSize;
2178 }
2179 }
2180 }
Stephen Linf7b6f552013-07-15 17:55:02 +00002181
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002182 // A common case is for the GEP to only do a constant offset. In this case,
2183 // just add it to the disp field and check validity.
2184 if (VariableOperand == -1) {
2185 AddrMode.BaseOffs += ConstantOffset;
2186 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2187 // Check to see if we can fold the base pointer in too.
2188 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2189 return true;
2190 }
2191 AddrMode.BaseOffs -= ConstantOffset;
2192 return false;
2193 }
2194
2195 // Save the valid addressing mode in case we can't match.
2196 ExtAddrMode BackupAddrMode = AddrMode;
2197 unsigned OldSize = AddrModeInsts.size();
2198
2199 // See if the scale and offset amount is valid for this target.
2200 AddrMode.BaseOffs += ConstantOffset;
2201
2202 // Match the base operand of the GEP.
2203 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2204 // If it couldn't be matched, just stuff the value in a register.
2205 if (AddrMode.HasBaseReg) {
2206 AddrMode = BackupAddrMode;
2207 AddrModeInsts.resize(OldSize);
2208 return false;
2209 }
2210 AddrMode.HasBaseReg = true;
2211 AddrMode.BaseReg = AddrInst->getOperand(0);
2212 }
2213
2214 // Match the remaining variable portion of the GEP.
2215 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2216 Depth)) {
2217 // If it couldn't be matched, try stuffing the base into a register
2218 // instead of matching it, and retrying the match of the scale.
2219 AddrMode = BackupAddrMode;
2220 AddrModeInsts.resize(OldSize);
2221 if (AddrMode.HasBaseReg)
2222 return false;
2223 AddrMode.HasBaseReg = true;
2224 AddrMode.BaseReg = AddrInst->getOperand(0);
2225 AddrMode.BaseOffs += ConstantOffset;
2226 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2227 VariableScale, Depth)) {
2228 // If even that didn't work, bail.
2229 AddrMode = BackupAddrMode;
2230 AddrModeInsts.resize(OldSize);
2231 return false;
2232 }
2233 }
2234
2235 return true;
2236 }
Stephen Hines37ed9c12014-12-01 14:51:49 -08002237 case Instruction::SExt:
2238 case Instruction::ZExt: {
2239 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2240 if (!Ext)
2241 return false;
2242
2243 // Try to move this ext out of the way of the addressing mode.
Stephen Hines36b56882014-04-23 16:57:46 -07002244 // Ask for a method for doing so.
Stephen Hines37ed9c12014-12-01 14:51:49 -08002245 TypePromotionHelper::Action TPH =
2246 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
Stephen Hines36b56882014-04-23 16:57:46 -07002247 if (!TPH)
2248 return false;
2249
2250 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2251 TPT.getRestorationPoint();
2252 unsigned CreatedInsts = 0;
Stephen Hines37ed9c12014-12-01 14:51:49 -08002253 Value *PromotedOperand = TPH(Ext, TPT, PromotedInsts, CreatedInsts);
Stephen Hines36b56882014-04-23 16:57:46 -07002254 // SExt has been moved away.
2255 // Thus either it will be rematched later in the recursive calls or it is
2256 // gone. Anyway, we must not fold it into the addressing mode at this point.
2257 // E.g.,
2258 // op = add opnd, 1
Stephen Hines37ed9c12014-12-01 14:51:49 -08002259 // idx = ext op
Stephen Hines36b56882014-04-23 16:57:46 -07002260 // addr = gep base, idx
2261 // is now:
Stephen Hines37ed9c12014-12-01 14:51:49 -08002262 // promotedOpnd = ext opnd <- no match here
Stephen Hines36b56882014-04-23 16:57:46 -07002263 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2264 // addr = gep base, op <- match
2265 if (MovedAway)
2266 *MovedAway = true;
2267
2268 assert(PromotedOperand &&
2269 "TypePromotionHelper should have filtered out those cases");
2270
2271 ExtAddrMode BackupAddrMode = AddrMode;
2272 unsigned OldSize = AddrModeInsts.size();
2273
2274 if (!MatchAddr(PromotedOperand, Depth) ||
2275 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2276 PromotedOperand)) {
2277 AddrMode = BackupAddrMode;
2278 AddrModeInsts.resize(OldSize);
2279 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2280 TPT.rollback(LastKnownGood);
2281 return false;
2282 }
2283 return true;
2284 }
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002285 }
2286 return false;
2287}
2288
2289/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2290/// addressing mode. If Addr can't be added to AddrMode this returns false and
2291/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2292/// or intptr_t for the target.
2293///
2294bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Stephen Hines36b56882014-04-23 16:57:46 -07002295 // Start a transaction at this point that we will rollback if the matching
2296 // fails.
2297 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2298 TPT.getRestorationPoint();
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002299 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2300 // Fold in immediates if legal for the target.
2301 AddrMode.BaseOffs += CI->getSExtValue();
2302 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2303 return true;
2304 AddrMode.BaseOffs -= CI->getSExtValue();
2305 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2306 // If this is a global variable, try to fold it into the addressing mode.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002307 if (!AddrMode.BaseGV) {
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002308 AddrMode.BaseGV = GV;
2309 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2310 return true;
Stephen Hinesdce4a402014-05-29 02:49:00 -07002311 AddrMode.BaseGV = nullptr;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002312 }
2313 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2314 ExtAddrMode BackupAddrMode = AddrMode;
2315 unsigned OldSize = AddrModeInsts.size();
2316
2317 // Check to see if it is possible to fold this operation.
Stephen Hines36b56882014-04-23 16:57:46 -07002318 bool MovedAway = false;
2319 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2320 // This instruction may have been move away. If so, there is nothing
2321 // to check here.
2322 if (MovedAway)
2323 return true;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002324 // Okay, it's possible to fold this. Check to see if it is actually
2325 // *profitable* to do so. We use a simple cost model to avoid increasing
2326 // register pressure too much.
2327 if (I->hasOneUse() ||
2328 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2329 AddrModeInsts.push_back(I);
2330 return true;
2331 }
Stephen Linf7b6f552013-07-15 17:55:02 +00002332
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002333 // It isn't profitable to do this, roll back.
2334 //cerr << "NOT FOLDING: " << *I;
2335 AddrMode = BackupAddrMode;
2336 AddrModeInsts.resize(OldSize);
Stephen Hines36b56882014-04-23 16:57:46 -07002337 TPT.rollback(LastKnownGood);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002338 }
2339 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2340 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2341 return true;
Stephen Hines36b56882014-04-23 16:57:46 -07002342 TPT.rollback(LastKnownGood);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002343 } else if (isa<ConstantPointerNull>(Addr)) {
2344 // Null pointer gets folded without affecting the addressing mode.
2345 return true;
2346 }
2347
2348 // Worse case, the target should support [reg] addressing modes. :)
2349 if (!AddrMode.HasBaseReg) {
2350 AddrMode.HasBaseReg = true;
2351 AddrMode.BaseReg = Addr;
2352 // Still check for legality in case the target supports [imm] but not [i+r].
2353 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2354 return true;
2355 AddrMode.HasBaseReg = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -07002356 AddrMode.BaseReg = nullptr;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002357 }
2358
2359 // If the base register is already taken, see if we can do [r+r].
2360 if (AddrMode.Scale == 0) {
2361 AddrMode.Scale = 1;
2362 AddrMode.ScaledReg = Addr;
2363 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2364 return true;
2365 AddrMode.Scale = 0;
Stephen Hinesdce4a402014-05-29 02:49:00 -07002366 AddrMode.ScaledReg = nullptr;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002367 }
2368 // Couldn't match.
Stephen Hines36b56882014-04-23 16:57:46 -07002369 TPT.rollback(LastKnownGood);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002370 return false;
2371}
2372
2373/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2374/// inline asm call are due to memory operands. If so, return true, otherwise
2375/// return false.
2376static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2377 const TargetLowering &TLI) {
2378 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2379 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2380 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Linf7b6f552013-07-15 17:55:02 +00002381
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002382 // Compute the constraint code and ConstraintType to use.
2383 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2384
2385 // If this asm operand is our Value*, and if it isn't an indirect memory
2386 // operand, we can't fold it!
2387 if (OpInfo.CallOperandVal == OpVal &&
2388 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2389 !OpInfo.isIndirect))
2390 return false;
2391 }
2392
2393 return true;
2394}
2395
2396/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2397/// memory use. If we find an obviously non-foldable instruction, return true.
2398/// Add the ultimately found memory instructions to MemoryUses.
2399static bool FindAllMemoryUses(Instruction *I,
2400 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Stephen Hines37ed9c12014-12-01 14:51:49 -08002401 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002402 const TargetLowering &TLI) {
2403 // If we already considered this instruction, we're done.
Stephen Hines37ed9c12014-12-01 14:51:49 -08002404 if (!ConsideredInsts.insert(I).second)
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002405 return false;
Stephen Linf7b6f552013-07-15 17:55:02 +00002406
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002407 // If this is an obviously unfoldable instruction, bail out.
2408 if (!MightBeFoldableInst(I))
2409 return true;
2410
2411 // Loop over all the uses, recursively processing them.
Stephen Hines36b56882014-04-23 16:57:46 -07002412 for (Use &U : I->uses()) {
2413 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002414
Stephen Hines36b56882014-04-23 16:57:46 -07002415 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2416 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002417 continue;
2418 }
Stephen Linf7b6f552013-07-15 17:55:02 +00002419
Stephen Hines36b56882014-04-23 16:57:46 -07002420 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2421 unsigned opNo = U.getOperandNo();
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002422 if (opNo == 0) return true; // Storing addr, not into addr.
2423 MemoryUses.push_back(std::make_pair(SI, opNo));
2424 continue;
2425 }
Stephen Linf7b6f552013-07-15 17:55:02 +00002426
Stephen Hines36b56882014-04-23 16:57:46 -07002427 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002428 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2429 if (!IA) return true;
Stephen Linf7b6f552013-07-15 17:55:02 +00002430
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002431 // If this is a memory operand, we're cool, otherwise bail out.
2432 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2433 return true;
2434 continue;
2435 }
Stephen Linf7b6f552013-07-15 17:55:02 +00002436
Stephen Hines36b56882014-04-23 16:57:46 -07002437 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002438 return true;
2439 }
2440
2441 return false;
2442}
2443
2444/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2445/// the use site that we're folding it into. If so, there is no cost to
2446/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2447/// that we know are live at the instruction already.
2448bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2449 Value *KnownLive2) {
2450 // If Val is either of the known-live values, we know it is live!
Stephen Hinesdce4a402014-05-29 02:49:00 -07002451 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002452 return true;
Stephen Linf7b6f552013-07-15 17:55:02 +00002453
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002454 // All values other than instructions and arguments (e.g. constants) are live.
2455 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Linf7b6f552013-07-15 17:55:02 +00002456
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002457 // If Val is a constant sized alloca in the entry block, it is live, this is
2458 // true because it is just a reference to the stack/frame pointer, which is
2459 // live for the whole function.
2460 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2461 if (AI->isStaticAlloca())
2462 return true;
Stephen Linf7b6f552013-07-15 17:55:02 +00002463
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002464 // Check to see if this value is already used in the memory instruction's
2465 // block. If so, it's already live into the block at the very least, so we
2466 // can reasonably fold it.
2467 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2468}
2469
2470/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2471/// mode of the machine to fold the specified instruction into a load or store
2472/// that ultimately uses it. However, the specified instruction has multiple
2473/// uses. Given this, it may actually increase register pressure to fold it
2474/// into the load. For example, consider this code:
2475///
2476/// X = ...
2477/// Y = X+1
2478/// use(Y) -> nonload/store
2479/// Z = Y+1
2480/// load Z
2481///
2482/// In this case, Y has multiple uses, and can be folded into the load of Z
2483/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2484/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2485/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2486/// number of computations either.
2487///
2488/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2489/// X was live across 'load Z' for other reasons, we actually *would* want to
2490/// fold the addressing mode in the Z case. This would make Y die earlier.
2491bool AddressingModeMatcher::
2492IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2493 ExtAddrMode &AMAfter) {
2494 if (IgnoreProfitability) return true;
Stephen Linf7b6f552013-07-15 17:55:02 +00002495
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002496 // AMBefore is the addressing mode before this instruction was folded into it,
2497 // and AMAfter is the addressing mode after the instruction was folded. Get
2498 // the set of registers referenced by AMAfter and subtract out those
2499 // referenced by AMBefore: this is the set of values which folding in this
2500 // address extends the lifetime of.
2501 //
2502 // Note that there are only two potential values being referenced here,
2503 // BaseReg and ScaleReg (global addresses are always available, as are any
2504 // folded immediates).
2505 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Linf7b6f552013-07-15 17:55:02 +00002506
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002507 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2508 // lifetime wasn't extended by adding this instruction.
2509 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Stephen Hinesdce4a402014-05-29 02:49:00 -07002510 BaseReg = nullptr;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002511 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Stephen Hinesdce4a402014-05-29 02:49:00 -07002512 ScaledReg = nullptr;
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002513
2514 // If folding this instruction (and it's subexprs) didn't extend any live
2515 // ranges, we're ok with it.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002516 if (!BaseReg && !ScaledReg)
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002517 return true;
2518
2519 // If all uses of this instruction are ultimately load/store/inlineasm's,
2520 // check to see if their addressing modes will include this instruction. If
2521 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2522 // uses.
2523 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2524 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2525 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2526 return false; // Has a non-memory, non-foldable use!
Stephen Linf7b6f552013-07-15 17:55:02 +00002527
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002528 // Now that we know that all uses of this instruction are part of a chain of
2529 // computation involving only operations that could theoretically be folded
2530 // into a memory use, loop over each of these uses and see if they could
2531 // *actually* fold the instruction.
2532 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2533 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2534 Instruction *User = MemoryUses[i].first;
2535 unsigned OpNo = MemoryUses[i].second;
Stephen Linf7b6f552013-07-15 17:55:02 +00002536
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002537 // Get the access type of this use. If the use isn't a pointer, we don't
2538 // know what it accesses.
2539 Value *Address = User->getOperand(OpNo);
2540 if (!Address->getType()->isPointerTy())
2541 return false;
Matt Arsenault4598bd52013-09-06 00:37:24 +00002542 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Linf7b6f552013-07-15 17:55:02 +00002543
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002544 // Do a match against the root of this address, ignoring profitability. This
2545 // will tell us if the addressing mode for the memory operation will
2546 // *actually* cover the shared instruction.
2547 ExtAddrMode Result;
Stephen Hines36b56882014-04-23 16:57:46 -07002548 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2549 TPT.getRestorationPoint();
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002550 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Stephen Hines36b56882014-04-23 16:57:46 -07002551 MemoryInst, Result, InsertedTruncs,
2552 PromotedInsts, TPT);
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002553 Matcher.IgnoreProfitability = true;
2554 bool Success = Matcher.MatchAddr(Address, 0);
2555 (void)Success; assert(Success && "Couldn't select *anything*?");
2556
Stephen Hines36b56882014-04-23 16:57:46 -07002557 // The match was to check the profitability, the changes made are not
2558 // part of the original matcher. Therefore, they should be dropped
2559 // otherwise the original matcher will not present the right state.
2560 TPT.rollback(LastKnownGood);
2561
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002562 // If the match didn't cover I, then it won't be shared by it.
2563 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2564 I) == MatchedAddrModeInsts.end())
2565 return false;
Stephen Linf7b6f552013-07-15 17:55:02 +00002566
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002567 MatchedAddrModeInsts.clear();
2568 }
Stephen Linf7b6f552013-07-15 17:55:02 +00002569
Chandler Carruthb1a429f2013-01-05 02:09:22 +00002570 return true;
2571}
2572
2573} // end anonymous namespace
2574
Chris Lattnerdd77df32007-04-13 20:30:56 +00002575/// IsNonLocalValue - Return true if the specified values are defined in a
2576/// different basic block than BB.
2577static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2578 if (Instruction *I = dyn_cast<Instruction>(V))
2579 return I->getParent() != BB;
2580 return false;
2581}
2582
Bob Wilson4a8ee232009-12-03 21:47:07 +00002583/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +00002584/// addressing modes that can do significant amounts of computation. As such,
2585/// instruction selection will try to get the load or store to do as much
2586/// computation as possible for the program. The problem is that isel can only
2587/// see within a single block. As such, we sink as much legal addressing mode
2588/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +00002589///
2590/// This method is used to optimize both load/store and inline asms with memory
2591/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +00002592bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002593 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +00002594 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +00002595
2596 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +00002597 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +00002598 SmallVector<Value*, 8> worklist;
2599 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +00002600 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +00002601
Owen Anderson35bf4d62010-11-27 08:15:55 +00002602 // Use a worklist to iteratively look through PHI nodes, and ensure that
2603 // the addressing mode obtained from the non-PHI roots of the graph
2604 // are equivalent.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002605 Value *Consensus = nullptr;
Cameron Zwarich4c078f02011-03-01 21:13:53 +00002606 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +00002607 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +00002608 SmallVector<Instruction*, 16> AddrModeInsts;
2609 ExtAddrMode AddrMode;
Stephen Hines36b56882014-04-23 16:57:46 -07002610 TypePromotionTransaction TPT;
2611 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2612 TPT.getRestorationPoint();
Owen Anderson35bf4d62010-11-27 08:15:55 +00002613 while (!worklist.empty()) {
2614 Value *V = worklist.back();
2615 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +00002616
Owen Anderson35bf4d62010-11-27 08:15:55 +00002617 // Break use-def graph loops.
Stephen Hines37ed9c12014-12-01 14:51:49 -08002618 if (!Visited.insert(V).second) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07002619 Consensus = nullptr;
Owen Anderson35bf4d62010-11-27 08:15:55 +00002620 break;
Owen Andersond2f41742010-11-19 22:15:03 +00002621 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00002622
Owen Anderson35bf4d62010-11-27 08:15:55 +00002623 // For a PHI node, push all of its incoming values.
2624 if (PHINode *P = dyn_cast<PHINode>(V)) {
2625 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2626 worklist.push_back(P->getIncomingValue(i));
2627 continue;
2628 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00002629
Owen Anderson35bf4d62010-11-27 08:15:55 +00002630 // For non-PHIs, determine the addressing mode being computed.
2631 SmallVector<Instruction*, 16> NewAddrModeInsts;
Stephen Hines36b56882014-04-23 16:57:46 -07002632 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2633 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2634 PromotedInsts, TPT);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +00002635
2636 // This check is broken into two cases with very similar code to avoid using
2637 // getNumUses() as much as possible. Some values have a lot of uses, so
2638 // calling getNumUses() unconditionally caused a significant compile-time
2639 // regression.
2640 if (!Consensus) {
2641 Consensus = V;
2642 AddrMode = NewAddrMode;
2643 AddrModeInsts = NewAddrModeInsts;
2644 continue;
2645 } else if (NewAddrMode == AddrMode) {
2646 if (!IsNumUsesConsensusValid) {
2647 NumUsesConsensus = Consensus->getNumUses();
2648 IsNumUsesConsensusValid = true;
2649 }
2650
2651 // Ensure that the obtained addressing mode is equivalent to that obtained
2652 // for all other roots of the PHI traversal. Also, when choosing one
2653 // such root as representative, select the one with the most uses in order
2654 // to keep the cost modeling heuristics in AddressingModeMatcher
2655 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +00002656 unsigned NumUses = V->getNumUses();
2657 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +00002658 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +00002659 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +00002660 AddrModeInsts = NewAddrModeInsts;
2661 }
2662 continue;
2663 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00002664
Stephen Hinesdce4a402014-05-29 02:49:00 -07002665 Consensus = nullptr;
Owen Anderson35bf4d62010-11-27 08:15:55 +00002666 break;
Owen Andersond2f41742010-11-19 22:15:03 +00002667 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00002668
Owen Anderson35bf4d62010-11-27 08:15:55 +00002669 // If the addressing mode couldn't be determined, or if multiple different
2670 // ones were determined, bail out now.
Stephen Hines36b56882014-04-23 16:57:46 -07002671 if (!Consensus) {
2672 TPT.rollback(LastKnownGood);
2673 return false;
2674 }
2675 TPT.commit();
Nadav Rotema94d6e82012-07-24 10:51:42 +00002676
Chris Lattnerdd77df32007-04-13 20:30:56 +00002677 // Check to see if any of the instructions supersumed by this addr mode are
2678 // non-local to I's BB.
2679 bool AnyNonLocal = false;
2680 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +00002681 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00002682 AnyNonLocal = true;
2683 break;
2684 }
2685 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00002686
Chris Lattnerdd77df32007-04-13 20:30:56 +00002687 // If all the instructions matched are already in this BB, don't do anything.
2688 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +00002689 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002690 return false;
2691 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00002692
Chris Lattnerdd77df32007-04-13 20:30:56 +00002693 // Insert this computation right after this user. Since our caller is
2694 // scanning from the top of the BB to the bottom, reuse of the expr are
2695 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +00002696 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +00002697
Chris Lattnerdd77df32007-04-13 20:30:56 +00002698 // Now that we determined the addressing expression we want to use and know
2699 // that we have to sink it into this block. Check to see if we have already
2700 // done this for some other load/store instr in this block. If so, reuse the
2701 // computation.
2702 Value *&SunkAddr = SunkAddrs[Addr];
2703 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +00002704 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Stephen Hinesdce4a402014-05-29 02:49:00 -07002705 << *MemoryInst << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002706 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +00002707 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Stephen Hinesdce4a402014-05-29 02:49:00 -07002708 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2709 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2710 // By default, we use the GEP-based method when AA is used later. This
2711 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2712 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2713 << *MemoryInst << "\n");
2714 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2715 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
2716
2717 // First, find the pointer.
2718 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2719 ResultPtr = AddrMode.BaseReg;
2720 AddrMode.BaseReg = nullptr;
2721 }
2722
2723 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2724 // We can't add more than one pointer together, nor can we scale a
2725 // pointer (both of which seem meaningless).
2726 if (ResultPtr || AddrMode.Scale != 1)
2727 return false;
2728
2729 ResultPtr = AddrMode.ScaledReg;
2730 AddrMode.Scale = 0;
2731 }
2732
2733 if (AddrMode.BaseGV) {
2734 if (ResultPtr)
2735 return false;
2736
2737 ResultPtr = AddrMode.BaseGV;
2738 }
2739
2740 // If the real base value actually came from an inttoptr, then the matcher
2741 // will look through it and provide only the integer value. In that case,
2742 // use it here.
2743 if (!ResultPtr && AddrMode.BaseReg) {
2744 ResultPtr =
2745 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2746 AddrMode.BaseReg = nullptr;
2747 } else if (!ResultPtr && AddrMode.Scale == 1) {
2748 ResultPtr =
2749 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2750 AddrMode.Scale = 0;
2751 }
2752
2753 if (!ResultPtr &&
2754 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2755 SunkAddr = Constant::getNullValue(Addr->getType());
2756 } else if (!ResultPtr) {
2757 return false;
2758 } else {
2759 Type *I8PtrTy =
2760 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2761
2762 // Start with the base register. Do this first so that subsequent address
2763 // matching finds it last, which will prevent it from trying to match it
2764 // as the scaled value in case it happens to be a mul. That would be
2765 // problematic if we've sunk a different mul for the scale, because then
2766 // we'd end up sinking both muls.
2767 if (AddrMode.BaseReg) {
2768 Value *V = AddrMode.BaseReg;
2769 if (V->getType() != IntPtrTy)
2770 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2771
2772 ResultIndex = V;
2773 }
2774
2775 // Add the scale value.
2776 if (AddrMode.Scale) {
2777 Value *V = AddrMode.ScaledReg;
2778 if (V->getType() == IntPtrTy) {
2779 // done.
2780 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2781 cast<IntegerType>(V->getType())->getBitWidth()) {
2782 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2783 } else {
2784 // It is only safe to sign extend the BaseReg if we know that the math
2785 // required to create it did not overflow before we extend it. Since
2786 // the original IR value was tossed in favor of a constant back when
2787 // the AddrMode was created we need to bail out gracefully if widths
2788 // do not match instead of extending it.
2789 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2790 if (I && (ResultIndex != AddrMode.BaseReg))
2791 I->eraseFromParent();
2792 return false;
2793 }
2794
2795 if (AddrMode.Scale != 1)
2796 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2797 "sunkaddr");
2798 if (ResultIndex)
2799 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2800 else
2801 ResultIndex = V;
2802 }
2803
2804 // Add in the Base Offset if present.
2805 if (AddrMode.BaseOffs) {
2806 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2807 if (ResultIndex) {
Stephen Hines37ed9c12014-12-01 14:51:49 -08002808 // We need to add this separately from the scale above to help with
2809 // SDAG consecutive load/store merging.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002810 if (ResultPtr->getType() != I8PtrTy)
2811 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2812 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2813 }
2814
2815 ResultIndex = V;
2816 }
2817
2818 if (!ResultIndex) {
2819 SunkAddr = ResultPtr;
2820 } else {
2821 if (ResultPtr->getType() != I8PtrTy)
2822 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2823 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2824 }
2825
2826 if (SunkAddr->getType() != Addr->getType())
2827 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2828 }
Chris Lattnerdd77df32007-04-13 20:30:56 +00002829 } else {
David Greene68d67fd2010-01-05 01:27:11 +00002830 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Stephen Hinesdce4a402014-05-29 02:49:00 -07002831 << *MemoryInst << "\n");
Matt Arsenaultce8e4642013-09-06 00:18:43 +00002832 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Stephen Hinesdce4a402014-05-29 02:49:00 -07002833 Value *Result = nullptr;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +00002834
2835 // Start with the base register. Do this first so that subsequent address
2836 // matching finds it last, which will prevent it from trying to match it
2837 // as the scaled value in case it happens to be a mul. That would be
2838 // problematic if we've sunk a different mul for the scale, because then
2839 // we'd end up sinking both muls.
2840 if (AddrMode.BaseReg) {
2841 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +00002842 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +00002843 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +00002844 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +00002845 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +00002846 Result = V;
2847 }
2848
2849 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +00002850 if (AddrMode.Scale) {
2851 Value *V = AddrMode.ScaledReg;
2852 if (V->getType() == IntPtrTy) {
2853 // done.
Duncan Sands1df98592010-02-16 11:11:14 +00002854 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +00002855 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002856 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2857 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +00002858 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002859 } else {
Stephen Hines36b56882014-04-23 16:57:46 -07002860 // It is only safe to sign extend the BaseReg if we know that the math
2861 // required to create it did not overflow before we extend it. Since
2862 // the original IR value was tossed in favor of a constant back when
2863 // the AddrMode was created we need to bail out gracefully if widths
2864 // do not match instead of extending it.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002865 Instruction *I = dyn_cast_or_null<Instruction>(Result);
2866 if (I && (Result != AddrMode.BaseReg))
2867 I->eraseFromParent();
Stephen Hines36b56882014-04-23 16:57:46 -07002868 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +00002869 }
2870 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +00002871 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2872 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002873 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +00002874 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002875 else
2876 Result = V;
2877 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00002878
Chris Lattnerdd77df32007-04-13 20:30:56 +00002879 // Add in the BaseGV if present.
2880 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +00002881 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002882 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +00002883 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002884 else
2885 Result = V;
2886 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00002887
Chris Lattnerdd77df32007-04-13 20:30:56 +00002888 // Add in the Base Offset if present.
2889 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002890 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00002891 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +00002892 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002893 else
2894 Result = V;
2895 }
2896
Stephen Hinesdce4a402014-05-29 02:49:00 -07002897 if (!Result)
Owen Andersona7235ea2009-07-31 20:28:14 +00002898 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +00002899 else
Devang Patel2048c372011-09-06 18:49:53 +00002900 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00002901 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00002902
Owen Andersond2f41742010-11-19 22:15:03 +00002903 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00002904
Chris Lattner0403b472011-04-09 07:05:44 +00002905 // If we have no uses, recursively delete the value and all dead instructions
2906 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +00002907 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +00002908 // This can cause recursive deletion, which can invalidate our iterator.
2909 // Use a WeakVH to hold onto it in case this happens.
2910 WeakVH IterHandle(CurInstIterator);
2911 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00002912
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00002913 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00002914
2915 if (IterHandle != CurInstIterator) {
2916 // If the iterator instruction was recursively deleted, start over at the
2917 // start of the block.
2918 CurInstIterator = BB->begin();
2919 SunkAddrs.clear();
Nadav Rotema94d6e82012-07-24 10:51:42 +00002920 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00002921 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00002922 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00002923 return true;
2924}
2925
Evan Cheng9bf12b52008-02-26 02:42:37 +00002926/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00002927/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00002928/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00002929bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00002930 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00002931
Nadav Rotema94d6e82012-07-24 10:51:42 +00002932 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00002933 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00002934 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00002935 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2936 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00002937
Evan Cheng9bf12b52008-02-26 02:42:37 +00002938 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00002939 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00002940
Eli Friedman9ec80952008-02-26 18:37:49 +00002941 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2942 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00002943 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00002944 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00002945 } else if (OpInfo.Type == InlineAsm::isInput)
2946 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00002947 }
2948
2949 return MadeChange;
2950}
2951
Dan Gohmanb00f2362009-10-16 20:59:35 +00002952/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2953/// basic block as the load, unless conditions are unfavorable. This allows
2954/// SelectionDAG to fold the extend into the load.
2955///
2956bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2957 // Look for a load being extended.
2958 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2959 if (!LI) return false;
2960
2961 // If they're already in the same block, there's nothing to do.
2962 if (LI->getParent() == I->getParent())
2963 return false;
2964
2965 // If the load has other users and the truncate is not free, this probably
2966 // isn't worthwhile.
2967 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00002968 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2969 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00002970 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00002971 return false;
2972
2973 // Check whether the target supports casts folded into loads.
2974 unsigned LType;
2975 if (isa<ZExtInst>(I))
2976 LType = ISD::ZEXTLOAD;
2977 else {
2978 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2979 LType = ISD::SEXTLOAD;
2980 }
Patrik Hagglund34525f92012-12-11 11:14:33 +00002981 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohmanb00f2362009-10-16 20:59:35 +00002982 return false;
2983
2984 // Move the extend into the same block as the load, so that SelectionDAG
2985 // can fold it.
2986 I->removeFromParent();
2987 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00002988 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00002989 return true;
2990}
2991
Evan Chengbdcb7262007-12-05 23:58:20 +00002992bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2993 BasicBlock *DefBB = I->getParent();
2994
Bob Wilson9120f5c2010-09-21 21:44:14 +00002995 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00002996 // other uses of the source with result of extension.
2997 Value *Src = I->getOperand(0);
2998 if (Src->hasOneUse())
2999 return false;
3000
Evan Cheng696e5c02007-12-13 07:50:36 +00003001 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00003002 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00003003 return false;
3004
Evan Cheng772de512007-12-12 00:51:06 +00003005 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00003006 // this block.
3007 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00003008 return false;
3009
Evan Chengbdcb7262007-12-05 23:58:20 +00003010 bool DefIsLiveOut = false;
Stephen Hines36b56882014-04-23 16:57:46 -07003011 for (User *U : I->users()) {
3012 Instruction *UI = cast<Instruction>(U);
Evan Chengbdcb7262007-12-05 23:58:20 +00003013
3014 // Figure out which BB this ext is used in.
Stephen Hines36b56882014-04-23 16:57:46 -07003015 BasicBlock *UserBB = UI->getParent();
Evan Chengbdcb7262007-12-05 23:58:20 +00003016 if (UserBB == DefBB) continue;
3017 DefIsLiveOut = true;
3018 break;
3019 }
3020 if (!DefIsLiveOut)
3021 return false;
3022
Jim Grosbach467116a2013-04-15 17:40:48 +00003023 // Make sure none of the uses are PHI nodes.
Stephen Hines36b56882014-04-23 16:57:46 -07003024 for (User *U : Src->users()) {
3025 Instruction *UI = cast<Instruction>(U);
3026 BasicBlock *UserBB = UI->getParent();
Evan Chengf9785f92007-12-13 03:32:53 +00003027 if (UserBB == DefBB) continue;
3028 // Be conservative. We don't want this xform to end up introducing
3029 // reloads just before load / store instructions.
Stephen Hines36b56882014-04-23 16:57:46 -07003030 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng765dff22007-12-12 02:53:41 +00003031 return false;
3032 }
3033
Evan Chengbdcb7262007-12-05 23:58:20 +00003034 // InsertedTruncs - Only insert one trunc in each block once.
3035 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3036
3037 bool MadeChange = false;
Stephen Hines36b56882014-04-23 16:57:46 -07003038 for (Use &U : Src->uses()) {
3039 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengbdcb7262007-12-05 23:58:20 +00003040
3041 // Figure out which BB this ext is used in.
3042 BasicBlock *UserBB = User->getParent();
3043 if (UserBB == DefBB) continue;
3044
3045 // Both src and def are live in this block. Rewrite the use.
3046 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3047
3048 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00003049 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00003050 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Stephen Hines36b56882014-04-23 16:57:46 -07003051 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengbdcb7262007-12-05 23:58:20 +00003052 }
3053
3054 // Replace a use of the {s|z}ext source with a use of the result.
Stephen Hines36b56882014-04-23 16:57:46 -07003055 U = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00003056 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00003057 MadeChange = true;
3058 }
3059
3060 return MadeChange;
3061}
3062
Benjamin Kramer59957502012-05-05 12:49:22 +00003063/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3064/// turned into an explicit branch.
3065static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3066 // FIXME: This should use the same heuristics as IfConversion to determine
3067 // whether a select is better represented as a branch. This requires that
3068 // branch probability metadata is preserved for the select, which is not the
3069 // case currently.
3070
3071 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3072
3073 // If the branch is predicted right, an out of order CPU can avoid blocking on
3074 // the compare. Emit cmovs on compares with a memory operand as branches to
3075 // avoid stalls on the load from memory. If the compare has more than one use
3076 // there's probably another cmov or setcc around so it's not worth emitting a
3077 // branch.
3078 if (!Cmp)
3079 return false;
3080
3081 Value *CmpOp0 = Cmp->getOperand(0);
3082 Value *CmpOp1 = Cmp->getOperand(1);
3083
3084 // We check that the memory operand has one use to avoid uses of the loaded
3085 // value directly after the compare, making branches unprofitable.
3086 return Cmp->hasOneUse() &&
3087 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3088 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3089}
3090
3091
Nadav Rotem9f40cb32012-09-02 12:10:19 +00003092/// If we have a SelectInst that will likely profit from branch prediction,
3093/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00003094bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00003095 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3096
3097 // Can we convert the 'select' to CF ?
3098 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00003099 return false;
3100
Nadav Rotem9f40cb32012-09-02 12:10:19 +00003101 TargetLowering::SelectSupportKind SelectKind;
3102 if (VectorCond)
3103 SelectKind = TargetLowering::VectorMaskSelect;
3104 else if (SI->getType()->isVectorTy())
3105 SelectKind = TargetLowering::ScalarCondVectorVal;
3106 else
3107 SelectKind = TargetLowering::ScalarValSelect;
3108
3109 // Do we have efficient codegen support for this kind of 'selects' ?
3110 if (TLI->isSelectSupported(SelectKind)) {
3111 // We have efficient codegen support for the select instruction.
3112 // Check if it is profitable to keep this 'select'.
3113 if (!TLI->isPredictableSelectExpensive() ||
3114 !isFormingBranchFromSelectProfitable(SI))
3115 return false;
3116 }
Benjamin Kramer59957502012-05-05 12:49:22 +00003117
3118 ModifiedDT = true;
3119
3120 // First, we split the block containing the select into 2 blocks.
3121 BasicBlock *StartBlock = SI->getParent();
3122 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3123 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3124
3125 // Create a new block serving as the landing pad for the branch.
3126 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3127 NextBlock->getParent(), NextBlock);
3128
3129 // Move the unconditional branch from the block with the select in it into our
3130 // landing pad block.
3131 StartBlock->getTerminator()->eraseFromParent();
3132 BranchInst::Create(NextBlock, SmallBlock);
3133
3134 // Insert the real conditional branch based on the original condition.
3135 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3136
3137 // The select itself is replaced with a PHI Node.
3138 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3139 PN->takeName(SI);
3140 PN->addIncoming(SI->getTrueValue(), StartBlock);
3141 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3142 SI->replaceAllUsesWith(PN);
3143 SI->eraseFromParent();
3144
3145 // Instruct OptimizeBlock to skip to the next block.
3146 CurInstIterator = StartBlock->end();
3147 ++NumSelectsExpanded;
3148 return true;
3149}
3150
Stephen Hines36b56882014-04-23 16:57:46 -07003151static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3152 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3153 int SplatElem = -1;
3154 for (unsigned i = 0; i < Mask.size(); ++i) {
3155 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3156 return false;
3157 SplatElem = Mask[i];
3158 }
3159
3160 return true;
3161}
3162
3163/// Some targets have expensive vector shifts if the lanes aren't all the same
3164/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3165/// it's often worth sinking a shufflevector splat down to its use so that
3166/// codegen can spot all lanes are identical.
3167bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3168 BasicBlock *DefBB = SVI->getParent();
3169
3170 // Only do this xform if variable vector shifts are particularly expensive.
3171 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3172 return false;
3173
3174 // We only expect better codegen by sinking a shuffle if we can recognise a
3175 // constant splat.
3176 if (!isBroadcastShuffle(SVI))
3177 return false;
3178
3179 // InsertedShuffles - Only insert a shuffle in each block once.
3180 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3181
3182 bool MadeChange = false;
3183 for (User *U : SVI->users()) {
3184 Instruction *UI = cast<Instruction>(U);
3185
3186 // Figure out which BB this ext is used in.
3187 BasicBlock *UserBB = UI->getParent();
3188 if (UserBB == DefBB) continue;
3189
3190 // For now only apply this when the splat is used by a shift instruction.
3191 if (!UI->isShift()) continue;
3192
3193 // Everything checks out, sink the shuffle if the user's block doesn't
3194 // already have a copy.
3195 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3196
3197 if (!InsertedShuffle) {
3198 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3199 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3200 SVI->getOperand(1),
3201 SVI->getOperand(2), "", InsertPt);
3202 }
3203
3204 UI->replaceUsesOfWith(SVI, InsertedShuffle);
3205 MadeChange = true;
3206 }
3207
3208 // If we removed all uses, nuke the shuffle.
3209 if (SVI->use_empty()) {
3210 SVI->eraseFromParent();
3211 MadeChange = true;
3212 }
3213
3214 return MadeChange;
3215}
3216
Stephen Hines37ed9c12014-12-01 14:51:49 -08003217namespace {
3218/// \brief Helper class to promote a scalar operation to a vector one.
3219/// This class is used to move downward extractelement transition.
3220/// E.g.,
3221/// a = vector_op <2 x i32>
3222/// b = extractelement <2 x i32> a, i32 0
3223/// c = scalar_op b
3224/// store c
3225///
3226/// =>
3227/// a = vector_op <2 x i32>
3228/// c = vector_op a (equivalent to scalar_op on the related lane)
3229/// * d = extractelement <2 x i32> c, i32 0
3230/// * store d
3231/// Assuming both extractelement and store can be combine, we get rid of the
3232/// transition.
3233class VectorPromoteHelper {
3234 /// Used to perform some checks on the legality of vector operations.
3235 const TargetLowering &TLI;
3236
3237 /// Used to estimated the cost of the promoted chain.
3238 const TargetTransformInfo &TTI;
3239
3240 /// The transition being moved downwards.
3241 Instruction *Transition;
3242 /// The sequence of instructions to be promoted.
3243 SmallVector<Instruction *, 4> InstsToBePromoted;
3244 /// Cost of combining a store and an extract.
3245 unsigned StoreExtractCombineCost;
3246 /// Instruction that will be combined with the transition.
3247 Instruction *CombineInst;
3248
3249 /// \brief The instruction that represents the current end of the transition.
3250 /// Since we are faking the promotion until we reach the end of the chain
3251 /// of computation, we need a way to get the current end of the transition.
3252 Instruction *getEndOfTransition() const {
3253 if (InstsToBePromoted.empty())
3254 return Transition;
3255 return InstsToBePromoted.back();
3256 }
3257
3258 /// \brief Return the index of the original value in the transition.
3259 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3260 /// c, is at index 0.
3261 unsigned getTransitionOriginalValueIdx() const {
3262 assert(isa<ExtractElementInst>(Transition) &&
3263 "Other kind of transitions are not supported yet");
3264 return 0;
3265 }
3266
3267 /// \brief Return the index of the index in the transition.
3268 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3269 /// is at index 1.
3270 unsigned getTransitionIdx() const {
3271 assert(isa<ExtractElementInst>(Transition) &&
3272 "Other kind of transitions are not supported yet");
3273 return 1;
3274 }
3275
3276 /// \brief Get the type of the transition.
3277 /// This is the type of the original value.
3278 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3279 /// transition is <2 x i32>.
3280 Type *getTransitionType() const {
3281 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3282 }
3283
3284 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3285 /// I.e., we have the following sequence:
3286 /// Def = Transition <ty1> a to <ty2>
3287 /// b = ToBePromoted <ty2> Def, ...
3288 /// =>
3289 /// b = ToBePromoted <ty1> a, ...
3290 /// Def = Transition <ty1> ToBePromoted to <ty2>
3291 void promoteImpl(Instruction *ToBePromoted);
3292
3293 /// \brief Check whether or not it is profitable to promote all the
3294 /// instructions enqueued to be promoted.
3295 bool isProfitableToPromote() {
3296 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3297 unsigned Index = isa<ConstantInt>(ValIdx)
3298 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3299 : -1;
3300 Type *PromotedType = getTransitionType();
3301
3302 StoreInst *ST = cast<StoreInst>(CombineInst);
3303 unsigned AS = ST->getPointerAddressSpace();
3304 unsigned Align = ST->getAlignment();
3305 // Check if this store is supported.
3306 if (!TLI.allowsMisalignedMemoryAccesses(
3307 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
3308 // If this is not supported, there is no way we can combine
3309 // the extract with the store.
3310 return false;
3311 }
3312
3313 // The scalar chain of computation has to pay for the transition
3314 // scalar to vector.
3315 // The vector chain has to account for the combining cost.
3316 uint64_t ScalarCost =
3317 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3318 uint64_t VectorCost = StoreExtractCombineCost;
3319 for (const auto &Inst : InstsToBePromoted) {
3320 // Compute the cost.
3321 // By construction, all instructions being promoted are arithmetic ones.
3322 // Moreover, one argument is a constant that can be viewed as a splat
3323 // constant.
3324 Value *Arg0 = Inst->getOperand(0);
3325 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3326 isa<ConstantFP>(Arg0);
3327 TargetTransformInfo::OperandValueKind Arg0OVK =
3328 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3329 : TargetTransformInfo::OK_AnyValue;
3330 TargetTransformInfo::OperandValueKind Arg1OVK =
3331 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3332 : TargetTransformInfo::OK_AnyValue;
3333 ScalarCost += TTI.getArithmeticInstrCost(
3334 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3335 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3336 Arg0OVK, Arg1OVK);
3337 }
3338 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3339 << ScalarCost << "\nVector: " << VectorCost << '\n');
3340 return ScalarCost > VectorCost;
3341 }
3342
3343 /// \brief Generate a constant vector with \p Val with the same
3344 /// number of elements as the transition.
3345 /// \p UseSplat defines whether or not \p Val should be replicated
3346 /// accross the whole vector.
3347 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3348 /// otherwise we generate a vector with as many undef as possible:
3349 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3350 /// used at the index of the extract.
3351 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3352 unsigned ExtractIdx = UINT_MAX;
3353 if (!UseSplat) {
3354 // If we cannot determine where the constant must be, we have to
3355 // use a splat constant.
3356 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3357 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3358 ExtractIdx = CstVal->getSExtValue();
3359 else
3360 UseSplat = true;
3361 }
3362
3363 unsigned End = getTransitionType()->getVectorNumElements();
3364 if (UseSplat)
3365 return ConstantVector::getSplat(End, Val);
3366
3367 SmallVector<Constant *, 4> ConstVec;
3368 UndefValue *UndefVal = UndefValue::get(Val->getType());
3369 for (unsigned Idx = 0; Idx != End; ++Idx) {
3370 if (Idx == ExtractIdx)
3371 ConstVec.push_back(Val);
3372 else
3373 ConstVec.push_back(UndefVal);
3374 }
3375 return ConstantVector::get(ConstVec);
3376 }
3377
3378 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3379 /// in \p Use can trigger undefined behavior.
3380 static bool canCauseUndefinedBehavior(const Instruction *Use,
3381 unsigned OperandIdx) {
3382 // This is not safe to introduce undef when the operand is on
3383 // the right hand side of a division-like instruction.
3384 if (OperandIdx != 1)
3385 return false;
3386 switch (Use->getOpcode()) {
3387 default:
3388 return false;
3389 case Instruction::SDiv:
3390 case Instruction::UDiv:
3391 case Instruction::SRem:
3392 case Instruction::URem:
3393 return true;
3394 case Instruction::FDiv:
3395 case Instruction::FRem:
3396 return !Use->hasNoNaNs();
3397 }
3398 llvm_unreachable(nullptr);
3399 }
3400
3401public:
3402 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3403 Instruction *Transition, unsigned CombineCost)
3404 : TLI(TLI), TTI(TTI), Transition(Transition),
3405 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3406 assert(Transition && "Do not know how to promote null");
3407 }
3408
3409 /// \brief Check if we can promote \p ToBePromoted to \p Type.
3410 bool canPromote(const Instruction *ToBePromoted) const {
3411 // We could support CastInst too.
3412 return isa<BinaryOperator>(ToBePromoted);
3413 }
3414
3415 /// \brief Check if it is profitable to promote \p ToBePromoted
3416 /// by moving downward the transition through.
3417 bool shouldPromote(const Instruction *ToBePromoted) const {
3418 // Promote only if all the operands can be statically expanded.
3419 // Indeed, we do not want to introduce any new kind of transitions.
3420 for (const Use &U : ToBePromoted->operands()) {
3421 const Value *Val = U.get();
3422 if (Val == getEndOfTransition()) {
3423 // If the use is a division and the transition is on the rhs,
3424 // we cannot promote the operation, otherwise we may create a
3425 // division by zero.
3426 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3427 return false;
3428 continue;
3429 }
3430 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3431 !isa<ConstantFP>(Val))
3432 return false;
3433 }
3434 // Check that the resulting operation is legal.
3435 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3436 if (!ISDOpcode)
3437 return false;
3438 return StressStoreExtract ||
3439 TLI.isOperationLegalOrCustom(
3440 ISDOpcode, TLI.getValueType(getTransitionType(), true));
3441 }
3442
3443 /// \brief Check whether or not \p Use can be combined
3444 /// with the transition.
3445 /// I.e., is it possible to do Use(Transition) => AnotherUse?
3446 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3447
3448 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3449 void enqueueForPromotion(Instruction *ToBePromoted) {
3450 InstsToBePromoted.push_back(ToBePromoted);
3451 }
3452
3453 /// \brief Set the instruction that will be combined with the transition.
3454 void recordCombineInstruction(Instruction *ToBeCombined) {
3455 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3456 CombineInst = ToBeCombined;
3457 }
3458
3459 /// \brief Promote all the instructions enqueued for promotion if it is
3460 /// is profitable.
3461 /// \return True if the promotion happened, false otherwise.
3462 bool promote() {
3463 // Check if there is something to promote.
3464 // Right now, if we do not have anything to combine with,
3465 // we assume the promotion is not profitable.
3466 if (InstsToBePromoted.empty() || !CombineInst)
3467 return false;
3468
3469 // Check cost.
3470 if (!StressStoreExtract && !isProfitableToPromote())
3471 return false;
3472
3473 // Promote.
3474 for (auto &ToBePromoted : InstsToBePromoted)
3475 promoteImpl(ToBePromoted);
3476 InstsToBePromoted.clear();
3477 return true;
3478 }
3479};
3480} // End of anonymous namespace.
3481
3482void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3483 // At this point, we know that all the operands of ToBePromoted but Def
3484 // can be statically promoted.
3485 // For Def, we need to use its parameter in ToBePromoted:
3486 // b = ToBePromoted ty1 a
3487 // Def = Transition ty1 b to ty2
3488 // Move the transition down.
3489 // 1. Replace all uses of the promoted operation by the transition.
3490 // = ... b => = ... Def.
3491 assert(ToBePromoted->getType() == Transition->getType() &&
3492 "The type of the result of the transition does not match "
3493 "the final type");
3494 ToBePromoted->replaceAllUsesWith(Transition);
3495 // 2. Update the type of the uses.
3496 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3497 Type *TransitionTy = getTransitionType();
3498 ToBePromoted->mutateType(TransitionTy);
3499 // 3. Update all the operands of the promoted operation with promoted
3500 // operands.
3501 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3502 for (Use &U : ToBePromoted->operands()) {
3503 Value *Val = U.get();
3504 Value *NewVal = nullptr;
3505 if (Val == Transition)
3506 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3507 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3508 isa<ConstantFP>(Val)) {
3509 // Use a splat constant if it is not safe to use undef.
3510 NewVal = getConstantVector(
3511 cast<Constant>(Val),
3512 isa<UndefValue>(Val) ||
3513 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3514 } else
3515 assert(0 && "Did you modified shouldPromote and forgot to update this?");
3516 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3517 }
3518 Transition->removeFromParent();
3519 Transition->insertAfter(ToBePromoted);
3520 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3521}
3522
3523/// Some targets can do store(extractelement) with one instruction.
3524/// Try to push the extractelement towards the stores when the target
3525/// has this feature and this is profitable.
3526bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
3527 unsigned CombineCost = UINT_MAX;
3528 if (DisableStoreExtract || !TLI ||
3529 (!StressStoreExtract &&
3530 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
3531 Inst->getOperand(1), CombineCost)))
3532 return false;
3533
3534 // At this point we know that Inst is a vector to scalar transition.
3535 // Try to move it down the def-use chain, until:
3536 // - We can combine the transition with its single use
3537 // => we got rid of the transition.
3538 // - We escape the current basic block
3539 // => we would need to check that we are moving it at a cheaper place and
3540 // we do not do that for now.
3541 BasicBlock *Parent = Inst->getParent();
3542 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
3543 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
3544 // If the transition has more than one use, assume this is not going to be
3545 // beneficial.
3546 while (Inst->hasOneUse()) {
3547 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
3548 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
3549
3550 if (ToBePromoted->getParent() != Parent) {
3551 DEBUG(dbgs() << "Instruction to promote is in a different block ("
3552 << ToBePromoted->getParent()->getName()
3553 << ") than the transition (" << Parent->getName() << ").\n");
3554 return false;
3555 }
3556
3557 if (VPH.canCombine(ToBePromoted)) {
3558 DEBUG(dbgs() << "Assume " << *Inst << '\n'
3559 << "will be combined with: " << *ToBePromoted << '\n');
3560 VPH.recordCombineInstruction(ToBePromoted);
3561 bool Changed = VPH.promote();
3562 NumStoreExtractExposed += Changed;
3563 return Changed;
3564 }
3565
3566 DEBUG(dbgs() << "Try promoting.\n");
3567 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
3568 return false;
3569
3570 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
3571
3572 VPH.enqueueForPromotion(ToBePromoted);
3573 Inst = ToBePromoted;
3574 }
3575 return false;
3576}
3577
Cameron Zwarichc0611012011-01-06 02:37:26 +00003578bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00003579 if (PHINode *P = dyn_cast<PHINode>(I)) {
3580 // It is possible for very late stage optimizations (such as SimplifyCFG)
3581 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3582 // trivial PHI, go ahead and zap it here.
Stephen Hinesdce4a402014-05-29 02:49:00 -07003583 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramerd7215202013-09-24 16:37:40 +00003584 TLInfo, DT)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00003585 P->replaceAllUsesWith(V);
3586 P->eraseFromParent();
3587 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00003588 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00003589 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00003590 return false;
3591 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00003592
Chris Lattner1a8943a2011-01-15 07:29:01 +00003593 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00003594 // If the source of the cast is a constant, then this should have
3595 // already been constant folded. The only reason NOT to constant fold
3596 // it is if something (e.g. LSR) was careful to place the constant
3597 // evaluation in a block other than then one that uses it (e.g. to hoist
3598 // the address of globals out of a loop). If this is the case, we don't
3599 // want to forward-subst the cast.
3600 if (isa<Constant>(CI->getOperand(0)))
3601 return false;
3602
Chris Lattner1a8943a2011-01-15 07:29:01 +00003603 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3604 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00003605
Chris Lattner1a8943a2011-01-15 07:29:01 +00003606 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Stephen Hines36b56882014-04-23 16:57:46 -07003607 /// Sink a zext or sext into its user blocks if the target type doesn't
3608 /// fit in one register
3609 if (TLI && TLI->getTypeAction(CI->getContext(),
3610 TLI->getValueType(CI->getType())) ==
3611 TargetLowering::TypeExpandInteger) {
3612 return SinkCast(CI);
3613 } else {
3614 bool MadeChange = MoveExtToFormExtLoad(I);
3615 return MadeChange | OptimizeExtUses(I);
3616 }
Cameron Zwarichc0611012011-01-06 02:37:26 +00003617 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00003618 return false;
3619 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00003620
Chris Lattner1a8943a2011-01-15 07:29:01 +00003621 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Stephen Hines36b56882014-04-23 16:57:46 -07003622 if (!TLI || !TLI->hasMultipleConditionRegisters())
3623 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00003624
Chris Lattner1a8943a2011-01-15 07:29:01 +00003625 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00003626 if (TLI)
Hans Wennborg04d7d132012-10-30 11:23:25 +00003627 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3628 return false;
Chris Lattner1a8943a2011-01-15 07:29:01 +00003629 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00003630
Chris Lattner1a8943a2011-01-15 07:29:01 +00003631 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00003632 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00003633 return OptimizeMemoryInst(I, SI->getOperand(1),
3634 SI->getOperand(0)->getType());
3635 return false;
3636 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00003637
Stephen Hinesdce4a402014-05-29 02:49:00 -07003638 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3639
3640 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3641 BinOp->getOpcode() == Instruction::LShr)) {
3642 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3643 if (TLI && CI && TLI->hasExtractBitsInsn())
3644 return OptimizeExtractBits(BinOp, CI, *TLI);
3645
3646 return false;
3647 }
3648
Chris Lattner1a8943a2011-01-15 07:29:01 +00003649 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00003650 if (GEPI->hasAllZeroIndices()) {
3651 /// The GEP operand must be a pointer, so must its result -> BitCast
3652 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3653 GEPI->getName(), GEPI);
3654 GEPI->replaceAllUsesWith(NC);
3655 GEPI->eraseFromParent();
3656 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00003657 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00003658 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00003659 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00003660 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00003661 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00003662
Chris Lattner1a8943a2011-01-15 07:29:01 +00003663 if (CallInst *CI = dyn_cast<CallInst>(I))
3664 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00003665
Benjamin Kramer59957502012-05-05 12:49:22 +00003666 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3667 return OptimizeSelectInst(SI);
3668
Stephen Hines36b56882014-04-23 16:57:46 -07003669 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3670 return OptimizeShuffleVectorInst(SVI);
3671
Stephen Hines37ed9c12014-12-01 14:51:49 -08003672 if (isa<ExtractElementInst>(I))
3673 return OptimizeExtractElementInst(I);
3674
Chris Lattner1a8943a2011-01-15 07:29:01 +00003675 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00003676}
3677
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00003678// In this pass we look for GEP and cast instructions that are used
3679// across basic blocks and rewrite them to improve basic-block-at-a-time
3680// selection.
3681bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00003682 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00003683 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00003684
Chris Lattner75796092011-01-15 07:14:54 +00003685 CurInstIterator = BB.begin();
Hans Wennborg93ba1332012-09-19 07:48:16 +00003686 while (CurInstIterator != BB.end())
Chris Lattner94e8e0c2011-01-15 07:25:29 +00003687 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00003688
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +00003689 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3690
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00003691 return MadeChange;
3692}
Devang Patelf56ea612011-08-18 00:50:51 +00003693
3694// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00003695// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00003696// find a node corresponding to the value.
3697bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3698 bool MadeChange = false;
3699 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07003700 Instruction *PrevNonDbgInst = nullptr;
Devang Patelf56ea612011-08-18 00:50:51 +00003701 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3702 Instruction *Insn = BI; ++BI;
3703 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Stephen Hinesdce4a402014-05-29 02:49:00 -07003704 // Leave dbg.values that refer to an alloca alone. These
3705 // instrinsics describe the address of a variable (= the alloca)
3706 // being taken. They should not be moved next to the alloca
3707 // (and to the beginning of the scope), but rather stay close to
3708 // where said address is used.
3709 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patelf56ea612011-08-18 00:50:51 +00003710 PrevNonDbgInst = Insn;
3711 continue;
3712 }
3713
3714 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3715 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3716 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3717 DVI->removeFromParent();
3718 if (isa<PHINode>(VI))
3719 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3720 else
3721 DVI->insertAfter(VI);
3722 MadeChange = true;
3723 ++NumDbgValueMoved;
3724 }
3725 }
3726 }
3727 return MadeChange;
3728}
Stephen Hines36b56882014-04-23 16:57:46 -07003729
3730// If there is a sequence that branches based on comparing a single bit
3731// against zero that can be combined into a single instruction, and the
3732// target supports folding these into a single instruction, sink the
3733// mask and compare into the branch uses. Do this before OptimizeBlock ->
3734// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3735// searched for.
3736bool CodeGenPrepare::sinkAndCmp(Function &F) {
3737 if (!EnableAndCmpSinking)
3738 return false;
3739 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3740 return false;
3741 bool MadeChange = false;
3742 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3743 BasicBlock *BB = I++;
3744
3745 // Does this BB end with the following?
3746 // %andVal = and %val, #single-bit-set
3747 // %icmpVal = icmp %andResult, 0
3748 // br i1 %cmpVal label %dest1, label %dest2"
3749 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3750 if (!Brcc || !Brcc->isConditional())
3751 continue;
3752 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3753 if (!Cmp || Cmp->getParent() != BB)
3754 continue;
3755 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3756 if (!Zero || !Zero->isZero())
3757 continue;
3758 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3759 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3760 continue;
3761 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3762 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3763 continue;
3764 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3765
3766 // Push the "and; icmp" for any users that are conditional branches.
3767 // Since there can only be one branch use per BB, we don't need to keep
3768 // track of which BBs we insert into.
3769 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3770 UI != E; ) {
3771 Use &TheUse = *UI;
3772 // Find brcc use.
3773 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3774 ++UI;
3775 if (!BrccUser || !BrccUser->isConditional())
3776 continue;
3777 BasicBlock *UserBB = BrccUser->getParent();
3778 if (UserBB == BB) continue;
3779 DEBUG(dbgs() << "found Brcc use\n");
3780
3781 // Sink the "and; icmp" to use.
3782 MadeChange = true;
3783 BinaryOperator *NewAnd =
3784 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3785 BrccUser);
3786 CmpInst *NewCmp =
3787 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3788 "", BrccUser);
3789 TheUse = NewCmp;
3790 ++NumAndCmpsMoved;
3791 DEBUG(BrccUser->getParent()->dump());
3792 }
3793 }
3794 return MadeChange;
3795}