blob: 9ed15fb77531ca74b9754fd909f3bd0a2ed44de5 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000023#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InlineAsm.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000034#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000035#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000036#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000038#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000039#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000040#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000041#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000044#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000047#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000050using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000051using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000052
Chandler Carruth1b9dde02014-04-22 02:02:50 +000053#define DEBUG_TYPE "codegenprepare"
54
Cameron Zwarichced753f2011-01-05 17:27:27 +000055STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000056STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
57STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000058STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
59 "sunken Cmps");
60STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
61 "of sunken Casts");
62STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
63 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000064STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
65STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
66STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000067STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000068STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000069STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000070STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000071
Cameron Zwarich338d3622011-03-11 21:52:04 +000072static cl::opt<bool> DisableBranchOpts(
73 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
74 cl::desc("Disable branch optimizations in CodeGenPrepare"));
75
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000076static cl::opt<bool>
77 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
78 cl::desc("Disable GC optimizations in CodeGenPrepare"));
79
Benjamin Kramer3d38c172012-05-06 14:25:16 +000080static cl::opt<bool> DisableSelectToBranch(
81 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
82 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000083
Hal Finkelc3998302014-04-12 00:59:48 +000084static cl::opt<bool> AddrSinkUsingGEPs(
85 "addr-sink-using-gep", cl::Hidden, cl::init(false),
86 cl::desc("Address sinking in CGP using GEPs."));
87
Tim Northovercea0abb2014-03-29 08:22:29 +000088static cl::opt<bool> EnableAndCmpSinking(
89 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
90 cl::desc("Enable sinkinig and/cmp into branches."));
91
Quentin Colombetc32615d2014-10-31 17:52:53 +000092static cl::opt<bool> DisableStoreExtract(
93 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
94 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
95
96static cl::opt<bool> StressStoreExtract(
97 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
98 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
99
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000100static cl::opt<bool> DisableExtLdPromotion(
101 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
103 "CodeGenPrepare"));
104
105static cl::opt<bool> StressExtLdPromotion(
106 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
107 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
108 "optimization in CodeGenPrepare"));
109
Eric Christopherc1ea1492008-09-24 05:32:41 +0000110namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000111typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000112typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000113typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000114class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000115
Chris Lattner2dd09db2009-09-02 06:11:42 +0000116 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000117 /// TLI - Keep a pointer of a TargetLowering to consult for determining
118 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000119 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000120 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000121 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000122 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000123
Chris Lattner7a277142011-01-15 07:14:54 +0000124 /// CurInstIterator - As we scan instructions optimizing them, this is the
125 /// next instruction to optimize. Xforms that can invalidate this should
126 /// update it.
127 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000128
Evan Cheng0663f232011-03-21 01:19:09 +0000129 /// Keeps track of non-local addresses that have been sunk into a block.
130 /// This allows us to avoid inserting duplicate code for blocks with
131 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000132 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000133
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000134 /// Keeps track of all instructions inserted for the current function.
135 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000136 /// Keeps track of the type of the related instruction before their
137 /// promotion for the current function.
138 InstrToOrigTy PromotedInsts;
139
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000140 /// ModifiedDT - If CFG is modified in anyway.
Devang Patel8f606d72011-03-24 15:35:25 +0000141 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000142
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000143 /// OptSize - True if optimizing for size.
144 bool OptSize;
145
Mehdi Amini4fe37982015-07-07 18:45:17 +0000146 /// DataLayout for the Function being processed.
147 const DataLayout *DL;
148
Chris Lattnerf2836d12007-03-31 04:06:36 +0000149 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000150 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000151 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000152 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000153 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
154 }
Craig Topper4584cd52014-03-07 09:26:03 +0000155 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000156
Craig Topper4584cd52014-03-07 09:26:03 +0000157 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000158
Craig Topper4584cd52014-03-07 09:26:03 +0000159 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000160 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000161 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000162 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000163 }
164
Chris Lattnerf2836d12007-03-31 04:06:36 +0000165 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000166 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000167 bool EliminateMostlyEmptyBlocks(Function &F);
168 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
169 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000170 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
171 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000172 bool OptimizeMemoryInst(Instruction *I, Value *Addr,
173 Type *AccessTy, unsigned AS);
Chris Lattner7a277142011-01-15 07:14:54 +0000174 bool OptimizeInlineAsmInst(CallInst *CS);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000175 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000176 bool MoveExtToFormExtLoad(Instruction *&I);
Evan Chengd3d80172007-12-05 23:58:20 +0000177 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000178 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000179 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000180 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000181 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000182 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000183 bool sinkAndCmp(Function &F);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000184 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
185 Instruction *&Inst,
186 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000187 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000188 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000189 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000190 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000191}
Devang Patel09f162c2007-05-01 21:15:47 +0000192
Devang Patel8c78a0b2007-05-03 01:11:54 +0000193char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000194INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
195 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000196
Bill Wendling7a639ea2013-06-19 21:07:11 +0000197FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
198 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000199}
200
Chris Lattnerf2836d12007-03-31 04:06:36 +0000201bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000202 if (skipOptnoneFunction(F))
203 return false;
204
Mehdi Amini4fe37982015-07-07 18:45:17 +0000205 DL = &F.getParent()->getDataLayout();
206
Chris Lattnerf2836d12007-03-31 04:06:36 +0000207 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000208 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000209 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000210 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000211
Devang Patel8f606d72011-03-24 15:35:25 +0000212 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000213 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000214 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000215 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000216 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000217 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000218
Preston Gurdcdf540d2012-09-04 18:22:17 +0000219 /// This optimization identifies DIV instructions that can be
220 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000221 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000222 const DenseMap<unsigned int, unsigned int> &BypassWidths =
223 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000224 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000225 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000226 }
227
228 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000229 // unconditional branch.
230 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000231
Devang Patel53771ba2011-08-18 00:50:51 +0000232 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000233 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000234 // find a node corresponding to the value.
235 EverMadeChange |= PlaceDbgValues(F);
236
Tim Northovercea0abb2014-03-29 08:22:29 +0000237 // If there is a mask, compare against zero, and branch that can be combined
238 // into a single target instruction, push the mask and compare into branch
239 // users. Do this before OptimizeBlock -> OptimizeInst ->
240 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000241 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000242 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000243 EverMadeChange |= splitBranchCondition(F);
244 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000245
Chris Lattnerc3748562007-04-02 01:35:34 +0000246 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000247 while (MadeChange) {
248 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000249 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000250 BasicBlock *BB = I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000251 bool ModifiedDTOnIteration = false;
252 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000253
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000254 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000255 if (ModifiedDTOnIteration)
256 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000257 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000258 EverMadeChange |= MadeChange;
259 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000260
261 SunkAddrs.clear();
262
Cameron Zwarich338d3622011-03-11 21:52:04 +0000263 if (!DisableBranchOpts) {
264 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000265 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000266 for (BasicBlock &BB : F) {
267 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
268 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000269 if (!MadeChange) continue;
270
271 for (SmallVectorImpl<BasicBlock*>::iterator
272 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
273 if (pred_begin(*II) == pred_end(*II))
274 WorkList.insert(*II);
275 }
276
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000277 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000278 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000279 while (!WorkList.empty()) {
280 BasicBlock *BB = *WorkList.begin();
281 WorkList.erase(BB);
282 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
283
284 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000285
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000286 for (SmallVectorImpl<BasicBlock*>::iterator
287 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
288 if (pred_begin(*II) == pred_end(*II))
289 WorkList.insert(*II);
290 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000291
Nadav Rotem70409992012-08-14 05:19:07 +0000292 // Merge pairs of basic blocks with unconditional branches, connected by
293 // a single edge.
294 if (EverMadeChange || MadeChange)
295 MadeChange |= EliminateFallThrough(F);
296
Cameron Zwarich338d3622011-03-11 21:52:04 +0000297 EverMadeChange |= MadeChange;
298 }
299
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000300 if (!DisableGCOpts) {
301 SmallVector<Instruction *, 2> Statepoints;
302 for (BasicBlock &BB : F)
303 for (Instruction &I : BB)
304 if (isStatepoint(I))
305 Statepoints.push_back(&I);
306 for (auto &I : Statepoints)
307 EverMadeChange |= simplifyOffsetableRelocate(*I);
308 }
309
Chris Lattnerf2836d12007-03-31 04:06:36 +0000310 return EverMadeChange;
311}
312
Nadav Rotem70409992012-08-14 05:19:07 +0000313/// EliminateFallThrough - Merge basic blocks which are connected
314/// by a single edge, where one of the basic blocks has a single successor
315/// pointing to the other basic block, which has a single predecessor.
316bool CodeGenPrepare::EliminateFallThrough(Function &F) {
317 bool Changed = false;
318 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000319 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000320 BasicBlock *BB = I++;
321 // If the destination block has a single pred, then this is a trivial
322 // edge, just collapse it.
323 BasicBlock *SinglePred = BB->getSinglePredecessor();
324
Evan Cheng64a223a2012-09-28 23:58:57 +0000325 // Don't merge if BB's address is taken.
326 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000327
328 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
329 if (Term && !Term->isConditional()) {
330 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000331 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000332 // Remember if SinglePred was the entry block of the function.
333 // If so, we will need to move BB back to the entry position.
334 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000335 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000336
337 if (isEntry && BB != &BB->getParent()->getEntryBlock())
338 BB->moveBefore(&BB->getParent()->getEntryBlock());
339
340 // We have erased a block. Update the iterator.
341 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000342 }
343 }
344 return Changed;
345}
346
Dale Johannesen4026b042009-03-27 01:13:37 +0000347/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
348/// debug info directives, and an unconditional branch. Passes before isel
349/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
350/// isel. Start by eliminating these blocks so we can split them the way we
351/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000352bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
353 bool MadeChange = false;
354 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000355 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000356 BasicBlock *BB = I++;
357
358 // If this block doesn't end with an uncond branch, ignore it.
359 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
360 if (!BI || !BI->isUnconditional())
361 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000362
Dale Johannesen4026b042009-03-27 01:13:37 +0000363 // If the instruction before the branch (skipping debug info) isn't a phi
364 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000365 BasicBlock::iterator BBI = BI;
366 if (BBI != BB->begin()) {
367 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000368 while (isa<DbgInfoIntrinsic>(BBI)) {
369 if (BBI == BB->begin())
370 break;
371 --BBI;
372 }
373 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
374 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000376
Chris Lattnerc3748562007-04-02 01:35:34 +0000377 // Do not break infinite loops.
378 BasicBlock *DestBB = BI->getSuccessor(0);
379 if (DestBB == BB)
380 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000381
Chris Lattnerc3748562007-04-02 01:35:34 +0000382 if (!CanMergeBlocks(BB, DestBB))
383 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000384
Chris Lattnerc3748562007-04-02 01:35:34 +0000385 EliminateMostlyEmptyBlock(BB);
386 MadeChange = true;
387 }
388 return MadeChange;
389}
390
391/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
392/// single uncond branch between them, and BB contains no other non-phi
393/// instructions.
394bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
395 const BasicBlock *DestBB) const {
396 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
397 // the successor. If there are more complex condition (e.g. preheaders),
398 // don't mess around with them.
399 BasicBlock::const_iterator BBI = BB->begin();
400 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000401 for (const User *U : PN->users()) {
402 const Instruction *UI = cast<Instruction>(U);
403 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000404 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000405 // If User is inside DestBB block and it is a PHINode then check
406 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000407 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000408 if (UI->getParent() == DestBB) {
409 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000410 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
411 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
412 if (Insn && Insn->getParent() == BB &&
413 Insn->getParent() != UPN->getIncomingBlock(I))
414 return false;
415 }
416 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000417 }
418 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000419
Chris Lattnerc3748562007-04-02 01:35:34 +0000420 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
421 // and DestBB may have conflicting incoming values for the block. If so, we
422 // can't merge the block.
423 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
424 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000425
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000427 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000428 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
429 // It is faster to get preds from a PHI than with pred_iterator.
430 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
431 BBPreds.insert(BBPN->getIncomingBlock(i));
432 } else {
433 BBPreds.insert(pred_begin(BB), pred_end(BB));
434 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000435
Chris Lattnerc3748562007-04-02 01:35:34 +0000436 // Walk the preds of DestBB.
437 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
438 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
439 if (BBPreds.count(Pred)) { // Common predecessor?
440 BBI = DestBB->begin();
441 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
442 const Value *V1 = PN->getIncomingValueForBlock(Pred);
443 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000444
Chris Lattnerc3748562007-04-02 01:35:34 +0000445 // If V2 is a phi node in BB, look up what the mapped value will be.
446 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
447 if (V2PN->getParent() == BB)
448 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000449
Chris Lattnerc3748562007-04-02 01:35:34 +0000450 // If there is a conflict, bail out.
451 if (V1 != V2) return false;
452 }
453 }
454 }
455
456 return true;
457}
458
459
460/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
461/// an unconditional branch in it.
462void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
463 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
464 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000465
David Greene74e2d492010-01-05 01:27:11 +0000466 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000467
Chris Lattnerc3748562007-04-02 01:35:34 +0000468 // If the destination block has a single pred, then this is a trivial edge,
469 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000470 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000471 if (SinglePred != DestBB) {
472 // Remember if SinglePred was the entry block of the function. If so, we
473 // will need to move BB back to the entry position.
474 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000475 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000476
Chris Lattner8a172da2008-11-28 19:54:49 +0000477 if (isEntry && BB != &BB->getParent()->getEntryBlock())
478 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000479
David Greene74e2d492010-01-05 01:27:11 +0000480 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000481 return;
482 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000483 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000484
Chris Lattnerc3748562007-04-02 01:35:34 +0000485 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
486 // to handle the new incoming edges it is about to have.
487 PHINode *PN;
488 for (BasicBlock::iterator BBI = DestBB->begin();
489 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
490 // Remove the incoming value for BB, and remember it.
491 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000492
Chris Lattnerc3748562007-04-02 01:35:34 +0000493 // Two options: either the InVal is a phi node defined in BB or it is some
494 // value that dominates BB.
495 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
496 if (InValPhi && InValPhi->getParent() == BB) {
497 // Add all of the input values of the input PHI as inputs of this phi.
498 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
499 PN->addIncoming(InValPhi->getIncomingValue(i),
500 InValPhi->getIncomingBlock(i));
501 } else {
502 // Otherwise, add one instance of the dominating value for each edge that
503 // we will be adding.
504 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
505 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
506 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
507 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000508 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
509 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000510 }
511 }
512 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000513
Chris Lattnerc3748562007-04-02 01:35:34 +0000514 // The PHIs are now updated, change everything that refers to BB to use
515 // DestBB and remove BB.
516 BB->replaceAllUsesWith(DestBB);
517 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000518 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000519
David Greene74e2d492010-01-05 01:27:11 +0000520 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000521}
522
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000523// Computes a map of base pointer relocation instructions to corresponding
524// derived pointer relocation instructions given a vector of all relocate calls
525static void computeBaseDerivedRelocateMap(
526 const SmallVectorImpl<User *> &AllRelocateCalls,
527 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
528 RelocateInstMap) {
529 // Collect information in two maps: one primarily for locating the base object
530 // while filling the second map; the second map is the final structure holding
531 // a mapping between Base and corresponding Derived relocate calls
532 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
533 for (auto &U : AllRelocateCalls) {
534 GCRelocateOperands ThisRelocate(U);
535 IntrinsicInst *I = cast<IntrinsicInst>(U);
Sanjoy Das499d7032015-05-06 02:36:26 +0000536 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
537 ThisRelocate.getDerivedPtrIndex());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000538 RelocateIdxMap.insert(std::make_pair(K, I));
539 }
540 for (auto &Item : RelocateIdxMap) {
541 std::pair<unsigned, unsigned> Key = Item.first;
542 if (Key.first == Key.second)
543 // Base relocation: nothing to insert
544 continue;
545
546 IntrinsicInst *I = Item.second;
547 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000548
549 // We're iterating over RelocateIdxMap so we cannot modify it.
550 auto MaybeBase = RelocateIdxMap.find(BaseKey);
551 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000552 // TODO: We might want to insert a new base object relocate and gep off
553 // that, if there are enough derived object relocates.
554 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000555
556 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000557 }
558}
559
560// Accepts a GEP and extracts the operands into a vector provided they're all
561// small integer constants
562static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
563 SmallVectorImpl<Value *> &OffsetV) {
564 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
565 // Only accept small constant integer operands
566 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
567 if (!Op || Op->getZExtValue() > 20)
568 return false;
569 }
570
571 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
572 OffsetV.push_back(GEP->getOperand(i));
573 return true;
574}
575
576// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
577// replace, computes a replacement, and affects it.
578static bool
579simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
580 const SmallVectorImpl<IntrinsicInst *> &Targets) {
581 bool MadeChange = false;
582 for (auto &ToReplace : Targets) {
583 GCRelocateOperands MasterRelocate(RelocatedBase);
584 GCRelocateOperands ThisRelocate(ToReplace);
585
Sanjoy Das499d7032015-05-06 02:36:26 +0000586 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000587 "Not relocating a derived object of the original base object");
Sanjoy Das499d7032015-05-06 02:36:26 +0000588 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000589 // A duplicate relocate call. TODO: coalesce duplicates.
590 continue;
591 }
592
Sanjoy Das499d7032015-05-06 02:36:26 +0000593 Value *Base = ThisRelocate.getBasePtr();
594 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000595 if (!Derived || Derived->getPointerOperand() != Base)
596 continue;
597
598 SmallVector<Value *, 2> OffsetV;
599 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
600 continue;
601
602 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000603 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
604
605 // Insert after RelocatedBase
606 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000607 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000608
609 // If gc_relocate does not match the actual type, cast it to the right type.
610 // In theory, there must be a bitcast after gc_relocate if the type does not
611 // match, and we should reuse it to get the derived pointer. But it could be
612 // cases like this:
613 // bb1:
614 // ...
615 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
616 // br label %merge
617 //
618 // bb2:
619 // ...
620 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
621 // br label %merge
622 //
623 // merge:
624 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
625 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
626 //
627 // In this case, we can not find the bitcast any more. So we insert a new bitcast
628 // no matter there is already one or not. In this way, we can handle all cases, and
629 // the extra bitcast should be optimized away in later passes.
630 Instruction *ActualRelocatedBase = RelocatedBase;
631 if (RelocatedBase->getType() != Base->getType()) {
632 ActualRelocatedBase =
633 cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000634 }
David Blaikie68d535c2015-03-24 22:38:16 +0000635 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000636 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000637 Instruction *ReplacementInst = cast<Instruction>(Replacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000638 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000639 // If the newly generated derived pointer's type does not match the original derived
640 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
641 Instruction *ActualReplacement = ReplacementInst;
642 if (ReplacementInst->getType() != ToReplace->getType()) {
643 ActualReplacement =
644 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000645 }
646 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000647 ToReplace->eraseFromParent();
648
649 MadeChange = true;
650 }
651 return MadeChange;
652}
653
654// Turns this:
655//
656// %base = ...
657// %ptr = gep %base + 15
658// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
659// %base' = relocate(%tok, i32 4, i32 4)
660// %ptr' = relocate(%tok, i32 4, i32 5)
661// %val = load %ptr'
662//
663// into this:
664//
665// %base = ...
666// %ptr = gep %base + 15
667// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
668// %base' = gc.relocate(%tok, i32 4, i32 4)
669// %ptr' = gep %base' + 15
670// %val = load %ptr'
671bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
672 bool MadeChange = false;
673 SmallVector<User *, 2> AllRelocateCalls;
674
675 for (auto *U : I.users())
676 if (isGCRelocate(dyn_cast<Instruction>(U)))
677 // Collect all the relocate calls associated with a statepoint
678 AllRelocateCalls.push_back(U);
679
680 // We need atleast one base pointer relocation + one derived pointer
681 // relocation to mangle
682 if (AllRelocateCalls.size() < 2)
683 return false;
684
685 // RelocateInstMap is a mapping from the base relocate instruction to the
686 // corresponding derived relocate instructions
687 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
688 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
689 if (RelocateInstMap.empty())
690 return false;
691
692 for (auto &Item : RelocateInstMap)
693 // Item.first is the RelocatedBase to offset against
694 // Item.second is the vector of Targets to replace
695 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
696 return MadeChange;
697}
698
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000699/// SinkCast - Sink the specified cast instruction into its user blocks
700static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000701 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000702
Chris Lattnerf2836d12007-03-31 04:06:36 +0000703 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000704 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000705
Chris Lattnerf2836d12007-03-31 04:06:36 +0000706 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000707 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000708 UI != E; ) {
709 Use &TheUse = UI.getUse();
710 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000711
Chris Lattnerf2836d12007-03-31 04:06:36 +0000712 // Figure out which BB this cast is used in. For PHI's this is the
713 // appropriate predecessor block.
714 BasicBlock *UserBB = User->getParent();
715 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000716 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000717 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000718
Chris Lattnerf2836d12007-03-31 04:06:36 +0000719 // Preincrement use iterator so we don't invalidate it.
720 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000721
Chris Lattnerf2836d12007-03-31 04:06:36 +0000722 // If this user is in the same block as the cast, don't change the cast.
723 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000724
Chris Lattnerf2836d12007-03-31 04:06:36 +0000725 // If we have already inserted a cast into this block, use it.
726 CastInst *&InsertedCast = InsertedCasts[UserBB];
727
728 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000729 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000730 InsertedCast =
731 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000732 InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000733 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000734
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000735 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000736 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000737 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000738 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000739 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000740
Chris Lattnerf2836d12007-03-31 04:06:36 +0000741 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000742 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000743 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000744 MadeChange = true;
745 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000746
Chris Lattnerf2836d12007-03-31 04:06:36 +0000747 return MadeChange;
748}
749
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000750/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
751/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
752/// sink it into user blocks to reduce the number of virtual
753/// registers that must be created and coalesced.
754///
755/// Return true if any changes are made.
756///
Mehdi Amini44ede332015-07-09 02:09:04 +0000757static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
758 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000759 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000760 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
761 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000762
763 // This is an fp<->int conversion?
764 if (SrcVT.isInteger() != DstVT.isInteger())
765 return false;
766
767 // If this is an extension, it will be a zero or sign extension, which
768 // isn't a noop.
769 if (SrcVT.bitsLT(DstVT)) return false;
770
771 // If these values will be promoted, find out what they will be promoted
772 // to. This helps us consider truncates on PPC as noop copies when they
773 // are.
774 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
775 TargetLowering::TypePromoteInteger)
776 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
777 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
778 TargetLowering::TypePromoteInteger)
779 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
780
781 // If, after promotion, these are the same types, this is a noop copy.
782 if (SrcVT != DstVT)
783 return false;
784
785 return SinkCast(CI);
786}
787
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000788/// CombineUAddWithOverflow - try to combine CI into a call to the
789/// llvm.uadd.with.overflow intrinsic if possible.
790///
791/// Return true if any changes were made.
792static bool CombineUAddWithOverflow(CmpInst *CI) {
793 Value *A, *B;
794 Instruction *AddI;
795 if (!match(CI,
796 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
797 return false;
798
799 Type *Ty = AddI->getType();
800 if (!isa<IntegerType>(Ty))
801 return false;
802
803 // We don't want to move around uses of condition values this late, so we we
804 // check if it is legal to create the call to the intrinsic in the basic
805 // block containing the icmp:
806
807 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
808 return false;
809
810#ifndef NDEBUG
811 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
812 // for now:
813 if (AddI->hasOneUse())
814 assert(*AddI->user_begin() == CI && "expected!");
815#endif
816
817 Module *M = CI->getParent()->getParent()->getParent();
818 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
819
820 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
821
822 auto *UAddWithOverflow =
823 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
824 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
825 auto *Overflow =
826 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
827
828 CI->replaceAllUsesWith(Overflow);
829 AddI->replaceAllUsesWith(UAdd);
830 CI->eraseFromParent();
831 AddI->eraseFromParent();
832 return true;
833}
834
835/// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000836/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000837/// a clear win except on targets with multiple condition code registers
838/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000839///
840/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000841static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000842 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000843
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000844 /// InsertedCmp - Only insert a cmp in each block once.
845 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000846
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000847 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000848 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000849 UI != E; ) {
850 Use &TheUse = UI.getUse();
851 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000852
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000853 // Preincrement use iterator so we don't invalidate it.
854 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000855
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000856 // Don't bother for PHI nodes.
857 if (isa<PHINode>(User))
858 continue;
859
860 // Figure out which BB this cmp is used in.
861 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000862
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000863 // If this user is in the same block as the cmp, don't change the cmp.
864 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000865
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000866 // If we have already inserted a cmp into this block, use it.
867 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
868
869 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000870 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000871 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000872 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000873 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000874 CI->getOperand(1), "", InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000875 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000876
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000877 // Replace a use of the cmp with a use of the new cmp.
878 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000879 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000880 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000881 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000882
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000883 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000884 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000885 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000886 MadeChange = true;
887 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000888
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000889 return MadeChange;
890}
891
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000892static bool OptimizeCmpExpression(CmpInst *CI) {
893 if (SinkCmpExpression(CI))
894 return true;
895
896 if (CombineUAddWithOverflow(CI))
897 return true;
898
899 return false;
900}
901
Yi Jiangd069f632014-04-21 19:34:27 +0000902/// isExtractBitsCandidateUse - Check if the candidates could
903/// be combined with shift instruction, which includes:
904/// 1. Truncate instruction
905/// 2. And instruction and the imm is a mask of the low bits:
906/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000907static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000908 if (!isa<TruncInst>(User)) {
909 if (User->getOpcode() != Instruction::And ||
910 !isa<ConstantInt>(User->getOperand(1)))
911 return false;
912
Quentin Colombetd4f44692014-04-22 01:20:34 +0000913 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000914
Quentin Colombetd4f44692014-04-22 01:20:34 +0000915 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000916 return false;
917 }
918 return true;
919}
920
921/// SinkShiftAndTruncate - sink both shift and truncate instruction
922/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000923static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000924SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
925 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000926 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000927 BasicBlock *UserBB = User->getParent();
928 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
929 TruncInst *TruncI = dyn_cast<TruncInst>(User);
930 bool MadeChange = false;
931
932 for (Value::user_iterator TruncUI = TruncI->user_begin(),
933 TruncE = TruncI->user_end();
934 TruncUI != TruncE;) {
935
936 Use &TruncTheUse = TruncUI.getUse();
937 Instruction *TruncUser = cast<Instruction>(*TruncUI);
938 // Preincrement use iterator so we don't invalidate it.
939
940 ++TruncUI;
941
942 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
943 if (!ISDOpcode)
944 continue;
945
Tim Northovere2239ff2014-07-29 10:20:22 +0000946 // If the use is actually a legal node, there will not be an
947 // implicit truncate.
948 // FIXME: always querying the result type is just an
949 // approximation; some nodes' legality is determined by the
950 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000951 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000952 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000953 continue;
954
955 // Don't bother for PHI nodes.
956 if (isa<PHINode>(TruncUser))
957 continue;
958
959 BasicBlock *TruncUserBB = TruncUser->getParent();
960
961 if (UserBB == TruncUserBB)
962 continue;
963
964 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
965 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
966
967 if (!InsertedShift && !InsertedTrunc) {
968 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
969 // Sink the shift
970 if (ShiftI->getOpcode() == Instruction::AShr)
971 InsertedShift =
972 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
973 else
974 InsertedShift =
975 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
976
977 // Sink the trunc
978 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
979 TruncInsertPt++;
980
981 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
982 TruncI->getType(), "", TruncInsertPt);
983
984 MadeChange = true;
985
986 TruncTheUse = InsertedTrunc;
987 }
988 }
989 return MadeChange;
990}
991
992/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
993/// the uses could potentially be combined with this shift instruction and
994/// generate BitExtract instruction. It will only be applied if the architecture
995/// supports BitExtract instruction. Here is an example:
996/// BB1:
997/// %x.extract.shift = lshr i64 %arg1, 32
998/// BB2:
999/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1000/// ==>
1001///
1002/// BB2:
1003/// %x.extract.shift.1 = lshr i64 %arg1, 32
1004/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1005///
1006/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1007/// instruction.
1008/// Return true if any changes are made.
1009static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001010 const TargetLowering &TLI,
1011 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001012 BasicBlock *DefBB = ShiftI->getParent();
1013
1014 /// Only insert instructions in each block once.
1015 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1016
Mehdi Amini44ede332015-07-09 02:09:04 +00001017 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001018
1019 bool MadeChange = false;
1020 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1021 UI != E;) {
1022 Use &TheUse = UI.getUse();
1023 Instruction *User = cast<Instruction>(*UI);
1024 // Preincrement use iterator so we don't invalidate it.
1025 ++UI;
1026
1027 // Don't bother for PHI nodes.
1028 if (isa<PHINode>(User))
1029 continue;
1030
1031 if (!isExtractBitsCandidateUse(User))
1032 continue;
1033
1034 BasicBlock *UserBB = User->getParent();
1035
1036 if (UserBB == DefBB) {
1037 // If the shift and truncate instruction are in the same BB. The use of
1038 // the truncate(TruncUse) may still introduce another truncate if not
1039 // legal. In this case, we would like to sink both shift and truncate
1040 // instruction to the BB of TruncUse.
1041 // for example:
1042 // BB1:
1043 // i64 shift.result = lshr i64 opnd, imm
1044 // trunc.result = trunc shift.result to i16
1045 //
1046 // BB2:
1047 // ----> We will have an implicit truncate here if the architecture does
1048 // not have i16 compare.
1049 // cmp i16 trunc.result, opnd2
1050 //
1051 if (isa<TruncInst>(User) && shiftIsLegal
1052 // If the type of the truncate is legal, no trucate will be
1053 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001054 &&
1055 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001056 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001057 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001058
1059 continue;
1060 }
1061 // If we have already inserted a shift into this block, use it.
1062 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1063
1064 if (!InsertedShift) {
1065 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1066
1067 if (ShiftI->getOpcode() == Instruction::AShr)
1068 InsertedShift =
1069 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
1070 else
1071 InsertedShift =
1072 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
1073
1074 MadeChange = true;
1075 }
1076
1077 // Replace a use of the shift with a use of the new shift.
1078 TheUse = InsertedShift;
1079 }
1080
1081 // If we removed all uses, nuke the shift.
1082 if (ShiftI->use_empty())
1083 ShiftI->eraseFromParent();
1084
1085 return MadeChange;
1086}
1087
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001088// ScalarizeMaskedLoad() translates masked load intrinsic, like
1089// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1090// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001091// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001092// the appropriate mask bit is set
1093//
1094// %1 = bitcast i8* %addr to i32*
1095// %2 = extractelement <16 x i1> %mask, i32 0
1096// %3 = icmp eq i1 %2, true
1097// br i1 %3, label %cond.load, label %else
1098//
1099//cond.load: ; preds = %0
1100// %4 = getelementptr i32* %1, i32 0
1101// %5 = load i32* %4
1102// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1103// br label %else
1104//
1105//else: ; preds = %0, %cond.load
1106// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1107// %7 = extractelement <16 x i1> %mask, i32 1
1108// %8 = icmp eq i1 %7, true
1109// br i1 %8, label %cond.load1, label %else2
1110//
1111//cond.load1: ; preds = %else
1112// %9 = getelementptr i32* %1, i32 1
1113// %10 = load i32* %9
1114// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1115// br label %else2
1116//
1117//else2: ; preds = %else, %cond.load1
1118// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1119// %12 = extractelement <16 x i1> %mask, i32 2
1120// %13 = icmp eq i1 %12, true
1121// br i1 %13, label %cond.load4, label %else5
1122//
1123static void ScalarizeMaskedLoad(CallInst *CI) {
1124 Value *Ptr = CI->getArgOperand(0);
1125 Value *Src0 = CI->getArgOperand(3);
1126 Value *Mask = CI->getArgOperand(2);
1127 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1128 Type *EltTy = VecType->getElementType();
1129
1130 assert(VecType && "Unexpected return type of masked load intrinsic");
1131
1132 IRBuilder<> Builder(CI->getContext());
1133 Instruction *InsertPt = CI;
1134 BasicBlock *IfBlock = CI->getParent();
1135 BasicBlock *CondBlock = nullptr;
1136 BasicBlock *PrevIfBlock = CI->getParent();
1137 Builder.SetInsertPoint(InsertPt);
1138
1139 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1140
1141 // Bitcast %addr fron i8* to EltTy*
1142 Type *NewPtrType =
1143 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1144 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1145 Value *UndefVal = UndefValue::get(VecType);
1146
1147 // The result vector
1148 Value *VResult = UndefVal;
1149
1150 PHINode *Phi = nullptr;
1151 Value *PrevPhi = UndefVal;
1152
1153 unsigned VectorWidth = VecType->getNumElements();
1154 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1155
1156 // Fill the "else" block, created in the previous iteration
1157 //
1158 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1159 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1160 // %to_load = icmp eq i1 %mask_1, true
1161 // br i1 %to_load, label %cond.load, label %else
1162 //
1163 if (Idx > 0) {
1164 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1165 Phi->addIncoming(VResult, CondBlock);
1166 Phi->addIncoming(PrevPhi, PrevIfBlock);
1167 PrevPhi = Phi;
1168 VResult = Phi;
1169 }
1170
1171 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1172 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1173 ConstantInt::get(Predicate->getType(), 1));
1174
1175 // Create "cond" block
1176 //
1177 // %EltAddr = getelementptr i32* %1, i32 0
1178 // %Elt = load i32* %EltAddr
1179 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1180 //
1181 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1182 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001183
1184 Value *Gep =
1185 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001186 LoadInst* Load = Builder.CreateLoad(Gep, false);
1187 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1188
1189 // Create "else" block, fill it in the next iteration
1190 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1191 Builder.SetInsertPoint(InsertPt);
1192 Instruction *OldBr = IfBlock->getTerminator();
1193 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1194 OldBr->eraseFromParent();
1195 PrevIfBlock = IfBlock;
1196 IfBlock = NewIfBlock;
1197 }
1198
1199 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1200 Phi->addIncoming(VResult, CondBlock);
1201 Phi->addIncoming(PrevPhi, PrevIfBlock);
1202 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1203 CI->replaceAllUsesWith(NewI);
1204 CI->eraseFromParent();
1205}
1206
1207// ScalarizeMaskedStore() translates masked store intrinsic, like
1208// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1209// <16 x i1> %mask)
1210// to a chain of basic blocks, that stores element one-by-one if
1211// the appropriate mask bit is set
1212//
1213// %1 = bitcast i8* %addr to i32*
1214// %2 = extractelement <16 x i1> %mask, i32 0
1215// %3 = icmp eq i1 %2, true
1216// br i1 %3, label %cond.store, label %else
1217//
1218// cond.store: ; preds = %0
1219// %4 = extractelement <16 x i32> %val, i32 0
1220// %5 = getelementptr i32* %1, i32 0
1221// store i32 %4, i32* %5
1222// br label %else
1223//
1224// else: ; preds = %0, %cond.store
1225// %6 = extractelement <16 x i1> %mask, i32 1
1226// %7 = icmp eq i1 %6, true
1227// br i1 %7, label %cond.store1, label %else2
1228//
1229// cond.store1: ; preds = %else
1230// %8 = extractelement <16 x i32> %val, i32 1
1231// %9 = getelementptr i32* %1, i32 1
1232// store i32 %8, i32* %9
1233// br label %else2
1234// . . .
1235static void ScalarizeMaskedStore(CallInst *CI) {
1236 Value *Ptr = CI->getArgOperand(1);
1237 Value *Src = CI->getArgOperand(0);
1238 Value *Mask = CI->getArgOperand(3);
1239
1240 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1241 Type *EltTy = VecType->getElementType();
1242
1243 assert(VecType && "Unexpected data type in masked store intrinsic");
1244
1245 IRBuilder<> Builder(CI->getContext());
1246 Instruction *InsertPt = CI;
1247 BasicBlock *IfBlock = CI->getParent();
1248 Builder.SetInsertPoint(InsertPt);
1249 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1250
1251 // Bitcast %addr fron i8* to EltTy*
1252 Type *NewPtrType =
1253 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1254 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1255
1256 unsigned VectorWidth = VecType->getNumElements();
1257 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1258
1259 // Fill the "else" block, created in the previous iteration
1260 //
1261 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1262 // %to_store = icmp eq i1 %mask_1, true
1263 // br i1 %to_load, label %cond.store, label %else
1264 //
1265 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1266 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1267 ConstantInt::get(Predicate->getType(), 1));
1268
1269 // Create "cond" block
1270 //
1271 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1272 // %EltAddr = getelementptr i32* %1, i32 0
1273 // %store i32 %OneElt, i32* %EltAddr
1274 //
1275 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1276 Builder.SetInsertPoint(InsertPt);
1277
1278 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001279 Value *Gep =
1280 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001281 Builder.CreateStore(OneElt, Gep);
1282
1283 // Create "else" block, fill it in the next iteration
1284 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1285 Builder.SetInsertPoint(InsertPt);
1286 Instruction *OldBr = IfBlock->getTerminator();
1287 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1288 OldBr->eraseFromParent();
1289 IfBlock = NewIfBlock;
1290 }
1291 CI->eraseFromParent();
1292}
1293
1294bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001295 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001296
Chris Lattner7a277142011-01-15 07:14:54 +00001297 // Lower inline assembly if we can.
1298 // If we found an inline asm expession, and if the target knows how to
1299 // lower it to normal LLVM code, do so now.
1300 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1301 if (TLI->ExpandInlineAsm(CI)) {
1302 // Avoid invalidating the iterator.
1303 CurInstIterator = BB->begin();
1304 // Avoid processing instructions out of order, which could cause
1305 // reuse before a value is defined.
1306 SunkAddrs.clear();
1307 return true;
1308 }
1309 // Sink address computing for memory operands into the block.
1310 if (OptimizeInlineAsmInst(CI))
1311 return true;
1312 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001313
John Brawn0dbcd652015-03-18 12:01:59 +00001314 // Align the pointer arguments to this call if the target thinks it's a good
1315 // idea
1316 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001317 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001318 for (auto &Arg : CI->arg_operands()) {
1319 // We want to align both objects whose address is used directly and
1320 // objects whose address is used in casts and GEPs, though it only makes
1321 // sense for GEPs if the offset is a multiple of the desired alignment and
1322 // if size - offset meets the size threshold.
1323 if (!Arg->getType()->isPointerTy())
1324 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001325 APInt Offset(DL->getPointerSizeInBits(
1326 cast<PointerType>(Arg->getType())->getAddressSpace()),
1327 0);
1328 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001329 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001330 if ((Offset2 & (PrefAlign-1)) != 0)
1331 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001332 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001333 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1334 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001335 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001336 // Global variables can only be aligned if they are defined in this
1337 // object (i.e. they are uniquely initialized in this object), and
1338 // over-aligning global variables that have an explicit section is
1339 // forbidden.
1340 GlobalVariable *GV;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001341 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1342 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1343 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1344 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001345 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001346 }
1347 // If this is a memcpy (or similar) then we may be able to improve the
1348 // alignment
1349 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001350 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001351 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001352 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
John Brawn0dbcd652015-03-18 12:01:59 +00001353 if (Align > MI->getAlignment())
1354 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1355 }
1356 }
1357
Eric Christopher4b7948e2010-03-11 02:41:03 +00001358 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001359 if (II) {
1360 switch (II->getIntrinsicID()) {
1361 default: break;
1362 case Intrinsic::objectsize: {
1363 // Lower all uses of llvm.objectsize.*
1364 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1365 Type *ReturnTy = CI->getType();
1366 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001367
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001368 // Substituting this can cause recursive simplifications, which can
1369 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1370 // happens.
1371 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001372
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001373 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001374 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001375
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001376 // If the iterator instruction was recursively deleted, start over at the
1377 // start of the block.
1378 if (IterHandle != CurInstIterator) {
1379 CurInstIterator = BB->begin();
1380 SunkAddrs.clear();
1381 }
1382 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001383 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001384 case Intrinsic::masked_load: {
1385 // Scalarize unsupported vector masked load
1386 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1387 ScalarizeMaskedLoad(CI);
1388 ModifiedDT = true;
1389 return true;
1390 }
1391 return false;
1392 }
1393 case Intrinsic::masked_store: {
1394 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1395 ScalarizeMaskedStore(CI);
1396 ModifiedDT = true;
1397 return true;
1398 }
1399 return false;
1400 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001401 case Intrinsic::aarch64_stlxr:
1402 case Intrinsic::aarch64_stxr: {
1403 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1404 if (!ExtVal || !ExtVal->hasOneUse() ||
1405 ExtVal->getParent() == CI->getParent())
1406 return false;
1407 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1408 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001409 // Mark this instruction as "inserted by CGP", so that other
1410 // optimizations don't touch it.
1411 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001412 return true;
1413 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001414 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001415
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001416 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001417 // Unknown address space.
1418 // TODO: Target hook to pick which address space the intrinsic cares
1419 // about?
1420 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001421 SmallVector<Value*, 2> PtrOps;
1422 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001423 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001424 while (!PtrOps.empty())
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001425 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001426 return true;
1427 }
Pete Cooper615fd892012-03-13 20:59:56 +00001428 }
1429
Eric Christopher4b7948e2010-03-11 02:41:03 +00001430 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001431 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001432
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001433 // Lower all default uses of _chk calls. This is very similar
1434 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001435 // to fortified library functions (e.g. __memcpy_chk) that have the default
1436 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001437 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001438 if (Value *V = Simplifier.optimizeCall(CI)) {
1439 CI->replaceAllUsesWith(V);
1440 CI->eraseFromParent();
1441 return true;
1442 }
1443 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001444}
Chris Lattner1b93be52011-01-15 07:25:29 +00001445
Evan Cheng0663f232011-03-21 01:19:09 +00001446/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1447/// instructions to the predecessor to enable tail call optimizations. The
1448/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001449/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001450/// bb0:
1451/// %tmp0 = tail call i32 @f0()
1452/// br label %return
1453/// bb1:
1454/// %tmp1 = tail call i32 @f1()
1455/// br label %return
1456/// bb2:
1457/// %tmp2 = tail call i32 @f2()
1458/// br label %return
1459/// return:
1460/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1461/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001462/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001463///
1464/// =>
1465///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001466/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001467/// bb0:
1468/// %tmp0 = tail call i32 @f0()
1469/// ret i32 %tmp0
1470/// bb1:
1471/// %tmp1 = tail call i32 @f1()
1472/// ret i32 %tmp1
1473/// bb2:
1474/// %tmp2 = tail call i32 @f2()
1475/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001476/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +00001477bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001478 if (!TLI)
1479 return false;
1480
Benjamin Kramer455fa352012-11-23 19:17:06 +00001481 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1482 if (!RI)
1483 return false;
1484
Craig Topperc0196b12014-04-14 00:51:57 +00001485 PHINode *PN = nullptr;
1486 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001487 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001488 if (V) {
1489 BCI = dyn_cast<BitCastInst>(V);
1490 if (BCI)
1491 V = BCI->getOperand(0);
1492
1493 PN = dyn_cast<PHINode>(V);
1494 if (!PN)
1495 return false;
1496 }
Evan Cheng0663f232011-03-21 01:19:09 +00001497
Cameron Zwarich4649f172011-03-24 04:52:10 +00001498 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001499 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001500
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001501 // It's not safe to eliminate the sign / zero extension of the return value.
1502 // See llvm::isInTailCallPosition().
1503 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001504 AttributeSet CallerAttrs = F->getAttributes();
1505 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1506 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001507 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001508
Cameron Zwarich4649f172011-03-24 04:52:10 +00001509 // Make sure there are no instructions between the PHI and return, or that the
1510 // return is the first instruction in the block.
1511 if (PN) {
1512 BasicBlock::iterator BI = BB->begin();
1513 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001514 if (&*BI == BCI)
1515 // Also skip over the bitcast.
1516 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001517 if (&*BI != RI)
1518 return false;
1519 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001520 BasicBlock::iterator BI = BB->begin();
1521 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1522 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001523 return false;
1524 }
Evan Cheng0663f232011-03-21 01:19:09 +00001525
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001526 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1527 /// call.
1528 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001529 if (PN) {
1530 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1531 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1532 // Make sure the phi value is indeed produced by the tail call.
1533 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1534 TLI->mayBeEmittedAsTailCall(CI))
1535 TailCalls.push_back(CI);
1536 }
1537 } else {
1538 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001539 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001540 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001541 continue;
1542
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001543 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001544 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1545 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001546 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1547 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001548 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001549
Cameron Zwarich4649f172011-03-24 04:52:10 +00001550 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001551 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001552 TailCalls.push_back(CI);
1553 }
Evan Cheng0663f232011-03-21 01:19:09 +00001554 }
1555
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001556 bool Changed = false;
1557 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1558 CallInst *CI = TailCalls[i];
1559 CallSite CS(CI);
1560
1561 // Conservatively require the attributes of the call to match those of the
1562 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001563 AttributeSet CalleeAttrs = CS.getAttributes();
1564 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001565 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001566 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001567 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001568 continue;
1569
1570 // Make sure the call instruction is followed by an unconditional branch to
1571 // the return block.
1572 BasicBlock *CallBB = CI->getParent();
1573 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1574 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1575 continue;
1576
1577 // Duplicate the return into CallBB.
1578 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001579 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001580 ++NumRetsDup;
1581 }
1582
1583 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001584 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001585 BB->eraseFromParent();
1586
1587 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001588}
1589
Chris Lattner728f9022008-11-25 07:09:13 +00001590//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001591// Memory Optimization
1592//===----------------------------------------------------------------------===//
1593
Chandler Carruthc8925912013-01-05 02:09:22 +00001594namespace {
1595
1596/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1597/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001598struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001599 Value *BaseReg;
1600 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001601 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001602 void print(raw_ostream &OS) const;
1603 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001604
Chandler Carruthc8925912013-01-05 02:09:22 +00001605 bool operator==(const ExtAddrMode& O) const {
1606 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1607 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1608 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1609 }
1610};
1611
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001612#ifndef NDEBUG
1613static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1614 AM.print(OS);
1615 return OS;
1616}
1617#endif
1618
Chandler Carruthc8925912013-01-05 02:09:22 +00001619void ExtAddrMode::print(raw_ostream &OS) const {
1620 bool NeedPlus = false;
1621 OS << "[";
1622 if (BaseGV) {
1623 OS << (NeedPlus ? " + " : "")
1624 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001625 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001626 NeedPlus = true;
1627 }
1628
Richard Trieuc0f91212014-05-30 03:15:17 +00001629 if (BaseOffs) {
1630 OS << (NeedPlus ? " + " : "")
1631 << BaseOffs;
1632 NeedPlus = true;
1633 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001634
1635 if (BaseReg) {
1636 OS << (NeedPlus ? " + " : "")
1637 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001638 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001639 NeedPlus = true;
1640 }
1641 if (Scale) {
1642 OS << (NeedPlus ? " + " : "")
1643 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001644 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001645 }
1646
1647 OS << ']';
1648}
1649
1650#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1651void ExtAddrMode::dump() const {
1652 print(dbgs());
1653 dbgs() << '\n';
1654}
1655#endif
1656
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001657/// \brief This class provides transaction based operation on the IR.
1658/// Every change made through this class is recorded in the internal state and
1659/// can be undone (rollback) until commit is called.
1660class TypePromotionTransaction {
1661
1662 /// \brief This represents the common interface of the individual transaction.
1663 /// Each class implements the logic for doing one specific modification on
1664 /// the IR via the TypePromotionTransaction.
1665 class TypePromotionAction {
1666 protected:
1667 /// The Instruction modified.
1668 Instruction *Inst;
1669
1670 public:
1671 /// \brief Constructor of the action.
1672 /// The constructor performs the related action on the IR.
1673 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1674
1675 virtual ~TypePromotionAction() {}
1676
1677 /// \brief Undo the modification done by this action.
1678 /// When this method is called, the IR must be in the same state as it was
1679 /// before this action was applied.
1680 /// \pre Undoing the action works if and only if the IR is in the exact same
1681 /// state as it was directly after this action was applied.
1682 virtual void undo() = 0;
1683
1684 /// \brief Advocate every change made by this action.
1685 /// When the results on the IR of the action are to be kept, it is important
1686 /// to call this function, otherwise hidden information may be kept forever.
1687 virtual void commit() {
1688 // Nothing to be done, this action is not doing anything.
1689 }
1690 };
1691
1692 /// \brief Utility to remember the position of an instruction.
1693 class InsertionHandler {
1694 /// Position of an instruction.
1695 /// Either an instruction:
1696 /// - Is the first in a basic block: BB is used.
1697 /// - Has a previous instructon: PrevInst is used.
1698 union {
1699 Instruction *PrevInst;
1700 BasicBlock *BB;
1701 } Point;
1702 /// Remember whether or not the instruction had a previous instruction.
1703 bool HasPrevInstruction;
1704
1705 public:
1706 /// \brief Record the position of \p Inst.
1707 InsertionHandler(Instruction *Inst) {
1708 BasicBlock::iterator It = Inst;
1709 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1710 if (HasPrevInstruction)
1711 Point.PrevInst = --It;
1712 else
1713 Point.BB = Inst->getParent();
1714 }
1715
1716 /// \brief Insert \p Inst at the recorded position.
1717 void insert(Instruction *Inst) {
1718 if (HasPrevInstruction) {
1719 if (Inst->getParent())
1720 Inst->removeFromParent();
1721 Inst->insertAfter(Point.PrevInst);
1722 } else {
1723 Instruction *Position = Point.BB->getFirstInsertionPt();
1724 if (Inst->getParent())
1725 Inst->moveBefore(Position);
1726 else
1727 Inst->insertBefore(Position);
1728 }
1729 }
1730 };
1731
1732 /// \brief Move an instruction before another.
1733 class InstructionMoveBefore : public TypePromotionAction {
1734 /// Original position of the instruction.
1735 InsertionHandler Position;
1736
1737 public:
1738 /// \brief Move \p Inst before \p Before.
1739 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1740 : TypePromotionAction(Inst), Position(Inst) {
1741 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1742 Inst->moveBefore(Before);
1743 }
1744
1745 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001746 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001747 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1748 Position.insert(Inst);
1749 }
1750 };
1751
1752 /// \brief Set the operand of an instruction with a new value.
1753 class OperandSetter : public TypePromotionAction {
1754 /// Original operand of the instruction.
1755 Value *Origin;
1756 /// Index of the modified instruction.
1757 unsigned Idx;
1758
1759 public:
1760 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1761 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1762 : TypePromotionAction(Inst), Idx(Idx) {
1763 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1764 << "for:" << *Inst << "\n"
1765 << "with:" << *NewVal << "\n");
1766 Origin = Inst->getOperand(Idx);
1767 Inst->setOperand(Idx, NewVal);
1768 }
1769
1770 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001771 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001772 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1773 << "for: " << *Inst << "\n"
1774 << "with: " << *Origin << "\n");
1775 Inst->setOperand(Idx, Origin);
1776 }
1777 };
1778
1779 /// \brief Hide the operands of an instruction.
1780 /// Do as if this instruction was not using any of its operands.
1781 class OperandsHider : public TypePromotionAction {
1782 /// The list of original operands.
1783 SmallVector<Value *, 4> OriginalValues;
1784
1785 public:
1786 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1787 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1788 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1789 unsigned NumOpnds = Inst->getNumOperands();
1790 OriginalValues.reserve(NumOpnds);
1791 for (unsigned It = 0; It < NumOpnds; ++It) {
1792 // Save the current operand.
1793 Value *Val = Inst->getOperand(It);
1794 OriginalValues.push_back(Val);
1795 // Set a dummy one.
1796 // We could use OperandSetter here, but that would implied an overhead
1797 // that we are not willing to pay.
1798 Inst->setOperand(It, UndefValue::get(Val->getType()));
1799 }
1800 }
1801
1802 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001803 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001804 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1805 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1806 Inst->setOperand(It, OriginalValues[It]);
1807 }
1808 };
1809
1810 /// \brief Build a truncate instruction.
1811 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001812 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001813 public:
1814 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1815 /// result.
1816 /// trunc Opnd to Ty.
1817 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1818 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001819 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1820 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001821 }
1822
Quentin Colombetac55b152014-09-16 22:36:07 +00001823 /// \brief Get the built value.
1824 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001825
1826 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001827 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001828 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1829 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1830 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001831 }
1832 };
1833
1834 /// \brief Build a sign extension instruction.
1835 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001836 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001837 public:
1838 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1839 /// result.
1840 /// sext Opnd to Ty.
1841 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001842 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001843 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001844 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1845 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001846 }
1847
Quentin Colombetac55b152014-09-16 22:36:07 +00001848 /// \brief Get the built value.
1849 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001850
1851 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001852 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001853 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1854 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1855 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001856 }
1857 };
1858
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001859 /// \brief Build a zero extension instruction.
1860 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001861 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001862 public:
1863 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1864 /// result.
1865 /// zext Opnd to Ty.
1866 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001867 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001868 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001869 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1870 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001871 }
1872
Quentin Colombetac55b152014-09-16 22:36:07 +00001873 /// \brief Get the built value.
1874 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001875
1876 /// \brief Remove the built instruction.
1877 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001878 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1879 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1880 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001881 }
1882 };
1883
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001884 /// \brief Mutate an instruction to another type.
1885 class TypeMutator : public TypePromotionAction {
1886 /// Record the original type.
1887 Type *OrigTy;
1888
1889 public:
1890 /// \brief Mutate the type of \p Inst into \p NewTy.
1891 TypeMutator(Instruction *Inst, Type *NewTy)
1892 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1893 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1894 << "\n");
1895 Inst->mutateType(NewTy);
1896 }
1897
1898 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001899 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001900 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1901 << "\n");
1902 Inst->mutateType(OrigTy);
1903 }
1904 };
1905
1906 /// \brief Replace the uses of an instruction by another instruction.
1907 class UsesReplacer : public TypePromotionAction {
1908 /// Helper structure to keep track of the replaced uses.
1909 struct InstructionAndIdx {
1910 /// The instruction using the instruction.
1911 Instruction *Inst;
1912 /// The index where this instruction is used for Inst.
1913 unsigned Idx;
1914 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1915 : Inst(Inst), Idx(Idx) {}
1916 };
1917
1918 /// Keep track of the original uses (pair Instruction, Index).
1919 SmallVector<InstructionAndIdx, 4> OriginalUses;
1920 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1921
1922 public:
1923 /// \brief Replace all the use of \p Inst by \p New.
1924 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1925 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1926 << "\n");
1927 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001928 for (Use &U : Inst->uses()) {
1929 Instruction *UserI = cast<Instruction>(U.getUser());
1930 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001931 }
1932 // Now, we can replace the uses.
1933 Inst->replaceAllUsesWith(New);
1934 }
1935
1936 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001937 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001938 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1939 for (use_iterator UseIt = OriginalUses.begin(),
1940 EndIt = OriginalUses.end();
1941 UseIt != EndIt; ++UseIt) {
1942 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1943 }
1944 }
1945 };
1946
1947 /// \brief Remove an instruction from the IR.
1948 class InstructionRemover : public TypePromotionAction {
1949 /// Original position of the instruction.
1950 InsertionHandler Inserter;
1951 /// Helper structure to hide all the link to the instruction. In other
1952 /// words, this helps to do as if the instruction was removed.
1953 OperandsHider Hider;
1954 /// Keep track of the uses replaced, if any.
1955 UsesReplacer *Replacer;
1956
1957 public:
1958 /// \brief Remove all reference of \p Inst and optinally replace all its
1959 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001960 /// \pre If !Inst->use_empty(), then New != nullptr
1961 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001962 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001963 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001964 if (New)
1965 Replacer = new UsesReplacer(Inst, New);
1966 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1967 Inst->removeFromParent();
1968 }
1969
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00001970 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001971
1972 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001973 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001974
1975 /// \brief Resurrect the instruction and reassign it to the proper uses if
1976 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001977 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001978 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1979 Inserter.insert(Inst);
1980 if (Replacer)
1981 Replacer->undo();
1982 Hider.undo();
1983 }
1984 };
1985
1986public:
1987 /// Restoration point.
1988 /// The restoration point is a pointer to an action instead of an iterator
1989 /// because the iterator may be invalidated but not the pointer.
1990 typedef const TypePromotionAction *ConstRestorationPt;
1991 /// Advocate every changes made in that transaction.
1992 void commit();
1993 /// Undo all the changes made after the given point.
1994 void rollback(ConstRestorationPt Point);
1995 /// Get the current restoration point.
1996 ConstRestorationPt getRestorationPoint() const;
1997
1998 /// \name API for IR modification with state keeping to support rollback.
1999 /// @{
2000 /// Same as Instruction::setOperand.
2001 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2002 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002003 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002004 /// Same as Value::replaceAllUsesWith.
2005 void replaceAllUsesWith(Instruction *Inst, Value *New);
2006 /// Same as Value::mutateType.
2007 void mutateType(Instruction *Inst, Type *NewTy);
2008 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002009 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002010 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002011 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002012 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002013 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002014 /// Same as Instruction::moveBefore.
2015 void moveBefore(Instruction *Inst, Instruction *Before);
2016 /// @}
2017
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002018private:
2019 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002020 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2021 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002022};
2023
2024void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2025 Value *NewVal) {
2026 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002027 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002028}
2029
2030void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2031 Value *NewVal) {
2032 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002033 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002034}
2035
2036void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2037 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002038 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002039}
2040
2041void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002042 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002043}
2044
Quentin Colombetac55b152014-09-16 22:36:07 +00002045Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2046 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002047 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002048 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002049 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002050 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002051}
2052
Quentin Colombetac55b152014-09-16 22:36:07 +00002053Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2054 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002055 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002056 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002057 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002058 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002059}
2060
Quentin Colombetac55b152014-09-16 22:36:07 +00002061Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2062 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002063 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002064 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002065 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002066 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002067}
2068
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002069void TypePromotionTransaction::moveBefore(Instruction *Inst,
2070 Instruction *Before) {
2071 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002072 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002073}
2074
2075TypePromotionTransaction::ConstRestorationPt
2076TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002077 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002078}
2079
2080void TypePromotionTransaction::commit() {
2081 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002082 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002083 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002084 Actions.clear();
2085}
2086
2087void TypePromotionTransaction::rollback(
2088 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002089 while (!Actions.empty() && Point != Actions.back().get()) {
2090 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002091 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002092 }
2093}
2094
Chandler Carruthc8925912013-01-05 02:09:22 +00002095/// \brief A helper class for matching addressing modes.
2096///
2097/// This encapsulates the logic for matching the target-legal addressing modes.
2098class AddressingModeMatcher {
2099 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002100 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002101 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002102 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002103
2104 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2105 /// the memory instruction that we're computing this address for.
2106 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002107 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002108 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002109
Chandler Carruthc8925912013-01-05 02:09:22 +00002110 /// AddrMode - This is the addressing mode that we're building up. This is
2111 /// part of the return value of this addressing mode matching stuff.
2112 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002113
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002114 /// The instructions inserted by other CodeGenPrepare optimizations.
2115 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002116 /// A map from the instructions to their type before promotion.
2117 InstrToOrigTy &PromotedInsts;
2118 /// The ongoing transaction where every action should be registered.
2119 TypePromotionTransaction &TPT;
2120
Chandler Carruthc8925912013-01-05 02:09:22 +00002121 /// IgnoreProfitability - This is set to true when we should not do
2122 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
2123 /// always returns true.
2124 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002125
Eric Christopherd75c00c2015-02-26 22:38:34 +00002126 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002127 const TargetMachine &TM, Type *AT, unsigned AS,
2128 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002129 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002130 InstrToOrigTy &PromotedInsts,
2131 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002132 : AddrModeInsts(AMI), TM(TM),
2133 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2134 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002135 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2136 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2137 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002138 IgnoreProfitability = false;
2139 }
2140public:
Stephen Lin837bba12013-07-15 17:55:02 +00002141
Chandler Carruthc8925912013-01-05 02:09:22 +00002142 /// Match - Find the maximal addressing mode that a load/store of V can fold,
2143 /// give an access type of AccessTy. This returns a list of involved
2144 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002145 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002146 /// optimizations.
2147 /// \p PromotedInsts maps the instructions to their type before promotion.
2148 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002149 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002150 Instruction *MemoryInst,
2151 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002152 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002153 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002154 InstrToOrigTy &PromotedInsts,
2155 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002156 ExtAddrMode Result;
2157
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002158 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002159 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002160 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002161 (void)Success; assert(Success && "Couldn't select *anything*?");
2162 return Result;
2163 }
2164private:
2165 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2166 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002167 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002168 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00002169 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
2170 ExtAddrMode &AMBefore,
2171 ExtAddrMode &AMAfter);
2172 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002173 bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002174 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002175};
2176
2177/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
2178/// Return true and update AddrMode if this addr mode is legal for the target,
2179/// false if not.
2180bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
2181 unsigned Depth) {
2182 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2183 // mode. Just process that directly.
2184 if (Scale == 1)
2185 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002186
Chandler Carruthc8925912013-01-05 02:09:22 +00002187 // If the scale is 0, it takes nothing to add this.
2188 if (Scale == 0)
2189 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002190
Chandler Carruthc8925912013-01-05 02:09:22 +00002191 // If we already have a scale of this value, we can add to it, otherwise, we
2192 // need an available scale field.
2193 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2194 return false;
2195
2196 ExtAddrMode TestAddrMode = AddrMode;
2197
2198 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2199 // [A+B + A*7] -> [B+A*8].
2200 TestAddrMode.Scale += Scale;
2201 TestAddrMode.ScaledReg = ScaleReg;
2202
2203 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002204 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002205 return false;
2206
2207 // It was legal, so commit it.
2208 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002209
Chandler Carruthc8925912013-01-05 02:09:22 +00002210 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2211 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2212 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002213 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002214 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2215 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2216 TestAddrMode.ScaledReg = AddLHS;
2217 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002218
Chandler Carruthc8925912013-01-05 02:09:22 +00002219 // If this addressing mode is legal, commit it and remember that we folded
2220 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002221 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002222 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2223 AddrMode = TestAddrMode;
2224 return true;
2225 }
2226 }
2227
2228 // Otherwise, not (x+c)*scale, just return what we have.
2229 return true;
2230}
2231
2232/// MightBeFoldableInst - This is a little filter, which returns true if an
2233/// addressing computation involving I might be folded into a load/store
2234/// accessing it. This doesn't need to be perfect, but needs to accept at least
2235/// the set of instructions that MatchOperationAddr can.
2236static bool MightBeFoldableInst(Instruction *I) {
2237 switch (I->getOpcode()) {
2238 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002239 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002240 // Don't touch identity bitcasts.
2241 if (I->getType() == I->getOperand(0)->getType())
2242 return false;
2243 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2244 case Instruction::PtrToInt:
2245 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2246 return true;
2247 case Instruction::IntToPtr:
2248 // We know the input is intptr_t, so this is foldable.
2249 return true;
2250 case Instruction::Add:
2251 return true;
2252 case Instruction::Mul:
2253 case Instruction::Shl:
2254 // Can only handle X*C and X << C.
2255 return isa<ConstantInt>(I->getOperand(1));
2256 case Instruction::GetElementPtr:
2257 return true;
2258 default:
2259 return false;
2260 }
2261}
2262
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002263/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2264/// \note \p Val is assumed to be the product of some type promotion.
2265/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2266/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002267static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2268 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002269 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2270 if (!PromotedInst)
2271 return false;
2272 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2273 // If the ISDOpcode is undefined, it was undefined before the promotion.
2274 if (!ISDOpcode)
2275 return true;
2276 // Otherwise, check if the promoted instruction is legal or not.
2277 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002278 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002279}
2280
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002281/// \brief Hepler class to perform type promotion.
2282class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002283 /// \brief Utility function to check whether or not a sign or zero extension
2284 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2285 /// either using the operands of \p Inst or promoting \p Inst.
2286 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002287 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002288 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002289 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002290 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002291 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002292 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002293 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002294 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2295 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296
2297 /// \brief Utility function to determine if \p OpIdx should be promoted when
2298 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002299 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002300 if (isa<SelectInst>(Inst) && OpIdx == 0)
2301 return false;
2302 return true;
2303 }
2304
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002305 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002306 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002307 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002308 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002309 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002310 /// Newly added extensions are inserted in \p Exts.
2311 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002313 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002314 static Value *promoteOperandForTruncAndAnyExt(
2315 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002316 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002317 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002318 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002319
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002320 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002321 /// operand is promotable and is not a supported trunc or sext.
2322 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002323 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002324 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002325 /// Newly added extensions are inserted in \p Exts.
2326 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002327 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002328 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002329 static Value *promoteOperandForOther(Instruction *Ext,
2330 TypePromotionTransaction &TPT,
2331 InstrToOrigTy &PromotedInsts,
2332 unsigned &CreatedInstsCost,
2333 SmallVectorImpl<Instruction *> *Exts,
2334 SmallVectorImpl<Instruction *> *Truncs,
2335 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002336
2337 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002338 static Value *signExtendOperandForOther(
2339 Instruction *Ext, TypePromotionTransaction &TPT,
2340 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2341 SmallVectorImpl<Instruction *> *Exts,
2342 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2343 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2344 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002345 }
2346
2347 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002348 static Value *zeroExtendOperandForOther(
2349 Instruction *Ext, TypePromotionTransaction &TPT,
2350 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2351 SmallVectorImpl<Instruction *> *Exts,
2352 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2353 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2354 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002355 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002356
2357public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002358 /// Type for the utility function that promotes the operand of Ext.
2359 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002360 InstrToOrigTy &PromotedInsts,
2361 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002362 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002363 SmallVectorImpl<Instruction *> *Truncs,
2364 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002365 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2366 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002367 /// \return NULL if no promotable action is possible with the current
2368 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002369 /// \p InsertedInsts keeps track of all the instructions inserted by the
2370 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002371 /// because we do not want to promote these instructions as CodeGenPrepare
2372 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2373 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002374 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002375 const TargetLowering &TLI,
2376 const InstrToOrigTy &PromotedInsts);
2377};
2378
2379bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002380 Type *ConsideredExtType,
2381 const InstrToOrigTy &PromotedInsts,
2382 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002383 // The promotion helper does not know how to deal with vector types yet.
2384 // To be able to fix that, we would need to fix the places where we
2385 // statically extend, e.g., constants and such.
2386 if (Inst->getType()->isVectorTy())
2387 return false;
2388
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002389 // We can always get through zext.
2390 if (isa<ZExtInst>(Inst))
2391 return true;
2392
2393 // sext(sext) is ok too.
2394 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002395 return true;
2396
2397 // We can get through binary operator, if it is legal. In other words, the
2398 // binary operator must have a nuw or nsw flag.
2399 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2400 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002401 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2402 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002403 return true;
2404
2405 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002406 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002407 if (!isa<TruncInst>(Inst))
2408 return false;
2409
2410 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002411 // Check if we can use this operand in the extension.
2412 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002413 // we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002414 if (!OpndVal->getType()->isIntegerTy() ||
2415 OpndVal->getType()->getIntegerBitWidth() >
2416 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002417 return false;
2418
2419 // If the operand of the truncate is not an instruction, we will not have
2420 // any information on the dropped bits.
2421 // (Actually we could for constant but it is not worth the extra logic).
2422 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2423 if (!Opnd)
2424 return false;
2425
2426 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002427 // I.e., check that trunc just drops extended bits of the same kind of
2428 // the extension.
2429 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002430 const Type *OpndType;
2431 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002432 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2433 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002434 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2435 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436 else
2437 return false;
2438
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002439 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002440 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2441 return true;
2442
2443 return false;
2444}
2445
2446TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002447 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002448 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002449 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2450 "Unexpected instruction type");
2451 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2452 Type *ExtTy = Ext->getType();
2453 bool IsSExt = isa<SExtInst>(Ext);
2454 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455 // get through.
2456 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002457 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002458 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459
2460 // Do not promote if the operand has been added by codegenprepare.
2461 // Otherwise, it means we are undoing an optimization that is likely to be
2462 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002463 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002464 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002465
2466 // SExt or Trunc instructions.
2467 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002468 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2469 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002470 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002471
2472 // Regular instruction.
2473 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002474 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002475 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002476 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002477}
2478
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002479Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002480 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002481 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002482 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002483 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002484 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2485 // get through it and this method should not be called.
2486 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002487 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002488 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002489 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002490 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002491 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002492 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002493 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002494 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2495 TPT.replaceAllUsesWith(SExt, ZExt);
2496 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002497 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002498 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002499 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2500 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002501 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2502 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002503 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002504
2505 // Remove dead code.
2506 if (SExtOpnd->use_empty())
2507 TPT.eraseInstruction(SExtOpnd);
2508
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002509 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002510 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002511 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002512 if (ExtInst) {
2513 if (Exts)
2514 Exts->push_back(ExtInst);
2515 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2516 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002517 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002518 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002519
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002520 // At this point we have: ext ty opnd to ty.
2521 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2522 Value *NextVal = ExtInst->getOperand(0);
2523 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 return NextVal;
2525}
2526
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002527Value *TypePromotionHelper::promoteOperandForOther(
2528 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002529 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002530 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002531 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2532 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002533 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002534 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002535 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002536 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002537 if (!ExtOpnd->hasOneUse()) {
2538 // ExtOpnd will be promoted.
2539 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002540 // promoted version.
2541 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002542 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002543 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2544 ITrunc->removeFromParent();
2545 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002546 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002547 if (Truncs)
2548 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002549 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002550
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002551 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2552 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002553 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002554 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002555 }
2556
2557 // Get through the Instruction:
2558 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002559 // 2. Replace the uses of Ext by Inst.
2560 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002561
2562 // Remember the original type of the instruction before promotion.
2563 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002564 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2565 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002566 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002567 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002568 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002569 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002570 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002571 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002572
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002573 DEBUG(dbgs() << "Propagate Ext to operands\n");
2574 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002575 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002576 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2577 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2578 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002579 DEBUG(dbgs() << "No need to propagate\n");
2580 continue;
2581 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002582 // Check if we can statically extend the operand.
2583 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002584 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002585 DEBUG(dbgs() << "Statically extend\n");
2586 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2587 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2588 : Cst->getValue().zext(BitWidth);
2589 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002590 continue;
2591 }
2592 // UndefValue are typed, so we have to statically sign extend them.
2593 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002594 DEBUG(dbgs() << "Statically extend\n");
2595 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002596 continue;
2597 }
2598
2599 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002600 // Check if Ext was reused to extend an operand.
2601 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002602 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002603 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002604 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2605 : TPT.createZExt(Ext, Opnd, Ext->getType());
2606 if (!isa<Instruction>(ValForExtOpnd)) {
2607 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2608 continue;
2609 }
2610 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002611 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002612 if (Exts)
2613 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002614 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002615
2616 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002617 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2618 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002619 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002620 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002621 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002622 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002623 if (ExtForOpnd == Ext) {
2624 DEBUG(dbgs() << "Extension is useless now\n");
2625 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002626 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002627 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002628}
2629
Quentin Colombet867c5502014-02-14 22:23:22 +00002630/// IsPromotionProfitable - Check whether or not promoting an instruction
2631/// to a wider type was profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002632/// \p NewCost gives the cost of extension instructions created by the
2633/// promotion.
2634/// \p OldCost gives the cost of extension instructions before the promotion
2635/// plus the number of instructions that have been
2636/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00002637/// \p PromotedOperand is the value that has been promoted.
2638/// \return True if the promotion is profitable, false otherwise.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002639bool AddressingModeMatcher::IsPromotionProfitable(
2640 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2641 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2642 // The cost of the new extensions is greater than the cost of the
2643 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00002644 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002645 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002646 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002647 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002648 return true;
2649 // The promotion is neutral but it may help folding the sign extension in
2650 // loads for instance.
2651 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00002652 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002653}
2654
Chandler Carruthc8925912013-01-05 02:09:22 +00002655/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2656/// fold the operation into the addressing mode. If so, update the addressing
2657/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002658/// If \p MovedAway is not NULL, it contains the information of whether or
2659/// not AddrInst has to be folded into the addressing mode on success.
2660/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2661/// because it has been moved away.
2662/// Thus AddrInst must not be added in the matched instructions.
2663/// This state can happen when AddrInst is a sext, since it may be moved away.
2664/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2665/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002666bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002667 unsigned Depth,
2668 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002669 // Avoid exponential behavior on extremely deep expression trees.
2670 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002671
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002672 // By default, all matched instructions stay in place.
2673 if (MovedAway)
2674 *MovedAway = false;
2675
Chandler Carruthc8925912013-01-05 02:09:22 +00002676 switch (Opcode) {
2677 case Instruction::PtrToInt:
2678 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2679 return MatchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00002680 case Instruction::IntToPtr: {
2681 auto AS = AddrInst->getType()->getPointerAddressSpace();
2682 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00002683 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00002684 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00002685 return MatchAddr(AddrInst->getOperand(0), Depth);
2686 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00002687 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002688 case Instruction::BitCast:
2689 // BitCast is always a noop, and we can handle it as long as it is
2690 // int->int or pointer->pointer (we don't want int<->fp or something).
2691 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2692 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2693 // Don't touch identity bitcasts. These were probably put here by LSR,
2694 // and we don't want to mess around with them. Assume it knows what it
2695 // is doing.
2696 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2697 return MatchAddr(AddrInst->getOperand(0), Depth);
2698 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00002699 case Instruction::AddrSpaceCast: {
2700 unsigned SrcAS
2701 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2702 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2703 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2704 return MatchAddr(AddrInst->getOperand(0), Depth);
2705 return false;
2706 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002707 case Instruction::Add: {
2708 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2709 ExtAddrMode BackupAddrMode = AddrMode;
2710 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002711 // Start a transaction at this point.
2712 // The LHS may match but not the RHS.
2713 // Therefore, we need a higher level restoration point to undo partially
2714 // matched operation.
2715 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2716 TPT.getRestorationPoint();
2717
Chandler Carruthc8925912013-01-05 02:09:22 +00002718 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2719 MatchAddr(AddrInst->getOperand(0), Depth+1))
2720 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002721
Chandler Carruthc8925912013-01-05 02:09:22 +00002722 // Restore the old addr mode info.
2723 AddrMode = BackupAddrMode;
2724 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002725 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002726
Chandler Carruthc8925912013-01-05 02:09:22 +00002727 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2728 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2729 MatchAddr(AddrInst->getOperand(1), Depth+1))
2730 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002731
Chandler Carruthc8925912013-01-05 02:09:22 +00002732 // Otherwise we definitely can't merge the ADD in.
2733 AddrMode = BackupAddrMode;
2734 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002735 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002736 break;
2737 }
2738 //case Instruction::Or:
2739 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2740 //break;
2741 case Instruction::Mul:
2742 case Instruction::Shl: {
2743 // Can only handle X*C and X << C.
2744 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002745 if (!RHS)
2746 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002747 int64_t Scale = RHS->getSExtValue();
2748 if (Opcode == Instruction::Shl)
2749 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002750
Chandler Carruthc8925912013-01-05 02:09:22 +00002751 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2752 }
2753 case Instruction::GetElementPtr: {
2754 // Scan the GEP. We check it if it contains constant offsets and at most
2755 // one variable offset.
2756 int VariableOperand = -1;
2757 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002758
Chandler Carruthc8925912013-01-05 02:09:22 +00002759 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00002760 gep_type_iterator GTI = gep_type_begin(AddrInst);
2761 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2762 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002763 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00002764 unsigned Idx =
2765 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2766 ConstantOffset += SL->getElementOffset(Idx);
2767 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002768 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00002769 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2770 ConstantOffset += CI->getSExtValue()*TypeSize;
2771 } else if (TypeSize) { // Scales of zero don't do anything.
2772 // We only allow one variable index at the moment.
2773 if (VariableOperand != -1)
2774 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002775
Chandler Carruthc8925912013-01-05 02:09:22 +00002776 // Remember the variable index.
2777 VariableOperand = i;
2778 VariableScale = TypeSize;
2779 }
2780 }
2781 }
Stephen Lin837bba12013-07-15 17:55:02 +00002782
Chandler Carruthc8925912013-01-05 02:09:22 +00002783 // A common case is for the GEP to only do a constant offset. In this case,
2784 // just add it to the disp field and check validity.
2785 if (VariableOperand == -1) {
2786 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002787 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002788 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002789 // Check to see if we can fold the base pointer in too.
2790 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2791 return true;
2792 }
2793 AddrMode.BaseOffs -= ConstantOffset;
2794 return false;
2795 }
2796
2797 // Save the valid addressing mode in case we can't match.
2798 ExtAddrMode BackupAddrMode = AddrMode;
2799 unsigned OldSize = AddrModeInsts.size();
2800
2801 // See if the scale and offset amount is valid for this target.
2802 AddrMode.BaseOffs += ConstantOffset;
2803
2804 // Match the base operand of the GEP.
2805 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2806 // If it couldn't be matched, just stuff the value in a register.
2807 if (AddrMode.HasBaseReg) {
2808 AddrMode = BackupAddrMode;
2809 AddrModeInsts.resize(OldSize);
2810 return false;
2811 }
2812 AddrMode.HasBaseReg = true;
2813 AddrMode.BaseReg = AddrInst->getOperand(0);
2814 }
2815
2816 // Match the remaining variable portion of the GEP.
2817 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2818 Depth)) {
2819 // If it couldn't be matched, try stuffing the base into a register
2820 // instead of matching it, and retrying the match of the scale.
2821 AddrMode = BackupAddrMode;
2822 AddrModeInsts.resize(OldSize);
2823 if (AddrMode.HasBaseReg)
2824 return false;
2825 AddrMode.HasBaseReg = true;
2826 AddrMode.BaseReg = AddrInst->getOperand(0);
2827 AddrMode.BaseOffs += ConstantOffset;
2828 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2829 VariableScale, Depth)) {
2830 // If even that didn't work, bail.
2831 AddrMode = BackupAddrMode;
2832 AddrModeInsts.resize(OldSize);
2833 return false;
2834 }
2835 }
2836
2837 return true;
2838 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002839 case Instruction::SExt:
2840 case Instruction::ZExt: {
2841 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2842 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002843 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002844
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002845 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002846 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002847 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002848 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002849 if (!TPH)
2850 return false;
2851
2852 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2853 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00002854 unsigned CreatedInstsCost = 0;
2855 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002856 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00002857 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002858 // SExt has been moved away.
2859 // Thus either it will be rematched later in the recursive calls or it is
2860 // gone. Anyway, we must not fold it into the addressing mode at this point.
2861 // E.g.,
2862 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002863 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002864 // addr = gep base, idx
2865 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002866 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002867 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2868 // addr = gep base, op <- match
2869 if (MovedAway)
2870 *MovedAway = true;
2871
2872 assert(PromotedOperand &&
2873 "TypePromotionHelper should have filtered out those cases");
2874
2875 ExtAddrMode BackupAddrMode = AddrMode;
2876 unsigned OldSize = AddrModeInsts.size();
2877
2878 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet1b274f92015-03-10 21:48:15 +00002879 // The total of the new cost is equals to the cost of the created
2880 // instructions.
2881 // The total of the old cost is equals to the cost of the extension plus
2882 // what we have saved in the addressing mode.
2883 !IsPromotionProfitable(CreatedInstsCost,
2884 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00002885 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002886 AddrMode = BackupAddrMode;
2887 AddrModeInsts.resize(OldSize);
2888 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2889 TPT.rollback(LastKnownGood);
2890 return false;
2891 }
2892 return true;
2893 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002894 }
2895 return false;
2896}
2897
2898/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2899/// addressing mode. If Addr can't be added to AddrMode this returns false and
2900/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2901/// or intptr_t for the target.
2902///
2903bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002904 // Start a transaction at this point that we will rollback if the matching
2905 // fails.
2906 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2907 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002908 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2909 // Fold in immediates if legal for the target.
2910 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002911 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002912 return true;
2913 AddrMode.BaseOffs -= CI->getSExtValue();
2914 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2915 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002916 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002917 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002918 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002919 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002920 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002921 }
2922 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2923 ExtAddrMode BackupAddrMode = AddrMode;
2924 unsigned OldSize = AddrModeInsts.size();
2925
2926 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002927 bool MovedAway = false;
2928 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2929 // This instruction may have been move away. If so, there is nothing
2930 // to check here.
2931 if (MovedAway)
2932 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002933 // Okay, it's possible to fold this. Check to see if it is actually
2934 // *profitable* to do so. We use a simple cost model to avoid increasing
2935 // register pressure too much.
2936 if (I->hasOneUse() ||
2937 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2938 AddrModeInsts.push_back(I);
2939 return true;
2940 }
Stephen Lin837bba12013-07-15 17:55:02 +00002941
Chandler Carruthc8925912013-01-05 02:09:22 +00002942 // It isn't profitable to do this, roll back.
2943 //cerr << "NOT FOLDING: " << *I;
2944 AddrMode = BackupAddrMode;
2945 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002946 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002947 }
2948 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2949 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2950 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002951 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002952 } else if (isa<ConstantPointerNull>(Addr)) {
2953 // Null pointer gets folded without affecting the addressing mode.
2954 return true;
2955 }
2956
2957 // Worse case, the target should support [reg] addressing modes. :)
2958 if (!AddrMode.HasBaseReg) {
2959 AddrMode.HasBaseReg = true;
2960 AddrMode.BaseReg = Addr;
2961 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002962 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002963 return true;
2964 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002965 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002966 }
2967
2968 // If the base register is already taken, see if we can do [r+r].
2969 if (AddrMode.Scale == 0) {
2970 AddrMode.Scale = 1;
2971 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002972 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002973 return true;
2974 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002975 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002976 }
2977 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002978 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002979 return false;
2980}
2981
2982/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2983/// inline asm call are due to memory operands. If so, return true, otherwise
2984/// return false.
2985static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00002986 const TargetMachine &TM) {
2987 const Function *F = CI->getParent()->getParent();
2988 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2989 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00002990 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002991 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
2992 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00002993 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2994 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002995
Chandler Carruthc8925912013-01-05 02:09:22 +00002996 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00002997 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00002998
2999 // If this asm operand is our Value*, and if it isn't an indirect memory
3000 // operand, we can't fold it!
3001 if (OpInfo.CallOperandVal == OpVal &&
3002 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3003 !OpInfo.isIndirect))
3004 return false;
3005 }
3006
3007 return true;
3008}
3009
3010/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
3011/// memory use. If we find an obviously non-foldable instruction, return true.
3012/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003013static bool FindAllMemoryUses(
3014 Instruction *I,
3015 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3016 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003017 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003018 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003019 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003020
Chandler Carruthc8925912013-01-05 02:09:22 +00003021 // If this is an obviously unfoldable instruction, bail out.
3022 if (!MightBeFoldableInst(I))
3023 return true;
3024
3025 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003026 for (Use &U : I->uses()) {
3027 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003028
Chandler Carruthcdf47882014-03-09 03:16:01 +00003029 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3030 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003031 continue;
3032 }
Stephen Lin837bba12013-07-15 17:55:02 +00003033
Chandler Carruthcdf47882014-03-09 03:16:01 +00003034 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3035 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003036 if (opNo == 0) return true; // Storing addr, not into addr.
3037 MemoryUses.push_back(std::make_pair(SI, opNo));
3038 continue;
3039 }
Stephen Lin837bba12013-07-15 17:55:02 +00003040
Chandler Carruthcdf47882014-03-09 03:16:01 +00003041 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003042 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3043 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003044
Chandler Carruthc8925912013-01-05 02:09:22 +00003045 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003046 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003047 return true;
3048 continue;
3049 }
Stephen Lin837bba12013-07-15 17:55:02 +00003050
Eric Christopher11e4df72015-02-26 22:38:43 +00003051 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003052 return true;
3053 }
3054
3055 return false;
3056}
3057
3058/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
3059/// the use site that we're folding it into. If so, there is no cost to
3060/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
3061/// that we know are live at the instruction already.
3062bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
3063 Value *KnownLive2) {
3064 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003065 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003066 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003067
Chandler Carruthc8925912013-01-05 02:09:22 +00003068 // All values other than instructions and arguments (e.g. constants) are live.
3069 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003070
Chandler Carruthc8925912013-01-05 02:09:22 +00003071 // If Val is a constant sized alloca in the entry block, it is live, this is
3072 // true because it is just a reference to the stack/frame pointer, which is
3073 // live for the whole function.
3074 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3075 if (AI->isStaticAlloca())
3076 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003077
Chandler Carruthc8925912013-01-05 02:09:22 +00003078 // Check to see if this value is already used in the memory instruction's
3079 // block. If so, it's already live into the block at the very least, so we
3080 // can reasonably fold it.
3081 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3082}
3083
3084/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
3085/// mode of the machine to fold the specified instruction into a load or store
3086/// that ultimately uses it. However, the specified instruction has multiple
3087/// uses. Given this, it may actually increase register pressure to fold it
3088/// into the load. For example, consider this code:
3089///
3090/// X = ...
3091/// Y = X+1
3092/// use(Y) -> nonload/store
3093/// Z = Y+1
3094/// load Z
3095///
3096/// In this case, Y has multiple uses, and can be folded into the load of Z
3097/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3098/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3099/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3100/// number of computations either.
3101///
3102/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3103/// X was live across 'load Z' for other reasons, we actually *would* want to
3104/// fold the addressing mode in the Z case. This would make Y die earlier.
3105bool AddressingModeMatcher::
3106IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
3107 ExtAddrMode &AMAfter) {
3108 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003109
Chandler Carruthc8925912013-01-05 02:09:22 +00003110 // AMBefore is the addressing mode before this instruction was folded into it,
3111 // and AMAfter is the addressing mode after the instruction was folded. Get
3112 // the set of registers referenced by AMAfter and subtract out those
3113 // referenced by AMBefore: this is the set of values which folding in this
3114 // address extends the lifetime of.
3115 //
3116 // Note that there are only two potential values being referenced here,
3117 // BaseReg and ScaleReg (global addresses are always available, as are any
3118 // folded immediates).
3119 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003120
Chandler Carruthc8925912013-01-05 02:09:22 +00003121 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3122 // lifetime wasn't extended by adding this instruction.
3123 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003124 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003125 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003126 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003127
3128 // If folding this instruction (and it's subexprs) didn't extend any live
3129 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003130 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003131 return true;
3132
3133 // If all uses of this instruction are ultimately load/store/inlineasm's,
3134 // check to see if their addressing modes will include this instruction. If
3135 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3136 // uses.
3137 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3138 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003139 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003140 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003141
Chandler Carruthc8925912013-01-05 02:09:22 +00003142 // Now that we know that all uses of this instruction are part of a chain of
3143 // computation involving only operations that could theoretically be folded
3144 // into a memory use, loop over each of these uses and see if they could
3145 // *actually* fold the instruction.
3146 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3147 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3148 Instruction *User = MemoryUses[i].first;
3149 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003150
Chandler Carruthc8925912013-01-05 02:09:22 +00003151 // Get the access type of this use. If the use isn't a pointer, we don't
3152 // know what it accesses.
3153 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003154 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3155 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003156 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003157 Type *AddressAccessTy = AddrTy->getElementType();
3158 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003159
Chandler Carruthc8925912013-01-05 02:09:22 +00003160 // Do a match against the root of this address, ignoring profitability. This
3161 // will tell us if the addressing mode for the memory operation will
3162 // *actually* cover the shared instruction.
3163 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003164 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3165 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003166 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003167 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003168 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003169 Matcher.IgnoreProfitability = true;
3170 bool Success = Matcher.MatchAddr(Address, 0);
3171 (void)Success; assert(Success && "Couldn't select *anything*?");
3172
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003173 // The match was to check the profitability, the changes made are not
3174 // part of the original matcher. Therefore, they should be dropped
3175 // otherwise the original matcher will not present the right state.
3176 TPT.rollback(LastKnownGood);
3177
Chandler Carruthc8925912013-01-05 02:09:22 +00003178 // If the match didn't cover I, then it won't be shared by it.
3179 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3180 I) == MatchedAddrModeInsts.end())
3181 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003182
Chandler Carruthc8925912013-01-05 02:09:22 +00003183 MatchedAddrModeInsts.clear();
3184 }
Stephen Lin837bba12013-07-15 17:55:02 +00003185
Chandler Carruthc8925912013-01-05 02:09:22 +00003186 return true;
3187}
3188
3189} // end anonymous namespace
3190
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003191/// IsNonLocalValue - Return true if the specified values are defined in a
3192/// different basic block than BB.
3193static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3194 if (Instruction *I = dyn_cast<Instruction>(V))
3195 return I->getParent() != BB;
3196 return false;
3197}
3198
Bob Wilson53bdae32009-12-03 21:47:07 +00003199/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003200/// addressing modes that can do significant amounts of computation. As such,
3201/// instruction selection will try to get the load or store to do as much
3202/// computation as possible for the program. The problem is that isel can only
3203/// see within a single block. As such, we sink as much legal addressing mode
3204/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003205///
3206/// This method is used to optimize both load/store and inline asms with memory
3207/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003208bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003209 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003210 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003211
3212 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003213 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003214 SmallVector<Value*, 8> worklist;
3215 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003216 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003217
Owen Anderson8ba5f392010-11-27 08:15:55 +00003218 // Use a worklist to iteratively look through PHI nodes, and ensure that
3219 // the addressing mode obtained from the non-PHI roots of the graph
3220 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003221 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003222 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003223 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003224 SmallVector<Instruction*, 16> AddrModeInsts;
3225 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003226 TypePromotionTransaction TPT;
3227 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3228 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003229 while (!worklist.empty()) {
3230 Value *V = worklist.back();
3231 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003232
Owen Anderson8ba5f392010-11-27 08:15:55 +00003233 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003234 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003235 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003236 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003237 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003238
Owen Anderson8ba5f392010-11-27 08:15:55 +00003239 // For a PHI node, push all of its incoming values.
3240 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003241 for (Value *IncValue : P->incoming_values())
3242 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003243 continue;
3244 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003245
Owen Anderson8ba5f392010-11-27 08:15:55 +00003246 // For non-PHIs, determine the addressing mode being computed.
3247 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003248 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003249 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003250 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003251
3252 // This check is broken into two cases with very similar code to avoid using
3253 // getNumUses() as much as possible. Some values have a lot of uses, so
3254 // calling getNumUses() unconditionally caused a significant compile-time
3255 // regression.
3256 if (!Consensus) {
3257 Consensus = V;
3258 AddrMode = NewAddrMode;
3259 AddrModeInsts = NewAddrModeInsts;
3260 continue;
3261 } else if (NewAddrMode == AddrMode) {
3262 if (!IsNumUsesConsensusValid) {
3263 NumUsesConsensus = Consensus->getNumUses();
3264 IsNumUsesConsensusValid = true;
3265 }
3266
3267 // Ensure that the obtained addressing mode is equivalent to that obtained
3268 // for all other roots of the PHI traversal. Also, when choosing one
3269 // such root as representative, select the one with the most uses in order
3270 // to keep the cost modeling heuristics in AddressingModeMatcher
3271 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003272 unsigned NumUses = V->getNumUses();
3273 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003274 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003275 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003276 AddrModeInsts = NewAddrModeInsts;
3277 }
3278 continue;
3279 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003280
Craig Topperc0196b12014-04-14 00:51:57 +00003281 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003282 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003283 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003284
Owen Anderson8ba5f392010-11-27 08:15:55 +00003285 // If the addressing mode couldn't be determined, or if multiple different
3286 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003287 if (!Consensus) {
3288 TPT.rollback(LastKnownGood);
3289 return false;
3290 }
3291 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003292
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003293 // Check to see if any of the instructions supersumed by this addr mode are
3294 // non-local to I's BB.
3295 bool AnyNonLocal = false;
3296 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003297 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003298 AnyNonLocal = true;
3299 break;
3300 }
3301 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003302
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003303 // If all the instructions matched are already in this BB, don't do anything.
3304 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003305 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003306 return false;
3307 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003308
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003309 // Insert this computation right after this user. Since our caller is
3310 // scanning from the top of the BB to the bottom, reuse of the expr are
3311 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003312 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003313
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003314 // Now that we determined the addressing expression we want to use and know
3315 // that we have to sink it into this block. Check to see if we have already
3316 // done this for some other load/store instr in this block. If so, reuse the
3317 // computation.
3318 Value *&SunkAddr = SunkAddrs[Addr];
3319 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003320 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003321 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003322 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003323 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003324 } else if (AddrSinkUsingGEPs ||
3325 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003326 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3327 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003328 // By default, we use the GEP-based method when AA is used later. This
3329 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3330 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003331 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003332 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003333 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003334
3335 // First, find the pointer.
3336 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3337 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003338 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003339 }
3340
3341 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3342 // We can't add more than one pointer together, nor can we scale a
3343 // pointer (both of which seem meaningless).
3344 if (ResultPtr || AddrMode.Scale != 1)
3345 return false;
3346
3347 ResultPtr = AddrMode.ScaledReg;
3348 AddrMode.Scale = 0;
3349 }
3350
3351 if (AddrMode.BaseGV) {
3352 if (ResultPtr)
3353 return false;
3354
3355 ResultPtr = AddrMode.BaseGV;
3356 }
3357
3358 // If the real base value actually came from an inttoptr, then the matcher
3359 // will look through it and provide only the integer value. In that case,
3360 // use it here.
3361 if (!ResultPtr && AddrMode.BaseReg) {
3362 ResultPtr =
3363 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003364 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003365 } else if (!ResultPtr && AddrMode.Scale == 1) {
3366 ResultPtr =
3367 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3368 AddrMode.Scale = 0;
3369 }
3370
3371 if (!ResultPtr &&
3372 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3373 SunkAddr = Constant::getNullValue(Addr->getType());
3374 } else if (!ResultPtr) {
3375 return false;
3376 } else {
3377 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003378 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3379 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003380
3381 // Start with the base register. Do this first so that subsequent address
3382 // matching finds it last, which will prevent it from trying to match it
3383 // as the scaled value in case it happens to be a mul. That would be
3384 // problematic if we've sunk a different mul for the scale, because then
3385 // we'd end up sinking both muls.
3386 if (AddrMode.BaseReg) {
3387 Value *V = AddrMode.BaseReg;
3388 if (V->getType() != IntPtrTy)
3389 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3390
3391 ResultIndex = V;
3392 }
3393
3394 // Add the scale value.
3395 if (AddrMode.Scale) {
3396 Value *V = AddrMode.ScaledReg;
3397 if (V->getType() == IntPtrTy) {
3398 // done.
3399 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3400 cast<IntegerType>(V->getType())->getBitWidth()) {
3401 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3402 } else {
3403 // It is only safe to sign extend the BaseReg if we know that the math
3404 // required to create it did not overflow before we extend it. Since
3405 // the original IR value was tossed in favor of a constant back when
3406 // the AddrMode was created we need to bail out gracefully if widths
3407 // do not match instead of extending it.
3408 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3409 if (I && (ResultIndex != AddrMode.BaseReg))
3410 I->eraseFromParent();
3411 return false;
3412 }
3413
3414 if (AddrMode.Scale != 1)
3415 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3416 "sunkaddr");
3417 if (ResultIndex)
3418 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3419 else
3420 ResultIndex = V;
3421 }
3422
3423 // Add in the Base Offset if present.
3424 if (AddrMode.BaseOffs) {
3425 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3426 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003427 // We need to add this separately from the scale above to help with
3428 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003429 if (ResultPtr->getType() != I8PtrTy)
3430 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003431 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003432 }
3433
3434 ResultIndex = V;
3435 }
3436
3437 if (!ResultIndex) {
3438 SunkAddr = ResultPtr;
3439 } else {
3440 if (ResultPtr->getType() != I8PtrTy)
3441 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003442 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003443 }
3444
3445 if (SunkAddr->getType() != Addr->getType())
3446 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3447 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003448 } else {
David Greene74e2d492010-01-05 01:27:11 +00003449 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003450 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003451 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003452 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003453
3454 // Start with the base register. Do this first so that subsequent address
3455 // matching finds it last, which will prevent it from trying to match it
3456 // as the scaled value in case it happens to be a mul. That would be
3457 // problematic if we've sunk a different mul for the scale, because then
3458 // we'd end up sinking both muls.
3459 if (AddrMode.BaseReg) {
3460 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003461 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003462 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003463 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003464 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003465 Result = V;
3466 }
3467
3468 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003469 if (AddrMode.Scale) {
3470 Value *V = AddrMode.ScaledReg;
3471 if (V->getType() == IntPtrTy) {
3472 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003473 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003474 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003475 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3476 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003477 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003478 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003479 // It is only safe to sign extend the BaseReg if we know that the math
3480 // required to create it did not overflow before we extend it. Since
3481 // the original IR value was tossed in favor of a constant back when
3482 // the AddrMode was created we need to bail out gracefully if widths
3483 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003484 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003485 if (I && (Result != AddrMode.BaseReg))
3486 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003487 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003488 }
3489 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003490 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3491 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003492 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003493 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003494 else
3495 Result = V;
3496 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003497
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003498 // Add in the BaseGV if present.
3499 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003500 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003501 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003502 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003503 else
3504 Result = V;
3505 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003506
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003507 // Add in the Base Offset if present.
3508 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003509 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003510 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003511 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003512 else
3513 Result = V;
3514 }
3515
Craig Topperc0196b12014-04-14 00:51:57 +00003516 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003517 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003518 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003519 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003520 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003521
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003522 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003523
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003524 // If we have no uses, recursively delete the value and all dead instructions
3525 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003526 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003527 // This can cause recursive deletion, which can invalidate our iterator.
3528 // Use a WeakVH to hold onto it in case this happens.
3529 WeakVH IterHandle(CurInstIterator);
3530 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003531
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003532 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003533
3534 if (IterHandle != CurInstIterator) {
3535 // If the iterator instruction was recursively deleted, start over at the
3536 // start of the block.
3537 CurInstIterator = BB->begin();
3538 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003539 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003540 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003541 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003542 return true;
3543}
3544
Evan Cheng1da25002008-02-26 02:42:37 +00003545/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00003546/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00003547/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00003548bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003549 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003550
Eric Christopher11e4df72015-02-26 22:38:43 +00003551 const TargetRegisterInfo *TRI =
3552 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003553 TargetLowering::AsmOperandInfoVector TargetConstraints =
3554 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003555 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003556 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3557 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003558
Evan Cheng1da25002008-02-26 02:42:37 +00003559 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003560 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003561
Eli Friedman666bbe32008-02-26 18:37:49 +00003562 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3563 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003564 Value *OpVal = CS->getArgOperand(ArgNo++);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003565 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003566 } else if (OpInfo.Type == InlineAsm::isInput)
3567 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003568 }
3569
3570 return MadeChange;
3571}
3572
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003573/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3574/// sign extensions.
3575static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3576 assert(!Inst->use_empty() && "Input must have at least one use");
3577 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3578 bool IsSExt = isa<SExtInst>(FirstUser);
3579 Type *ExtTy = FirstUser->getType();
3580 for (const User *U : Inst->users()) {
3581 const Instruction *UI = cast<Instruction>(U);
3582 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3583 return false;
3584 Type *CurTy = UI->getType();
3585 // Same input and output types: Same instruction after CSE.
3586 if (CurTy == ExtTy)
3587 continue;
3588
3589 // If IsSExt is true, we are in this situation:
3590 // a = Inst
3591 // b = sext ty1 a to ty2
3592 // c = sext ty1 a to ty3
3593 // Assuming ty2 is shorter than ty3, this could be turned into:
3594 // a = Inst
3595 // b = sext ty1 a to ty2
3596 // c = sext ty2 b to ty3
3597 // However, the last sext is not free.
3598 if (IsSExt)
3599 return false;
3600
3601 // This is a ZExt, maybe this is free to extend from one type to another.
3602 // In that case, we would not account for a different use.
3603 Type *NarrowTy;
3604 Type *LargeTy;
3605 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3606 CurTy->getScalarType()->getIntegerBitWidth()) {
3607 NarrowTy = CurTy;
3608 LargeTy = ExtTy;
3609 } else {
3610 NarrowTy = ExtTy;
3611 LargeTy = CurTy;
3612 }
3613
3614 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3615 return false;
3616 }
3617 // All uses are the same or can be derived from one another for free.
3618 return true;
3619}
3620
3621/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3622/// load instruction.
3623/// If an ext(load) can be formed, it is returned via \p LI for the load
3624/// and \p Inst for the extension.
3625/// Otherwise LI == nullptr and Inst == nullptr.
3626/// When some promotion happened, \p TPT contains the proper state to
3627/// revert them.
3628///
3629/// \return true when promoting was necessary to expose the ext(load)
3630/// opportunity, false otherwise.
3631///
3632/// Example:
3633/// \code
3634/// %ld = load i32* %addr
3635/// %add = add nuw i32 %ld, 4
3636/// %zext = zext i32 %add to i64
3637/// \endcode
3638/// =>
3639/// \code
3640/// %ld = load i32* %addr
3641/// %zext = zext i32 %ld to i64
3642/// %add = add nuw i64 %zext, 4
3643/// \encode
3644/// Thanks to the promotion, we can match zext(load i32*) to i64.
3645bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3646 LoadInst *&LI, Instruction *&Inst,
3647 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003648 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003649 // Iterate over all the extensions to see if one form an ext(load).
3650 for (auto I : Exts) {
3651 // Check if we directly have ext(load).
3652 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3653 Inst = I;
3654 // No promotion happened here.
3655 return false;
3656 }
3657 // Check whether or not we want to do any promotion.
3658 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3659 continue;
3660 // Get the action to perform the promotion.
3661 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003662 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003663 // Check if we can promote.
3664 if (!TPH)
3665 continue;
3666 // Save the current state.
3667 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3668 TPT.getRestorationPoint();
3669 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003670 unsigned NewCreatedInstsCost = 0;
3671 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003672 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003673 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3674 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003675 assert(PromotedVal &&
3676 "TypePromotionHelper should have filtered out those cases");
3677
3678 // We would be able to merge only one extension in a load.
3679 // Therefore, if we have more than 1 new extension we heuristically
3680 // cut this search path, because it means we degrade the code quality.
3681 // With exactly 2, the transformation is neutral, because we will merge
3682 // one extension but leave one. However, we optimistically keep going,
3683 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003684 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3685 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003686 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00003687 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00003688 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003689 // The promotion is not profitable, rollback to the previous state.
3690 TPT.rollback(LastKnownGood);
3691 continue;
3692 }
3693 // The promotion is profitable.
3694 // Check if it exposes an ext(load).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003695 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
3696 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003697 // If we have created a new extension, i.e., now we have two
3698 // extensions. We must make sure one of them is merged with
3699 // the load, otherwise we may degrade the code quality.
3700 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3701 // Promotion happened.
3702 return true;
3703 // If this does not help to expose an ext(load) then, rollback.
3704 TPT.rollback(LastKnownGood);
3705 }
3706 // None of the extension can form an ext(load).
3707 LI = nullptr;
3708 Inst = nullptr;
3709 return false;
3710}
3711
Dan Gohman99429a02009-10-16 20:59:35 +00003712/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3713/// basic block as the load, unless conditions are unfavorable. This allows
3714/// SelectionDAG to fold the extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003715/// \p I[in/out] the extension may be modified during the process if some
3716/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003717///
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003718bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3719 // Try to promote a chain of computation if it allows to form
3720 // an extended load.
3721 TypePromotionTransaction TPT;
3722 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3723 TPT.getRestorationPoint();
3724 SmallVector<Instruction *, 1> Exts;
3725 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003726 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003727 LoadInst *LI = nullptr;
3728 Instruction *OldExt = I;
3729 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3730 if (!LI || !I) {
3731 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3732 "the code must remain the same");
3733 I = OldExt;
3734 return false;
3735 }
Dan Gohman99429a02009-10-16 20:59:35 +00003736
3737 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003738 // Make the cheap checks first if we did not promote.
3739 // If we promoted, we need to check if it is indeed profitable.
3740 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003741 return false;
3742
Mehdi Amini44ede332015-07-09 02:09:04 +00003743 EVT VT = TLI->getValueType(*DL, I->getType());
3744 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003745
Dan Gohman99429a02009-10-16 20:59:35 +00003746 // If the load has other users and the truncate is not free, this probably
3747 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003748 if (!LI->hasOneUse() && TLI &&
3749 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003750 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3751 I = OldExt;
3752 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003753 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003754 }
Dan Gohman99429a02009-10-16 20:59:35 +00003755
3756 // Check whether the target supports casts folded into loads.
3757 unsigned LType;
3758 if (isa<ZExtInst>(I))
3759 LType = ISD::ZEXTLOAD;
3760 else {
3761 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3762 LType = ISD::SEXTLOAD;
3763 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003764 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003765 I = OldExt;
3766 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003767 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003768 }
Dan Gohman99429a02009-10-16 20:59:35 +00003769
3770 // Move the extend into the same block as the load, so that SelectionDAG
3771 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003772 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003773 I->removeFromParent();
3774 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003775 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003776 return true;
3777}
3778
Evan Chengd3d80172007-12-05 23:58:20 +00003779bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3780 BasicBlock *DefBB = I->getParent();
3781
Bob Wilsonff714f92010-09-21 21:44:14 +00003782 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003783 // other uses of the source with result of extension.
3784 Value *Src = I->getOperand(0);
3785 if (Src->hasOneUse())
3786 return false;
3787
Evan Cheng2011df42007-12-13 07:50:36 +00003788 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003789 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003790 return false;
3791
Evan Cheng7bc89422007-12-12 00:51:06 +00003792 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003793 // this block.
3794 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003795 return false;
3796
Evan Chengd3d80172007-12-05 23:58:20 +00003797 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003798 for (User *U : I->users()) {
3799 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003800
3801 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003802 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003803 if (UserBB == DefBB) continue;
3804 DefIsLiveOut = true;
3805 break;
3806 }
3807 if (!DefIsLiveOut)
3808 return false;
3809
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003810 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003811 for (User *U : Src->users()) {
3812 Instruction *UI = cast<Instruction>(U);
3813 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003814 if (UserBB == DefBB) continue;
3815 // Be conservative. We don't want this xform to end up introducing
3816 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003817 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003818 return false;
3819 }
3820
Evan Chengd3d80172007-12-05 23:58:20 +00003821 // InsertedTruncs - Only insert one trunc in each block once.
3822 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3823
3824 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003825 for (Use &U : Src->uses()) {
3826 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003827
3828 // Figure out which BB this ext is used in.
3829 BasicBlock *UserBB = User->getParent();
3830 if (UserBB == DefBB) continue;
3831
3832 // Both src and def are live in this block. Rewrite the use.
3833 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3834
3835 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003836 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003837 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003838 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003839 }
3840
3841 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003842 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003843 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003844 MadeChange = true;
3845 }
3846
3847 return MadeChange;
3848}
3849
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003850/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3851/// turned into an explicit branch.
3852static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3853 // FIXME: This should use the same heuristics as IfConversion to determine
3854 // whether a select is better represented as a branch. This requires that
3855 // branch probability metadata is preserved for the select, which is not the
3856 // case currently.
3857
3858 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3859
3860 // If the branch is predicted right, an out of order CPU can avoid blocking on
3861 // the compare. Emit cmovs on compares with a memory operand as branches to
3862 // avoid stalls on the load from memory. If the compare has more than one use
3863 // there's probably another cmov or setcc around so it's not worth emitting a
3864 // branch.
3865 if (!Cmp)
3866 return false;
3867
3868 Value *CmpOp0 = Cmp->getOperand(0);
3869 Value *CmpOp1 = Cmp->getOperand(1);
3870
3871 // We check that the memory operand has one use to avoid uses of the loaded
3872 // value directly after the compare, making branches unprofitable.
3873 return Cmp->hasOneUse() &&
3874 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3875 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3876}
3877
3878
Nadav Rotem9d832022012-09-02 12:10:19 +00003879/// If we have a SelectInst that will likely profit from branch prediction,
3880/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003881bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003882 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3883
3884 // Can we convert the 'select' to CF ?
3885 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003886 return false;
3887
Nadav Rotem9d832022012-09-02 12:10:19 +00003888 TargetLowering::SelectSupportKind SelectKind;
3889 if (VectorCond)
3890 SelectKind = TargetLowering::VectorMaskSelect;
3891 else if (SI->getType()->isVectorTy())
3892 SelectKind = TargetLowering::ScalarCondVectorVal;
3893 else
3894 SelectKind = TargetLowering::ScalarValSelect;
3895
3896 // Do we have efficient codegen support for this kind of 'selects' ?
3897 if (TLI->isSelectSupported(SelectKind)) {
3898 // We have efficient codegen support for the select instruction.
3899 // Check if it is profitable to keep this 'select'.
3900 if (!TLI->isPredictableSelectExpensive() ||
3901 !isFormingBranchFromSelectProfitable(SI))
3902 return false;
3903 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003904
3905 ModifiedDT = true;
3906
3907 // First, we split the block containing the select into 2 blocks.
3908 BasicBlock *StartBlock = SI->getParent();
3909 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3910 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3911
3912 // Create a new block serving as the landing pad for the branch.
3913 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3914 NextBlock->getParent(), NextBlock);
3915
3916 // Move the unconditional branch from the block with the select in it into our
3917 // landing pad block.
3918 StartBlock->getTerminator()->eraseFromParent();
3919 BranchInst::Create(NextBlock, SmallBlock);
3920
3921 // Insert the real conditional branch based on the original condition.
3922 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3923
3924 // The select itself is replaced with a PHI Node.
3925 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3926 PN->takeName(SI);
3927 PN->addIncoming(SI->getTrueValue(), StartBlock);
3928 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3929 SI->replaceAllUsesWith(PN);
3930 SI->eraseFromParent();
3931
3932 // Instruct OptimizeBlock to skip to the next block.
3933 CurInstIterator = StartBlock->end();
3934 ++NumSelectsExpanded;
3935 return true;
3936}
3937
Benjamin Kramer573ff362014-03-01 17:24:40 +00003938static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003939 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3940 int SplatElem = -1;
3941 for (unsigned i = 0; i < Mask.size(); ++i) {
3942 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3943 return false;
3944 SplatElem = Mask[i];
3945 }
3946
3947 return true;
3948}
3949
3950/// Some targets have expensive vector shifts if the lanes aren't all the same
3951/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3952/// it's often worth sinking a shufflevector splat down to its use so that
3953/// codegen can spot all lanes are identical.
3954bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3955 BasicBlock *DefBB = SVI->getParent();
3956
3957 // Only do this xform if variable vector shifts are particularly expensive.
3958 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3959 return false;
3960
3961 // We only expect better codegen by sinking a shuffle if we can recognise a
3962 // constant splat.
3963 if (!isBroadcastShuffle(SVI))
3964 return false;
3965
3966 // InsertedShuffles - Only insert a shuffle in each block once.
3967 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3968
3969 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003970 for (User *U : SVI->users()) {
3971 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003972
3973 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003974 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003975 if (UserBB == DefBB) continue;
3976
3977 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003978 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003979
3980 // Everything checks out, sink the shuffle if the user's block doesn't
3981 // already have a copy.
3982 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3983
3984 if (!InsertedShuffle) {
3985 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3986 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3987 SVI->getOperand(1),
3988 SVI->getOperand(2), "", InsertPt);
3989 }
3990
Chandler Carruthcdf47882014-03-09 03:16:01 +00003991 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003992 MadeChange = true;
3993 }
3994
3995 // If we removed all uses, nuke the shuffle.
3996 if (SVI->use_empty()) {
3997 SVI->eraseFromParent();
3998 MadeChange = true;
3999 }
4000
4001 return MadeChange;
4002}
4003
Quentin Colombetc32615d2014-10-31 17:52:53 +00004004namespace {
4005/// \brief Helper class to promote a scalar operation to a vector one.
4006/// This class is used to move downward extractelement transition.
4007/// E.g.,
4008/// a = vector_op <2 x i32>
4009/// b = extractelement <2 x i32> a, i32 0
4010/// c = scalar_op b
4011/// store c
4012///
4013/// =>
4014/// a = vector_op <2 x i32>
4015/// c = vector_op a (equivalent to scalar_op on the related lane)
4016/// * d = extractelement <2 x i32> c, i32 0
4017/// * store d
4018/// Assuming both extractelement and store can be combine, we get rid of the
4019/// transition.
4020class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004021 /// DataLayout associated with the current module.
4022 const DataLayout &DL;
4023
Quentin Colombetc32615d2014-10-31 17:52:53 +00004024 /// Used to perform some checks on the legality of vector operations.
4025 const TargetLowering &TLI;
4026
4027 /// Used to estimated the cost of the promoted chain.
4028 const TargetTransformInfo &TTI;
4029
4030 /// The transition being moved downwards.
4031 Instruction *Transition;
4032 /// The sequence of instructions to be promoted.
4033 SmallVector<Instruction *, 4> InstsToBePromoted;
4034 /// Cost of combining a store and an extract.
4035 unsigned StoreExtractCombineCost;
4036 /// Instruction that will be combined with the transition.
4037 Instruction *CombineInst;
4038
4039 /// \brief The instruction that represents the current end of the transition.
4040 /// Since we are faking the promotion until we reach the end of the chain
4041 /// of computation, we need a way to get the current end of the transition.
4042 Instruction *getEndOfTransition() const {
4043 if (InstsToBePromoted.empty())
4044 return Transition;
4045 return InstsToBePromoted.back();
4046 }
4047
4048 /// \brief Return the index of the original value in the transition.
4049 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4050 /// c, is at index 0.
4051 unsigned getTransitionOriginalValueIdx() const {
4052 assert(isa<ExtractElementInst>(Transition) &&
4053 "Other kind of transitions are not supported yet");
4054 return 0;
4055 }
4056
4057 /// \brief Return the index of the index in the transition.
4058 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4059 /// is at index 1.
4060 unsigned getTransitionIdx() const {
4061 assert(isa<ExtractElementInst>(Transition) &&
4062 "Other kind of transitions are not supported yet");
4063 return 1;
4064 }
4065
4066 /// \brief Get the type of the transition.
4067 /// This is the type of the original value.
4068 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4069 /// transition is <2 x i32>.
4070 Type *getTransitionType() const {
4071 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4072 }
4073
4074 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4075 /// I.e., we have the following sequence:
4076 /// Def = Transition <ty1> a to <ty2>
4077 /// b = ToBePromoted <ty2> Def, ...
4078 /// =>
4079 /// b = ToBePromoted <ty1> a, ...
4080 /// Def = Transition <ty1> ToBePromoted to <ty2>
4081 void promoteImpl(Instruction *ToBePromoted);
4082
4083 /// \brief Check whether or not it is profitable to promote all the
4084 /// instructions enqueued to be promoted.
4085 bool isProfitableToPromote() {
4086 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4087 unsigned Index = isa<ConstantInt>(ValIdx)
4088 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4089 : -1;
4090 Type *PromotedType = getTransitionType();
4091
4092 StoreInst *ST = cast<StoreInst>(CombineInst);
4093 unsigned AS = ST->getPointerAddressSpace();
4094 unsigned Align = ST->getAlignment();
4095 // Check if this store is supported.
4096 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004097 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4098 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004099 // If this is not supported, there is no way we can combine
4100 // the extract with the store.
4101 return false;
4102 }
4103
4104 // The scalar chain of computation has to pay for the transition
4105 // scalar to vector.
4106 // The vector chain has to account for the combining cost.
4107 uint64_t ScalarCost =
4108 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4109 uint64_t VectorCost = StoreExtractCombineCost;
4110 for (const auto &Inst : InstsToBePromoted) {
4111 // Compute the cost.
4112 // By construction, all instructions being promoted are arithmetic ones.
4113 // Moreover, one argument is a constant that can be viewed as a splat
4114 // constant.
4115 Value *Arg0 = Inst->getOperand(0);
4116 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4117 isa<ConstantFP>(Arg0);
4118 TargetTransformInfo::OperandValueKind Arg0OVK =
4119 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4120 : TargetTransformInfo::OK_AnyValue;
4121 TargetTransformInfo::OperandValueKind Arg1OVK =
4122 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4123 : TargetTransformInfo::OK_AnyValue;
4124 ScalarCost += TTI.getArithmeticInstrCost(
4125 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4126 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4127 Arg0OVK, Arg1OVK);
4128 }
4129 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4130 << ScalarCost << "\nVector: " << VectorCost << '\n');
4131 return ScalarCost > VectorCost;
4132 }
4133
4134 /// \brief Generate a constant vector with \p Val with the same
4135 /// number of elements as the transition.
4136 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004137 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004138 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4139 /// otherwise we generate a vector with as many undef as possible:
4140 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4141 /// used at the index of the extract.
4142 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4143 unsigned ExtractIdx = UINT_MAX;
4144 if (!UseSplat) {
4145 // If we cannot determine where the constant must be, we have to
4146 // use a splat constant.
4147 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4148 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4149 ExtractIdx = CstVal->getSExtValue();
4150 else
4151 UseSplat = true;
4152 }
4153
4154 unsigned End = getTransitionType()->getVectorNumElements();
4155 if (UseSplat)
4156 return ConstantVector::getSplat(End, Val);
4157
4158 SmallVector<Constant *, 4> ConstVec;
4159 UndefValue *UndefVal = UndefValue::get(Val->getType());
4160 for (unsigned Idx = 0; Idx != End; ++Idx) {
4161 if (Idx == ExtractIdx)
4162 ConstVec.push_back(Val);
4163 else
4164 ConstVec.push_back(UndefVal);
4165 }
4166 return ConstantVector::get(ConstVec);
4167 }
4168
4169 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4170 /// in \p Use can trigger undefined behavior.
4171 static bool canCauseUndefinedBehavior(const Instruction *Use,
4172 unsigned OperandIdx) {
4173 // This is not safe to introduce undef when the operand is on
4174 // the right hand side of a division-like instruction.
4175 if (OperandIdx != 1)
4176 return false;
4177 switch (Use->getOpcode()) {
4178 default:
4179 return false;
4180 case Instruction::SDiv:
4181 case Instruction::UDiv:
4182 case Instruction::SRem:
4183 case Instruction::URem:
4184 return true;
4185 case Instruction::FDiv:
4186 case Instruction::FRem:
4187 return !Use->hasNoNaNs();
4188 }
4189 llvm_unreachable(nullptr);
4190 }
4191
4192public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004193 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4194 const TargetTransformInfo &TTI, Instruction *Transition,
4195 unsigned CombineCost)
4196 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004197 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4198 assert(Transition && "Do not know how to promote null");
4199 }
4200
4201 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4202 bool canPromote(const Instruction *ToBePromoted) const {
4203 // We could support CastInst too.
4204 return isa<BinaryOperator>(ToBePromoted);
4205 }
4206
4207 /// \brief Check if it is profitable to promote \p ToBePromoted
4208 /// by moving downward the transition through.
4209 bool shouldPromote(const Instruction *ToBePromoted) const {
4210 // Promote only if all the operands can be statically expanded.
4211 // Indeed, we do not want to introduce any new kind of transitions.
4212 for (const Use &U : ToBePromoted->operands()) {
4213 const Value *Val = U.get();
4214 if (Val == getEndOfTransition()) {
4215 // If the use is a division and the transition is on the rhs,
4216 // we cannot promote the operation, otherwise we may create a
4217 // division by zero.
4218 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4219 return false;
4220 continue;
4221 }
4222 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4223 !isa<ConstantFP>(Val))
4224 return false;
4225 }
4226 // Check that the resulting operation is legal.
4227 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4228 if (!ISDOpcode)
4229 return false;
4230 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004231 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004232 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004233 }
4234
4235 /// \brief Check whether or not \p Use can be combined
4236 /// with the transition.
4237 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4238 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4239
4240 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4241 void enqueueForPromotion(Instruction *ToBePromoted) {
4242 InstsToBePromoted.push_back(ToBePromoted);
4243 }
4244
4245 /// \brief Set the instruction that will be combined with the transition.
4246 void recordCombineInstruction(Instruction *ToBeCombined) {
4247 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4248 CombineInst = ToBeCombined;
4249 }
4250
4251 /// \brief Promote all the instructions enqueued for promotion if it is
4252 /// is profitable.
4253 /// \return True if the promotion happened, false otherwise.
4254 bool promote() {
4255 // Check if there is something to promote.
4256 // Right now, if we do not have anything to combine with,
4257 // we assume the promotion is not profitable.
4258 if (InstsToBePromoted.empty() || !CombineInst)
4259 return false;
4260
4261 // Check cost.
4262 if (!StressStoreExtract && !isProfitableToPromote())
4263 return false;
4264
4265 // Promote.
4266 for (auto &ToBePromoted : InstsToBePromoted)
4267 promoteImpl(ToBePromoted);
4268 InstsToBePromoted.clear();
4269 return true;
4270 }
4271};
4272} // End of anonymous namespace.
4273
4274void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4275 // At this point, we know that all the operands of ToBePromoted but Def
4276 // can be statically promoted.
4277 // For Def, we need to use its parameter in ToBePromoted:
4278 // b = ToBePromoted ty1 a
4279 // Def = Transition ty1 b to ty2
4280 // Move the transition down.
4281 // 1. Replace all uses of the promoted operation by the transition.
4282 // = ... b => = ... Def.
4283 assert(ToBePromoted->getType() == Transition->getType() &&
4284 "The type of the result of the transition does not match "
4285 "the final type");
4286 ToBePromoted->replaceAllUsesWith(Transition);
4287 // 2. Update the type of the uses.
4288 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4289 Type *TransitionTy = getTransitionType();
4290 ToBePromoted->mutateType(TransitionTy);
4291 // 3. Update all the operands of the promoted operation with promoted
4292 // operands.
4293 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4294 for (Use &U : ToBePromoted->operands()) {
4295 Value *Val = U.get();
4296 Value *NewVal = nullptr;
4297 if (Val == Transition)
4298 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4299 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4300 isa<ConstantFP>(Val)) {
4301 // Use a splat constant if it is not safe to use undef.
4302 NewVal = getConstantVector(
4303 cast<Constant>(Val),
4304 isa<UndefValue>(Val) ||
4305 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4306 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004307 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4308 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004309 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4310 }
4311 Transition->removeFromParent();
4312 Transition->insertAfter(ToBePromoted);
4313 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4314}
4315
4316/// Some targets can do store(extractelement) with one instruction.
4317/// Try to push the extractelement towards the stores when the target
4318/// has this feature and this is profitable.
4319bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4320 unsigned CombineCost = UINT_MAX;
4321 if (DisableStoreExtract || !TLI ||
4322 (!StressStoreExtract &&
4323 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4324 Inst->getOperand(1), CombineCost)))
4325 return false;
4326
4327 // At this point we know that Inst is a vector to scalar transition.
4328 // Try to move it down the def-use chain, until:
4329 // - We can combine the transition with its single use
4330 // => we got rid of the transition.
4331 // - We escape the current basic block
4332 // => we would need to check that we are moving it at a cheaper place and
4333 // we do not do that for now.
4334 BasicBlock *Parent = Inst->getParent();
4335 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00004336 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00004337 // If the transition has more than one use, assume this is not going to be
4338 // beneficial.
4339 while (Inst->hasOneUse()) {
4340 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4341 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4342
4343 if (ToBePromoted->getParent() != Parent) {
4344 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4345 << ToBePromoted->getParent()->getName()
4346 << ") than the transition (" << Parent->getName() << ").\n");
4347 return false;
4348 }
4349
4350 if (VPH.canCombine(ToBePromoted)) {
4351 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4352 << "will be combined with: " << *ToBePromoted << '\n');
4353 VPH.recordCombineInstruction(ToBePromoted);
4354 bool Changed = VPH.promote();
4355 NumStoreExtractExposed += Changed;
4356 return Changed;
4357 }
4358
4359 DEBUG(dbgs() << "Try promoting.\n");
4360 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4361 return false;
4362
4363 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4364
4365 VPH.enqueueForPromotion(ToBePromoted);
4366 Inst = ToBePromoted;
4367 }
4368 return false;
4369}
4370
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004371bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004372 // Bail out if we inserted the instruction to prevent optimizations from
4373 // stepping on each other's toes.
4374 if (InsertedInsts.count(I))
4375 return false;
4376
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004377 if (PHINode *P = dyn_cast<PHINode>(I)) {
4378 // It is possible for very late stage optimizations (such as SimplifyCFG)
4379 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4380 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00004381 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004382 P->replaceAllUsesWith(V);
4383 P->eraseFromParent();
4384 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004385 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004386 }
Chris Lattneree588de2011-01-15 07:29:01 +00004387 return false;
4388 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004389
Chris Lattneree588de2011-01-15 07:29:01 +00004390 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004391 // If the source of the cast is a constant, then this should have
4392 // already been constant folded. The only reason NOT to constant fold
4393 // it is if something (e.g. LSR) was careful to place the constant
4394 // evaluation in a block other than then one that uses it (e.g. to hoist
4395 // the address of globals out of a loop). If this is the case, we don't
4396 // want to forward-subst the cast.
4397 if (isa<Constant>(CI->getOperand(0)))
4398 return false;
4399
Mehdi Amini44ede332015-07-09 02:09:04 +00004400 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00004401 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004402
Chris Lattneree588de2011-01-15 07:29:01 +00004403 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004404 /// Sink a zext or sext into its user blocks if the target type doesn't
4405 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00004406 if (TLI &&
4407 TLI->getTypeAction(CI->getContext(),
4408 TLI->getValueType(*DL, CI->getType())) ==
4409 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004410 return SinkCast(CI);
4411 } else {
4412 bool MadeChange = MoveExtToFormExtLoad(I);
4413 return MadeChange | OptimizeExtUses(I);
4414 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004415 }
Chris Lattneree588de2011-01-15 07:29:01 +00004416 return false;
4417 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004418
Chris Lattneree588de2011-01-15 07:29:01 +00004419 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004420 if (!TLI || !TLI->hasMultipleConditionRegisters())
4421 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004422
Chris Lattneree588de2011-01-15 07:29:01 +00004423 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004424 if (TLI) {
4425 unsigned AS = LI->getPointerAddressSpace();
4426 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
4427 }
Hans Wennborgf3254832012-10-30 11:23:25 +00004428 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004429 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004430
Chris Lattneree588de2011-01-15 07:29:01 +00004431 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004432 if (TLI) {
4433 unsigned AS = SI->getPointerAddressSpace();
Chris Lattneree588de2011-01-15 07:29:01 +00004434 return OptimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004435 SI->getOperand(0)->getType(), AS);
4436 }
Chris Lattneree588de2011-01-15 07:29:01 +00004437 return false;
4438 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004439
Yi Jiangd069f632014-04-21 19:34:27 +00004440 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4441
4442 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4443 BinOp->getOpcode() == Instruction::LShr)) {
4444 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4445 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00004446 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00004447
4448 return false;
4449 }
4450
Chris Lattneree588de2011-01-15 07:29:01 +00004451 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004452 if (GEPI->hasAllZeroIndices()) {
4453 /// The GEP operand must be a pointer, so must its result -> BitCast
4454 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4455 GEPI->getName(), GEPI);
4456 GEPI->replaceAllUsesWith(NC);
4457 GEPI->eraseFromParent();
4458 ++NumGEPsElim;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004459 OptimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004460 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004461 }
Chris Lattneree588de2011-01-15 07:29:01 +00004462 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004463 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004464
Chris Lattneree588de2011-01-15 07:29:01 +00004465 if (CallInst *CI = dyn_cast<CallInst>(I))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004466 return OptimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004467
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004468 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4469 return OptimizeSelectInst(SI);
4470
Tim Northoveraeb8e062014-02-19 10:02:43 +00004471 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4472 return OptimizeShuffleVectorInst(SVI);
4473
Quentin Colombetc32615d2014-10-31 17:52:53 +00004474 if (isa<ExtractElementInst>(I))
4475 return OptimizeExtractElementInst(I);
4476
Chris Lattneree588de2011-01-15 07:29:01 +00004477 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004478}
4479
Chris Lattnerf2836d12007-03-31 04:06:36 +00004480// In this pass we look for GEP and cast instructions that are used
4481// across basic blocks and rewrite them to improve basic-block-at-a-time
4482// selection.
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004483bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004484 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004485 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004486
Chris Lattner7a277142011-01-15 07:14:54 +00004487 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004488 while (CurInstIterator != BB.end()) {
4489 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4490 if (ModifiedDT)
4491 return true;
4492 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00004493 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4494
Chris Lattnerf2836d12007-03-31 04:06:36 +00004495 return MadeChange;
4496}
Devang Patel53771ba2011-08-18 00:50:51 +00004497
4498// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004499// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004500// find a node corresponding to the value.
4501bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4502 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004503 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004504 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004505 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithe90f1162015-01-08 21:07:55 +00004506 Instruction *Insn = BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00004507 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004508 // Leave dbg.values that refer to an alloca alone. These
4509 // instrinsics describe the address of a variable (= the alloca)
4510 // being taken. They should not be moved next to the alloca
4511 // (and to the beginning of the scope), but rather stay close to
4512 // where said address is used.
4513 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004514 PrevNonDbgInst = Insn;
4515 continue;
4516 }
4517
4518 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4519 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4520 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4521 DVI->removeFromParent();
4522 if (isa<PHINode>(VI))
4523 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4524 else
4525 DVI->insertAfter(VI);
4526 MadeChange = true;
4527 ++NumDbgValueMoved;
4528 }
4529 }
4530 }
4531 return MadeChange;
4532}
Tim Northovercea0abb2014-03-29 08:22:29 +00004533
4534// If there is a sequence that branches based on comparing a single bit
4535// against zero that can be combined into a single instruction, and the
4536// target supports folding these into a single instruction, sink the
4537// mask and compare into the branch uses. Do this before OptimizeBlock ->
4538// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4539// searched for.
4540bool CodeGenPrepare::sinkAndCmp(Function &F) {
4541 if (!EnableAndCmpSinking)
4542 return false;
4543 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4544 return false;
4545 bool MadeChange = false;
4546 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4547 BasicBlock *BB = I++;
4548
4549 // Does this BB end with the following?
4550 // %andVal = and %val, #single-bit-set
4551 // %icmpVal = icmp %andResult, 0
4552 // br i1 %cmpVal label %dest1, label %dest2"
4553 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4554 if (!Brcc || !Brcc->isConditional())
4555 continue;
4556 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4557 if (!Cmp || Cmp->getParent() != BB)
4558 continue;
4559 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4560 if (!Zero || !Zero->isZero())
4561 continue;
4562 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4563 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4564 continue;
4565 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4566 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4567 continue;
4568 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4569
4570 // Push the "and; icmp" for any users that are conditional branches.
4571 // Since there can only be one branch use per BB, we don't need to keep
4572 // track of which BBs we insert into.
4573 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4574 UI != E; ) {
4575 Use &TheUse = *UI;
4576 // Find brcc use.
4577 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4578 ++UI;
4579 if (!BrccUser || !BrccUser->isConditional())
4580 continue;
4581 BasicBlock *UserBB = BrccUser->getParent();
4582 if (UserBB == BB) continue;
4583 DEBUG(dbgs() << "found Brcc use\n");
4584
4585 // Sink the "and; icmp" to use.
4586 MadeChange = true;
4587 BinaryOperator *NewAnd =
4588 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4589 BrccUser);
4590 CmpInst *NewCmp =
4591 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4592 "", BrccUser);
4593 TheUse = NewCmp;
4594 ++NumAndCmpsMoved;
4595 DEBUG(BrccUser->getParent()->dump());
4596 }
4597 }
4598 return MadeChange;
4599}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004600
Juergen Ributzka194350a2014-12-09 17:32:12 +00004601/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4602/// success, or returns false if no or invalid metadata was found.
4603static bool extractBranchMetadata(BranchInst *BI,
4604 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4605 assert(BI->isConditional() &&
4606 "Looking for probabilities on unconditional branch?");
4607 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4608 if (!ProfileData || ProfileData->getNumOperands() != 3)
4609 return false;
4610
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004611 const auto *CITrue =
4612 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4613 const auto *CIFalse =
4614 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004615 if (!CITrue || !CIFalse)
4616 return false;
4617
4618 ProbTrue = CITrue->getValue().getZExtValue();
4619 ProbFalse = CIFalse->getValue().getZExtValue();
4620
4621 return true;
4622}
4623
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004624/// \brief Scale down both weights to fit into uint32_t.
4625static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4626 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4627 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4628 NewTrue = NewTrue / Scale;
4629 NewFalse = NewFalse / Scale;
4630}
4631
4632/// \brief Some targets prefer to split a conditional branch like:
4633/// \code
4634/// %0 = icmp ne i32 %a, 0
4635/// %1 = icmp ne i32 %b, 0
4636/// %or.cond = or i1 %0, %1
4637/// br i1 %or.cond, label %TrueBB, label %FalseBB
4638/// \endcode
4639/// into multiple branch instructions like:
4640/// \code
4641/// bb1:
4642/// %0 = icmp ne i32 %a, 0
4643/// br i1 %0, label %TrueBB, label %bb2
4644/// bb2:
4645/// %1 = icmp ne i32 %b, 0
4646/// br i1 %1, label %TrueBB, label %FalseBB
4647/// \endcode
4648/// This usually allows instruction selection to do even further optimizations
4649/// and combine the compare with the branch instruction. Currently this is
4650/// applied for targets which have "cheap" jump instructions.
4651///
4652/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4653///
4654bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00004655 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004656 return false;
4657
4658 bool MadeChange = false;
4659 for (auto &BB : F) {
4660 // Does this BB end with the following?
4661 // %cond1 = icmp|fcmp|binary instruction ...
4662 // %cond2 = icmp|fcmp|binary instruction ...
4663 // %cond.or = or|and i1 %cond1, cond2
4664 // br i1 %cond.or label %dest1, label %dest2"
4665 BinaryOperator *LogicOp;
4666 BasicBlock *TBB, *FBB;
4667 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4668 continue;
4669
Sanjay Patel42574202015-09-02 19:23:23 +00004670 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4671 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
4672 continue;
4673
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004674 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004675 Value *Cond1, *Cond2;
4676 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4677 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004678 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004679 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4680 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004681 Opc = Instruction::Or;
4682 else
4683 continue;
4684
4685 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4686 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4687 continue;
4688
4689 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4690
4691 // Create a new BB.
4692 auto *InsertBefore = std::next(Function::iterator(BB))
4693 .getNodePtrUnchecked();
4694 auto TmpBB = BasicBlock::Create(BB.getContext(),
4695 BB.getName() + ".cond.split",
4696 BB.getParent(), InsertBefore);
4697
4698 // Update original basic block by using the first condition directly by the
4699 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004700 Br1->setCondition(Cond1);
4701 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004702
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004703 // Depending on the conditon we have to either replace the true or the false
4704 // successor of the original branch instruction.
4705 if (Opc == Instruction::And)
4706 Br1->setSuccessor(0, TmpBB);
4707 else
4708 Br1->setSuccessor(1, TmpBB);
4709
4710 // Fill in the new basic block.
4711 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004712 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4713 I->removeFromParent();
4714 I->insertBefore(Br2);
4715 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004716
4717 // Update PHI nodes in both successors. The original BB needs to be
4718 // replaced in one succesor's PHI nodes, because the branch comes now from
4719 // the newly generated BB (NewBB). In the other successor we need to add one
4720 // incoming edge to the PHI nodes, because both branch instructions target
4721 // now the same successor. Depending on the original branch condition
4722 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4723 // we perfrom the correct update for the PHI nodes.
4724 // This doesn't change the successor order of the just created branch
4725 // instruction (or any other instruction).
4726 if (Opc == Instruction::Or)
4727 std::swap(TBB, FBB);
4728
4729 // Replace the old BB with the new BB.
4730 for (auto &I : *TBB) {
4731 PHINode *PN = dyn_cast<PHINode>(&I);
4732 if (!PN)
4733 break;
4734 int i;
4735 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4736 PN->setIncomingBlock(i, TmpBB);
4737 }
4738
4739 // Add another incoming edge form the new BB.
4740 for (auto &I : *FBB) {
4741 PHINode *PN = dyn_cast<PHINode>(&I);
4742 if (!PN)
4743 break;
4744 auto *Val = PN->getIncomingValueForBlock(&BB);
4745 PN->addIncoming(Val, TmpBB);
4746 }
4747
4748 // Update the branch weights (from SelectionDAGBuilder::
4749 // FindMergedConditions).
4750 if (Opc == Instruction::Or) {
4751 // Codegen X | Y as:
4752 // BB1:
4753 // jmp_if_X TBB
4754 // jmp TmpBB
4755 // TmpBB:
4756 // jmp_if_Y TBB
4757 // jmp FBB
4758 //
4759
4760 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4761 // The requirement is that
4762 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4763 // = TrueProb for orignal BB.
4764 // Assuming the orignal weights are A and B, one choice is to set BB1's
4765 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4766 // assumes that
4767 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4768 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4769 // TmpBB, but the math is more complicated.
4770 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004771 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004772 uint64_t NewTrueWeight = TrueWeight;
4773 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4774 scaleWeights(NewTrueWeight, NewFalseWeight);
4775 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4776 .createBranchWeights(TrueWeight, FalseWeight));
4777
4778 NewTrueWeight = TrueWeight;
4779 NewFalseWeight = 2 * FalseWeight;
4780 scaleWeights(NewTrueWeight, NewFalseWeight);
4781 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4782 .createBranchWeights(TrueWeight, FalseWeight));
4783 }
4784 } else {
4785 // Codegen X & Y as:
4786 // BB1:
4787 // jmp_if_X TmpBB
4788 // jmp FBB
4789 // TmpBB:
4790 // jmp_if_Y TBB
4791 // jmp FBB
4792 //
4793 // This requires creation of TmpBB after CurBB.
4794
4795 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4796 // The requirement is that
4797 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4798 // = FalseProb for orignal BB.
4799 // Assuming the orignal weights are A and B, one choice is to set BB1's
4800 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4801 // assumes that
4802 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4803 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004804 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004805 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4806 uint64_t NewFalseWeight = FalseWeight;
4807 scaleWeights(NewTrueWeight, NewFalseWeight);
4808 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4809 .createBranchWeights(TrueWeight, FalseWeight));
4810
4811 NewTrueWeight = 2 * TrueWeight;
4812 NewFalseWeight = FalseWeight;
4813 scaleWeights(NewTrueWeight, NewFalseWeight);
4814 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4815 .createBranchWeights(TrueWeight, FalseWeight));
4816 }
4817 }
4818
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004819 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00004820 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004821 ModifiedDT = true;
4822
4823 MadeChange = true;
4824
4825 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4826 TmpBB->dump());
4827 }
4828 return MadeChange;
4829}