blob: 2d260f5d520338a6d1f036e5a80c6a4982edd179 [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"
Sanjay Patel69a50a12015-10-19 21:59:12 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000024#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000030#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000035#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000036#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000037#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000038#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000039#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000040#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000041#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000042#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000044#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000045#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000048#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000050#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000051using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000052using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000053
Chandler Carruth1b9dde02014-04-22 02:02:50 +000054#define DEBUG_TYPE "codegenprepare"
55
Cameron Zwarichced753f2011-01-05 17:27:27 +000056STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000057STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
58STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000059STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
60 "sunken Cmps");
61STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
62 "of sunken Casts");
63STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
64 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000065STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
66STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
67STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000068STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000069STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000070STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000071STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000072
Cameron Zwarich338d3622011-03-11 21:52:04 +000073static cl::opt<bool> DisableBranchOpts(
74 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
75 cl::desc("Disable branch optimizations in CodeGenPrepare"));
76
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000077static cl::opt<bool>
78 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
79 cl::desc("Disable GC optimizations in CodeGenPrepare"));
80
Benjamin Kramer3d38c172012-05-06 14:25:16 +000081static cl::opt<bool> DisableSelectToBranch(
82 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
83 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000084
Hal Finkelc3998302014-04-12 00:59:48 +000085static cl::opt<bool> AddrSinkUsingGEPs(
86 "addr-sink-using-gep", cl::Hidden, cl::init(false),
87 cl::desc("Address sinking in CGP using GEPs."));
88
Tim Northovercea0abb2014-03-29 08:22:29 +000089static cl::opt<bool> EnableAndCmpSinking(
90 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
91 cl::desc("Enable sinkinig and/cmp into branches."));
92
Quentin Colombetc32615d2014-10-31 17:52:53 +000093static cl::opt<bool> DisableStoreExtract(
94 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
95 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
96
97static cl::opt<bool> StressStoreExtract(
98 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
99 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
100
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000101static cl::opt<bool> DisableExtLdPromotion(
102 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
103 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
104 "CodeGenPrepare"));
105
106static cl::opt<bool> StressExtLdPromotion(
107 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
108 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
109 "optimization in CodeGenPrepare"));
110
Eric Christopherc1ea1492008-09-24 05:32:41 +0000111namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000112typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000113typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000114typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000115class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000116
Chris Lattner2dd09db2009-09-02 06:11:42 +0000117 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000118 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000119 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000120 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000121 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000122
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000123 /// As we scan instructions optimizing them, this is the next instruction
124 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000125 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000126
Evan Cheng0663f232011-03-21 01:19:09 +0000127 /// Keeps track of non-local addresses that have been sunk into a block.
128 /// This allows us to avoid inserting duplicate code for blocks with
129 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000130 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000131
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000132 /// Keeps track of all instructions inserted for the current function.
133 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000134 /// Keeps track of the type of the related instruction before their
135 /// promotion for the current function.
136 InstrToOrigTy PromotedInsts;
137
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000138 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000139 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000140
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000141 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000142 bool OptSize;
143
Mehdi Amini4fe37982015-07-07 18:45:17 +0000144 /// DataLayout for the Function being processed.
145 const DataLayout *DL;
146
Chris Lattnerf2836d12007-03-31 04:06:36 +0000147 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000148 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000149 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000150 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000151 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
152 }
Craig Topper4584cd52014-03-07 09:26:03 +0000153 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000154
Craig Topper4584cd52014-03-07 09:26:03 +0000155 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000156
Craig Topper4584cd52014-03-07 09:26:03 +0000157 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000158 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000159 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000160 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000161 }
162
Chris Lattnerf2836d12007-03-31 04:06:36 +0000163 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000164 bool eliminateFallThrough(Function &F);
165 bool eliminateMostlyEmptyBlocks(Function &F);
166 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
167 void eliminateMostlyEmptyBlock(BasicBlock *BB);
168 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
169 bool optimizeInst(Instruction *I, bool& ModifiedDT);
170 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000171 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000172 bool optimizeInlineAsmInst(CallInst *CS);
173 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
174 bool moveExtToFormExtLoad(Instruction *&I);
175 bool optimizeExtUses(Instruction *I);
176 bool optimizeSelectInst(SelectInst *SI);
177 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
178 bool optimizeExtractElementInst(Instruction *Inst);
179 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
180 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000181 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000182 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000183 Instruction *&Inst,
184 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000185 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000186 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000187 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000188 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000189 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000190}
Devang Patel09f162c2007-05-01 21:15:47 +0000191
Devang Patel8c78a0b2007-05-03 01:11:54 +0000192char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000193INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
194 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000195
Bill Wendling7a639ea2013-06-19 21:07:11 +0000196FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
197 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000198}
199
Chris Lattnerf2836d12007-03-31 04:06:36 +0000200bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000201 if (skipOptnoneFunction(F))
202 return false;
203
Mehdi Amini4fe37982015-07-07 18:45:17 +0000204 DL = &F.getParent()->getDataLayout();
205
Chris Lattnerf2836d12007-03-31 04:06:36 +0000206 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000207 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000208 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000209 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000210
Devang Patel8f606d72011-03-24 15:35:25 +0000211 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000212 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000213 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000214 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000215 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000216 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000217
Preston Gurdcdf540d2012-09-04 18:22:17 +0000218 /// This optimization identifies DIV instructions that can be
219 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000220 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000221 const DenseMap<unsigned int, unsigned int> &BypassWidths =
222 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000223 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000224 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000225 }
226
227 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000228 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000229 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000230
Devang Patel53771ba2011-08-18 00:50:51 +0000231 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000232 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000233 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000234 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000235
Tim Northovercea0abb2014-03-29 08:22:29 +0000236 // If there is a mask, compare against zero, and branch that can be combined
237 // into a single target instruction, push the mask and compare into branch
238 // users. Do this before OptimizeBlock -> OptimizeInst ->
239 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000240 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000241 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000242 EverMadeChange |= splitBranchCondition(F);
243 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000244
Chris Lattnerc3748562007-04-02 01:35:34 +0000245 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000246 while (MadeChange) {
247 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000248 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000249 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000250 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000251 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000252
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000253 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000254 if (ModifiedDTOnIteration)
255 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000256 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000257 EverMadeChange |= MadeChange;
258 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000259
260 SunkAddrs.clear();
261
Cameron Zwarich338d3622011-03-11 21:52:04 +0000262 if (!DisableBranchOpts) {
263 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000264 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000265 for (BasicBlock &BB : F) {
266 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
267 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000268 if (!MadeChange) continue;
269
270 for (SmallVectorImpl<BasicBlock*>::iterator
271 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
272 if (pred_begin(*II) == pred_end(*II))
273 WorkList.insert(*II);
274 }
275
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000276 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000277 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000278 while (!WorkList.empty()) {
279 BasicBlock *BB = *WorkList.begin();
280 WorkList.erase(BB);
281 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
282
283 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000284
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000285 for (SmallVectorImpl<BasicBlock*>::iterator
286 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
287 if (pred_begin(*II) == pred_end(*II))
288 WorkList.insert(*II);
289 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000290
Nadav Rotem70409992012-08-14 05:19:07 +0000291 // Merge pairs of basic blocks with unconditional branches, connected by
292 // a single edge.
293 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000294 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000295
Cameron Zwarich338d3622011-03-11 21:52:04 +0000296 EverMadeChange |= MadeChange;
297 }
298
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000299 if (!DisableGCOpts) {
300 SmallVector<Instruction *, 2> Statepoints;
301 for (BasicBlock &BB : F)
302 for (Instruction &I : BB)
303 if (isStatepoint(I))
304 Statepoints.push_back(&I);
305 for (auto &I : Statepoints)
306 EverMadeChange |= simplifyOffsetableRelocate(*I);
307 }
308
Chris Lattnerf2836d12007-03-31 04:06:36 +0000309 return EverMadeChange;
310}
311
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000312/// Merge basic blocks which are connected by a single edge, where one of the
313/// basic blocks has a single successor pointing to the other basic block,
314/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000315bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000316 bool Changed = false;
317 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000318 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000319 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000320 // If the destination block has a single pred, then this is a trivial
321 // edge, just collapse it.
322 BasicBlock *SinglePred = BB->getSinglePredecessor();
323
Evan Cheng64a223a2012-09-28 23:58:57 +0000324 // Don't merge if BB's address is taken.
325 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000326
327 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
328 if (Term && !Term->isConditional()) {
329 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000330 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000331 // Remember if SinglePred was the entry block of the function.
332 // If so, we will need to move BB back to the entry position.
333 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000334 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000335
336 if (isEntry && BB != &BB->getParent()->getEntryBlock())
337 BB->moveBefore(&BB->getParent()->getEntryBlock());
338
339 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000340 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000341 }
342 }
343 return Changed;
344}
345
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000346/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
347/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
348/// edges in ways that are non-optimal for isel. Start by eliminating these
349/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000350bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000351 bool MadeChange = false;
352 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000353 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000354 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000355
356 // If this block doesn't end with an uncond branch, ignore it.
357 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
358 if (!BI || !BI->isUnconditional())
359 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000360
Dale Johannesen4026b042009-03-27 01:13:37 +0000361 // If the instruction before the branch (skipping debug info) isn't a phi
362 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000363 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000364 if (BBI != BB->begin()) {
365 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000366 while (isa<DbgInfoIntrinsic>(BBI)) {
367 if (BBI == BB->begin())
368 break;
369 --BBI;
370 }
371 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
372 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000373 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000374
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 // Do not break infinite loops.
376 BasicBlock *DestBB = BI->getSuccessor(0);
377 if (DestBB == BB)
378 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000379
Sanjay Patelfc580a62015-09-21 23:03:16 +0000380 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000381 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000382
Sanjay Patelfc580a62015-09-21 23:03:16 +0000383 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 MadeChange = true;
385 }
386 return MadeChange;
387}
388
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000389/// Return true if we can merge BB into DestBB if there is a single
390/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000391/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000392bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000393 const BasicBlock *DestBB) const {
394 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
395 // the successor. If there are more complex condition (e.g. preheaders),
396 // don't mess around with them.
397 BasicBlock::const_iterator BBI = BB->begin();
398 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000399 for (const User *U : PN->users()) {
400 const Instruction *UI = cast<Instruction>(U);
401 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000402 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000403 // If User is inside DestBB block and it is a PHINode then check
404 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000405 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000406 if (UI->getParent() == DestBB) {
407 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000408 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
409 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
410 if (Insn && Insn->getParent() == BB &&
411 Insn->getParent() != UPN->getIncomingBlock(I))
412 return false;
413 }
414 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000415 }
416 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000417
Chris Lattnerc3748562007-04-02 01:35:34 +0000418 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
419 // and DestBB may have conflicting incoming values for the block. If so, we
420 // can't merge the block.
421 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
422 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000423
Chris Lattnerc3748562007-04-02 01:35:34 +0000424 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000425 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
427 // It is faster to get preds from a PHI than with pred_iterator.
428 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
429 BBPreds.insert(BBPN->getIncomingBlock(i));
430 } else {
431 BBPreds.insert(pred_begin(BB), pred_end(BB));
432 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000433
Chris Lattnerc3748562007-04-02 01:35:34 +0000434 // Walk the preds of DestBB.
435 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
436 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
437 if (BBPreds.count(Pred)) { // Common predecessor?
438 BBI = DestBB->begin();
439 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
440 const Value *V1 = PN->getIncomingValueForBlock(Pred);
441 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442
Chris Lattnerc3748562007-04-02 01:35:34 +0000443 // If V2 is a phi node in BB, look up what the mapped value will be.
444 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
445 if (V2PN->getParent() == BB)
446 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000447
Chris Lattnerc3748562007-04-02 01:35:34 +0000448 // If there is a conflict, bail out.
449 if (V1 != V2) return false;
450 }
451 }
452 }
453
454 return true;
455}
456
457
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000458/// Eliminate a basic block that has only phi's and an unconditional branch in
459/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000460void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000461 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
462 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000463
David Greene74e2d492010-01-05 01:27:11 +0000464 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000465
Chris Lattnerc3748562007-04-02 01:35:34 +0000466 // If the destination block has a single pred, then this is a trivial edge,
467 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000468 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000469 if (SinglePred != DestBB) {
470 // Remember if SinglePred was the entry block of the function. If so, we
471 // will need to move BB back to the entry position.
472 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000473 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000474
Chris Lattner8a172da2008-11-28 19:54:49 +0000475 if (isEntry && BB != &BB->getParent()->getEntryBlock())
476 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000477
David Greene74e2d492010-01-05 01:27:11 +0000478 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000479 return;
480 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000481 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000482
Chris Lattnerc3748562007-04-02 01:35:34 +0000483 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
484 // to handle the new incoming edges it is about to have.
485 PHINode *PN;
486 for (BasicBlock::iterator BBI = DestBB->begin();
487 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
488 // Remove the incoming value for BB, and remember it.
489 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000490
Chris Lattnerc3748562007-04-02 01:35:34 +0000491 // Two options: either the InVal is a phi node defined in BB or it is some
492 // value that dominates BB.
493 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
494 if (InValPhi && InValPhi->getParent() == BB) {
495 // Add all of the input values of the input PHI as inputs of this phi.
496 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
497 PN->addIncoming(InValPhi->getIncomingValue(i),
498 InValPhi->getIncomingBlock(i));
499 } else {
500 // Otherwise, add one instance of the dominating value for each edge that
501 // we will be adding.
502 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
503 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
504 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
505 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000506 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
507 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000508 }
509 }
510 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000511
Chris Lattnerc3748562007-04-02 01:35:34 +0000512 // The PHIs are now updated, change everything that refers to BB to use
513 // DestBB and remove BB.
514 BB->replaceAllUsesWith(DestBB);
515 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000516 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000517
David Greene74e2d492010-01-05 01:27:11 +0000518 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000519}
520
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000521// Computes a map of base pointer relocation instructions to corresponding
522// derived pointer relocation instructions given a vector of all relocate calls
523static void computeBaseDerivedRelocateMap(
524 const SmallVectorImpl<User *> &AllRelocateCalls,
525 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
526 RelocateInstMap) {
527 // Collect information in two maps: one primarily for locating the base object
528 // while filling the second map; the second map is the final structure holding
529 // a mapping between Base and corresponding Derived relocate calls
530 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
531 for (auto &U : AllRelocateCalls) {
532 GCRelocateOperands ThisRelocate(U);
533 IntrinsicInst *I = cast<IntrinsicInst>(U);
Sanjoy Das499d7032015-05-06 02:36:26 +0000534 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
535 ThisRelocate.getDerivedPtrIndex());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000536 RelocateIdxMap.insert(std::make_pair(K, I));
537 }
538 for (auto &Item : RelocateIdxMap) {
539 std::pair<unsigned, unsigned> Key = Item.first;
540 if (Key.first == Key.second)
541 // Base relocation: nothing to insert
542 continue;
543
544 IntrinsicInst *I = Item.second;
545 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000546
547 // We're iterating over RelocateIdxMap so we cannot modify it.
548 auto MaybeBase = RelocateIdxMap.find(BaseKey);
549 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000550 // TODO: We might want to insert a new base object relocate and gep off
551 // that, if there are enough derived object relocates.
552 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000553
554 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000555 }
556}
557
558// Accepts a GEP and extracts the operands into a vector provided they're all
559// small integer constants
560static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
561 SmallVectorImpl<Value *> &OffsetV) {
562 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
563 // Only accept small constant integer operands
564 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
565 if (!Op || Op->getZExtValue() > 20)
566 return false;
567 }
568
569 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
570 OffsetV.push_back(GEP->getOperand(i));
571 return true;
572}
573
574// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
575// replace, computes a replacement, and affects it.
576static bool
577simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
578 const SmallVectorImpl<IntrinsicInst *> &Targets) {
579 bool MadeChange = false;
580 for (auto &ToReplace : Targets) {
581 GCRelocateOperands MasterRelocate(RelocatedBase);
582 GCRelocateOperands ThisRelocate(ToReplace);
583
Sanjoy Das499d7032015-05-06 02:36:26 +0000584 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000585 "Not relocating a derived object of the original base object");
Sanjoy Das499d7032015-05-06 02:36:26 +0000586 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000587 // A duplicate relocate call. TODO: coalesce duplicates.
588 continue;
589 }
590
Sanjoy Das499d7032015-05-06 02:36:26 +0000591 Value *Base = ThisRelocate.getBasePtr();
592 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000593 if (!Derived || Derived->getPointerOperand() != Base)
594 continue;
595
596 SmallVector<Value *, 2> OffsetV;
597 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
598 continue;
599
600 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000601 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
602
603 // Insert after RelocatedBase
604 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000605 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000606
607 // If gc_relocate does not match the actual type, cast it to the right type.
608 // In theory, there must be a bitcast after gc_relocate if the type does not
609 // match, and we should reuse it to get the derived pointer. But it could be
610 // cases like this:
611 // bb1:
612 // ...
613 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
614 // br label %merge
615 //
616 // bb2:
617 // ...
618 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
619 // br label %merge
620 //
621 // merge:
622 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
623 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
624 //
625 // In this case, we can not find the bitcast any more. So we insert a new bitcast
626 // no matter there is already one or not. In this way, we can handle all cases, and
627 // the extra bitcast should be optimized away in later passes.
628 Instruction *ActualRelocatedBase = RelocatedBase;
629 if (RelocatedBase->getType() != Base->getType()) {
630 ActualRelocatedBase =
631 cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000632 }
David Blaikie68d535c2015-03-24 22:38:16 +0000633 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000634 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000635 Instruction *ReplacementInst = cast<Instruction>(Replacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000636 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000637 // If the newly generated derived pointer's type does not match the original derived
638 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
639 Instruction *ActualReplacement = ReplacementInst;
640 if (ReplacementInst->getType() != ToReplace->getType()) {
641 ActualReplacement =
642 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000643 }
644 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000645 ToReplace->eraseFromParent();
646
647 MadeChange = true;
648 }
649 return MadeChange;
650}
651
652// Turns this:
653//
654// %base = ...
655// %ptr = gep %base + 15
656// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
657// %base' = relocate(%tok, i32 4, i32 4)
658// %ptr' = relocate(%tok, i32 4, i32 5)
659// %val = load %ptr'
660//
661// into this:
662//
663// %base = ...
664// %ptr = gep %base + 15
665// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
666// %base' = gc.relocate(%tok, i32 4, i32 4)
667// %ptr' = gep %base' + 15
668// %val = load %ptr'
669bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
670 bool MadeChange = false;
671 SmallVector<User *, 2> AllRelocateCalls;
672
673 for (auto *U : I.users())
674 if (isGCRelocate(dyn_cast<Instruction>(U)))
675 // Collect all the relocate calls associated with a statepoint
676 AllRelocateCalls.push_back(U);
677
678 // We need atleast one base pointer relocation + one derived pointer
679 // relocation to mangle
680 if (AllRelocateCalls.size() < 2)
681 return false;
682
683 // RelocateInstMap is a mapping from the base relocate instruction to the
684 // corresponding derived relocate instructions
685 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
686 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
687 if (RelocateInstMap.empty())
688 return false;
689
690 for (auto &Item : RelocateInstMap)
691 // Item.first is the RelocatedBase to offset against
692 // Item.second is the vector of Targets to replace
693 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
694 return MadeChange;
695}
696
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000697/// SinkCast - Sink the specified cast instruction into its user blocks
698static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000699 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000700
Chris Lattnerf2836d12007-03-31 04:06:36 +0000701 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000702 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000703
Chris Lattnerf2836d12007-03-31 04:06:36 +0000704 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000705 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000706 UI != E; ) {
707 Use &TheUse = UI.getUse();
708 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000709
Chris Lattnerf2836d12007-03-31 04:06:36 +0000710 // Figure out which BB this cast is used in. For PHI's this is the
711 // appropriate predecessor block.
712 BasicBlock *UserBB = User->getParent();
713 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000714 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000715 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000716
Chris Lattnerf2836d12007-03-31 04:06:36 +0000717 // Preincrement use iterator so we don't invalidate it.
718 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000719
Chris Lattnerf2836d12007-03-31 04:06:36 +0000720 // If this user is in the same block as the cast, don't change the cast.
721 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000722
Chris Lattnerf2836d12007-03-31 04:06:36 +0000723 // If we have already inserted a cast into this block, use it.
724 CastInst *&InsertedCast = InsertedCasts[UserBB];
725
726 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000727 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000728 assert(InsertPt != UserBB->end());
729 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
730 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000731 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000732
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000733 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000734 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000735 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000736 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000737 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000738
Chris Lattnerf2836d12007-03-31 04:06:36 +0000739 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000740 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000741 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000742 MadeChange = true;
743 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000744
Chris Lattnerf2836d12007-03-31 04:06:36 +0000745 return MadeChange;
746}
747
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000748/// If the specified cast instruction is a noop copy (e.g. it's casting from
749/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
750/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000751///
752/// Return true if any changes are made.
753///
Mehdi Amini44ede332015-07-09 02:09:04 +0000754static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
755 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000756 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000757 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
758 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000759
760 // This is an fp<->int conversion?
761 if (SrcVT.isInteger() != DstVT.isInteger())
762 return false;
763
764 // If this is an extension, it will be a zero or sign extension, which
765 // isn't a noop.
766 if (SrcVT.bitsLT(DstVT)) return false;
767
768 // If these values will be promoted, find out what they will be promoted
769 // to. This helps us consider truncates on PPC as noop copies when they
770 // are.
771 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
772 TargetLowering::TypePromoteInteger)
773 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
774 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
775 TargetLowering::TypePromoteInteger)
776 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
777
778 // If, after promotion, these are the same types, this is a noop copy.
779 if (SrcVT != DstVT)
780 return false;
781
782 return SinkCast(CI);
783}
784
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000785/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
786/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000787///
788/// Return true if any changes were made.
789static bool CombineUAddWithOverflow(CmpInst *CI) {
790 Value *A, *B;
791 Instruction *AddI;
792 if (!match(CI,
793 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
794 return false;
795
796 Type *Ty = AddI->getType();
797 if (!isa<IntegerType>(Ty))
798 return false;
799
800 // We don't want to move around uses of condition values this late, so we we
801 // check if it is legal to create the call to the intrinsic in the basic
802 // block containing the icmp:
803
804 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
805 return false;
806
807#ifndef NDEBUG
808 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
809 // for now:
810 if (AddI->hasOneUse())
811 assert(*AddI->user_begin() == CI && "expected!");
812#endif
813
814 Module *M = CI->getParent()->getParent()->getParent();
815 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
816
817 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
818
819 auto *UAddWithOverflow =
820 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
821 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
822 auto *Overflow =
823 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
824
825 CI->replaceAllUsesWith(Overflow);
826 AddI->replaceAllUsesWith(UAdd);
827 CI->eraseFromParent();
828 AddI->eraseFromParent();
829 return true;
830}
831
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000832/// Sink the given CmpInst into user blocks to reduce the number of virtual
833/// registers that must be created and coalesced. This is a clear win except on
834/// targets with multiple condition code registers (PowerPC), where it might
835/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000836///
837/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000838static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000839 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000840
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000841 /// Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000842 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000843
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000844 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000845 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000846 UI != E; ) {
847 Use &TheUse = UI.getUse();
848 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000849
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000850 // Preincrement use iterator so we don't invalidate it.
851 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000852
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000853 // Don't bother for PHI nodes.
854 if (isa<PHINode>(User))
855 continue;
856
857 // Figure out which BB this cmp is used in.
858 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000859
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000860 // If this user is in the same block as the cmp, don't change the cmp.
861 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000862
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000863 // If we have already inserted a cmp into this block, use it.
864 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
865
866 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000867 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000868 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000869 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000870 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
871 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000872 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000873
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000874 // Replace a use of the cmp with a use of the new cmp.
875 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000876 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000877 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000878 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000879
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000880 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000881 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000882 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000883 MadeChange = true;
884 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000885
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000886 return MadeChange;
887}
888
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000889static bool OptimizeCmpExpression(CmpInst *CI) {
890 if (SinkCmpExpression(CI))
891 return true;
892
893 if (CombineUAddWithOverflow(CI))
894 return true;
895
896 return false;
897}
898
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000899/// Check if the candidates could be combined with a shift instruction, which
900/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000901/// 1. Truncate instruction
902/// 2. And instruction and the imm is a mask of the low bits:
903/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000904static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000905 if (!isa<TruncInst>(User)) {
906 if (User->getOpcode() != Instruction::And ||
907 !isa<ConstantInt>(User->getOperand(1)))
908 return false;
909
Quentin Colombetd4f44692014-04-22 01:20:34 +0000910 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000911
Quentin Colombetd4f44692014-04-22 01:20:34 +0000912 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000913 return false;
914 }
915 return true;
916}
917
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000918/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000919static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000920SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
921 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000922 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000923 BasicBlock *UserBB = User->getParent();
924 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
925 TruncInst *TruncI = dyn_cast<TruncInst>(User);
926 bool MadeChange = false;
927
928 for (Value::user_iterator TruncUI = TruncI->user_begin(),
929 TruncE = TruncI->user_end();
930 TruncUI != TruncE;) {
931
932 Use &TruncTheUse = TruncUI.getUse();
933 Instruction *TruncUser = cast<Instruction>(*TruncUI);
934 // Preincrement use iterator so we don't invalidate it.
935
936 ++TruncUI;
937
938 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
939 if (!ISDOpcode)
940 continue;
941
Tim Northovere2239ff2014-07-29 10:20:22 +0000942 // If the use is actually a legal node, there will not be an
943 // implicit truncate.
944 // FIXME: always querying the result type is just an
945 // approximation; some nodes' legality is determined by the
946 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000947 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000948 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000949 continue;
950
951 // Don't bother for PHI nodes.
952 if (isa<PHINode>(TruncUser))
953 continue;
954
955 BasicBlock *TruncUserBB = TruncUser->getParent();
956
957 if (UserBB == TruncUserBB)
958 continue;
959
960 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
961 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
962
963 if (!InsertedShift && !InsertedTrunc) {
964 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000965 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000966 // Sink the shift
967 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000968 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
969 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000970 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000971 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
972 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000973
974 // Sink the trunc
975 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
976 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000977 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000978
979 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000980 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000981
982 MadeChange = true;
983
984 TruncTheUse = InsertedTrunc;
985 }
986 }
987 return MadeChange;
988}
989
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000990/// Sink the shift *right* instruction into user blocks if the uses could
991/// potentially be combined with this shift instruction and generate BitExtract
992/// instruction. It will only be applied if the architecture supports BitExtract
993/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +0000994/// BB1:
995/// %x.extract.shift = lshr i64 %arg1, 32
996/// BB2:
997/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
998/// ==>
999///
1000/// BB2:
1001/// %x.extract.shift.1 = lshr i64 %arg1, 32
1002/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1003///
1004/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1005/// instruction.
1006/// Return true if any changes are made.
1007static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001008 const TargetLowering &TLI,
1009 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001010 BasicBlock *DefBB = ShiftI->getParent();
1011
1012 /// Only insert instructions in each block once.
1013 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1014
Mehdi Amini44ede332015-07-09 02:09:04 +00001015 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001016
1017 bool MadeChange = false;
1018 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1019 UI != E;) {
1020 Use &TheUse = UI.getUse();
1021 Instruction *User = cast<Instruction>(*UI);
1022 // Preincrement use iterator so we don't invalidate it.
1023 ++UI;
1024
1025 // Don't bother for PHI nodes.
1026 if (isa<PHINode>(User))
1027 continue;
1028
1029 if (!isExtractBitsCandidateUse(User))
1030 continue;
1031
1032 BasicBlock *UserBB = User->getParent();
1033
1034 if (UserBB == DefBB) {
1035 // If the shift and truncate instruction are in the same BB. The use of
1036 // the truncate(TruncUse) may still introduce another truncate if not
1037 // legal. In this case, we would like to sink both shift and truncate
1038 // instruction to the BB of TruncUse.
1039 // for example:
1040 // BB1:
1041 // i64 shift.result = lshr i64 opnd, imm
1042 // trunc.result = trunc shift.result to i16
1043 //
1044 // BB2:
1045 // ----> We will have an implicit truncate here if the architecture does
1046 // not have i16 compare.
1047 // cmp i16 trunc.result, opnd2
1048 //
1049 if (isa<TruncInst>(User) && shiftIsLegal
1050 // If the type of the truncate is legal, no trucate will be
1051 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001052 &&
1053 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001054 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001055 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001056
1057 continue;
1058 }
1059 // If we have already inserted a shift into this block, use it.
1060 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1061
1062 if (!InsertedShift) {
1063 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001064 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001065
1066 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001067 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1068 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001069 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001070 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1071 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001072
1073 MadeChange = true;
1074 }
1075
1076 // Replace a use of the shift with a use of the new shift.
1077 TheUse = InsertedShift;
1078 }
1079
1080 // If we removed all uses, nuke the shift.
1081 if (ShiftI->use_empty())
1082 ShiftI->eraseFromParent();
1083
1084 return MadeChange;
1085}
1086
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001087// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001088// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1089// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001090// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001091// the appropriate mask bit is set
1092//
1093// %1 = bitcast i8* %addr to i32*
1094// %2 = extractelement <16 x i1> %mask, i32 0
1095// %3 = icmp eq i1 %2, true
1096// br i1 %3, label %cond.load, label %else
1097//
1098//cond.load: ; preds = %0
1099// %4 = getelementptr i32* %1, i32 0
1100// %5 = load i32* %4
1101// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1102// br label %else
1103//
1104//else: ; preds = %0, %cond.load
1105// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1106// %7 = extractelement <16 x i1> %mask, i32 1
1107// %8 = icmp eq i1 %7, true
1108// br i1 %8, label %cond.load1, label %else2
1109//
1110//cond.load1: ; preds = %else
1111// %9 = getelementptr i32* %1, i32 1
1112// %10 = load i32* %9
1113// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1114// br label %else2
1115//
1116//else2: ; preds = %else, %cond.load1
1117// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1118// %12 = extractelement <16 x i1> %mask, i32 2
1119// %13 = icmp eq i1 %12, true
1120// br i1 %13, label %cond.load4, label %else5
1121//
1122static void ScalarizeMaskedLoad(CallInst *CI) {
1123 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001124 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001125 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001126 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001127
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001128 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1129 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001130 assert(VecType && "Unexpected return type of masked load intrinsic");
1131
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001132 Type *EltTy = CI->getType()->getVectorElementType();
1133
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001134 IRBuilder<> Builder(CI->getContext());
1135 Instruction *InsertPt = CI;
1136 BasicBlock *IfBlock = CI->getParent();
1137 BasicBlock *CondBlock = nullptr;
1138 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001139
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001140 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001141 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1142
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001143 // Short-cut if the mask is all-true.
1144 bool IsAllOnesMask = isa<Constant>(Mask) &&
1145 cast<Constant>(Mask)->isAllOnesValue();
1146
1147 if (IsAllOnesMask) {
1148 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1149 CI->replaceAllUsesWith(NewI);
1150 CI->eraseFromParent();
1151 return;
1152 }
1153
1154 // Adjust alignment for the scalar instruction.
1155 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001156 // Bitcast %addr fron i8* to EltTy*
1157 Type *NewPtrType =
1158 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1159 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001160 unsigned VectorWidth = VecType->getNumElements();
1161
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001162 Value *UndefVal = UndefValue::get(VecType);
1163
1164 // The result vector
1165 Value *VResult = UndefVal;
1166
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001167 if (isa<ConstantVector>(Mask)) {
1168 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1169 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1170 continue;
1171 Value *Gep =
1172 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1173 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1174 VResult = Builder.CreateInsertElement(VResult, Load,
1175 Builder.getInt32(Idx));
1176 }
1177 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1178 CI->replaceAllUsesWith(NewI);
1179 CI->eraseFromParent();
1180 return;
1181 }
1182
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001183 PHINode *Phi = nullptr;
1184 Value *PrevPhi = UndefVal;
1185
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001186 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1187
1188 // Fill the "else" block, created in the previous iteration
1189 //
1190 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1191 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1192 // %to_load = icmp eq i1 %mask_1, true
1193 // br i1 %to_load, label %cond.load, label %else
1194 //
1195 if (Idx > 0) {
1196 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1197 Phi->addIncoming(VResult, CondBlock);
1198 Phi->addIncoming(PrevPhi, PrevIfBlock);
1199 PrevPhi = Phi;
1200 VResult = Phi;
1201 }
1202
1203 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1204 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1205 ConstantInt::get(Predicate->getType(), 1));
1206
1207 // Create "cond" block
1208 //
1209 // %EltAddr = getelementptr i32* %1, i32 0
1210 // %Elt = load i32* %EltAddr
1211 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1212 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001213 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001214 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001215
1216 Value *Gep =
1217 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001218 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001219 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1220
1221 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001222 BasicBlock *NewIfBlock =
1223 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001224 Builder.SetInsertPoint(InsertPt);
1225 Instruction *OldBr = IfBlock->getTerminator();
1226 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1227 OldBr->eraseFromParent();
1228 PrevIfBlock = IfBlock;
1229 IfBlock = NewIfBlock;
1230 }
1231
1232 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1233 Phi->addIncoming(VResult, CondBlock);
1234 Phi->addIncoming(PrevPhi, PrevIfBlock);
1235 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1236 CI->replaceAllUsesWith(NewI);
1237 CI->eraseFromParent();
1238}
1239
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001240// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001241// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1242// <16 x i1> %mask)
1243// to a chain of basic blocks, that stores element one-by-one if
1244// the appropriate mask bit is set
1245//
1246// %1 = bitcast i8* %addr to i32*
1247// %2 = extractelement <16 x i1> %mask, i32 0
1248// %3 = icmp eq i1 %2, true
1249// br i1 %3, label %cond.store, label %else
1250//
1251// cond.store: ; preds = %0
1252// %4 = extractelement <16 x i32> %val, i32 0
1253// %5 = getelementptr i32* %1, i32 0
1254// store i32 %4, i32* %5
1255// br label %else
1256//
1257// else: ; preds = %0, %cond.store
1258// %6 = extractelement <16 x i1> %mask, i32 1
1259// %7 = icmp eq i1 %6, true
1260// br i1 %7, label %cond.store1, label %else2
1261//
1262// cond.store1: ; preds = %else
1263// %8 = extractelement <16 x i32> %val, i32 1
1264// %9 = getelementptr i32* %1, i32 1
1265// store i32 %8, i32* %9
1266// br label %else2
1267// . . .
1268static void ScalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001269 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001270 Value *Ptr = CI->getArgOperand(1);
1271 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001272 Value *Mask = CI->getArgOperand(3);
1273
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001274 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001275 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001276 assert(VecType && "Unexpected data type in masked store intrinsic");
1277
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001278 Type *EltTy = VecType->getElementType();
1279
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001280 IRBuilder<> Builder(CI->getContext());
1281 Instruction *InsertPt = CI;
1282 BasicBlock *IfBlock = CI->getParent();
1283 Builder.SetInsertPoint(InsertPt);
1284 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1285
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001286 // Short-cut if the mask is all-true.
1287 bool IsAllOnesMask = isa<Constant>(Mask) &&
1288 cast<Constant>(Mask)->isAllOnesValue();
1289
1290 if (IsAllOnesMask) {
1291 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1292 CI->eraseFromParent();
1293 return;
1294 }
1295
1296 // Adjust alignment for the scalar instruction.
1297 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001298 // Bitcast %addr fron i8* to EltTy*
1299 Type *NewPtrType =
1300 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1301 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001302 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001303
1304 if (isa<ConstantVector>(Mask)) {
1305 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1306 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1307 continue;
1308 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1309 Value *Gep =
1310 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1311 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1312 }
1313 CI->eraseFromParent();
1314 return;
1315 }
1316
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001317 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1318
1319 // Fill the "else" block, created in the previous iteration
1320 //
1321 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1322 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001323 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001324 //
1325 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1326 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1327 ConstantInt::get(Predicate->getType(), 1));
1328
1329 // Create "cond" block
1330 //
1331 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1332 // %EltAddr = getelementptr i32* %1, i32 0
1333 // %store i32 %OneElt, i32* %EltAddr
1334 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001335 BasicBlock *CondBlock =
1336 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001337 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001338
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001339 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001340 Value *Gep =
1341 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001342 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001343
1344 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001345 BasicBlock *NewIfBlock =
1346 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001347 Builder.SetInsertPoint(InsertPt);
1348 Instruction *OldBr = IfBlock->getTerminator();
1349 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1350 OldBr->eraseFromParent();
1351 IfBlock = NewIfBlock;
1352 }
1353 CI->eraseFromParent();
1354}
1355
Sanjay Patelfc580a62015-09-21 23:03:16 +00001356bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001357 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001358
Chris Lattner7a277142011-01-15 07:14:54 +00001359 // Lower inline assembly if we can.
1360 // If we found an inline asm expession, and if the target knows how to
1361 // lower it to normal LLVM code, do so now.
1362 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1363 if (TLI->ExpandInlineAsm(CI)) {
1364 // Avoid invalidating the iterator.
1365 CurInstIterator = BB->begin();
1366 // Avoid processing instructions out of order, which could cause
1367 // reuse before a value is defined.
1368 SunkAddrs.clear();
1369 return true;
1370 }
1371 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001372 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001373 return true;
1374 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001375
John Brawn0dbcd652015-03-18 12:01:59 +00001376 // Align the pointer arguments to this call if the target thinks it's a good
1377 // idea
1378 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001379 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001380 for (auto &Arg : CI->arg_operands()) {
1381 // We want to align both objects whose address is used directly and
1382 // objects whose address is used in casts and GEPs, though it only makes
1383 // sense for GEPs if the offset is a multiple of the desired alignment and
1384 // if size - offset meets the size threshold.
1385 if (!Arg->getType()->isPointerTy())
1386 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001387 APInt Offset(DL->getPointerSizeInBits(
1388 cast<PointerType>(Arg->getType())->getAddressSpace()),
1389 0);
1390 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001391 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001392 if ((Offset2 & (PrefAlign-1)) != 0)
1393 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001394 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001395 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1396 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001397 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001398 // Global variables can only be aligned if they are defined in this
1399 // object (i.e. they are uniquely initialized in this object), and
1400 // over-aligning global variables that have an explicit section is
1401 // forbidden.
1402 GlobalVariable *GV;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001403 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1404 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1405 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1406 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001407 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001408 }
1409 // If this is a memcpy (or similar) then we may be able to improve the
1410 // alignment
1411 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001412 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001413 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001414 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
John Brawn0dbcd652015-03-18 12:01:59 +00001415 if (Align > MI->getAlignment())
1416 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1417 }
1418 }
1419
Eric Christopher4b7948e2010-03-11 02:41:03 +00001420 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001421 if (II) {
1422 switch (II->getIntrinsicID()) {
1423 default: break;
1424 case Intrinsic::objectsize: {
1425 // Lower all uses of llvm.objectsize.*
1426 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1427 Type *ReturnTy = CI->getType();
1428 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001429
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001430 // Substituting this can cause recursive simplifications, which can
1431 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1432 // happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001433 WeakVH IterHandle(&*CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001434
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001435 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001436 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001437
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001438 // If the iterator instruction was recursively deleted, start over at the
1439 // start of the block.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001440 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001441 CurInstIterator = BB->begin();
1442 SunkAddrs.clear();
1443 }
1444 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001445 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001446 case Intrinsic::masked_load: {
1447 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001448 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001449 ScalarizeMaskedLoad(CI);
1450 ModifiedDT = true;
1451 return true;
1452 }
1453 return false;
1454 }
1455 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001456 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001457 ScalarizeMaskedStore(CI);
1458 ModifiedDT = true;
1459 return true;
1460 }
1461 return false;
1462 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001463 case Intrinsic::aarch64_stlxr:
1464 case Intrinsic::aarch64_stxr: {
1465 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1466 if (!ExtVal || !ExtVal->hasOneUse() ||
1467 ExtVal->getParent() == CI->getParent())
1468 return false;
1469 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1470 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001471 // Mark this instruction as "inserted by CGP", so that other
1472 // optimizations don't touch it.
1473 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001474 return true;
1475 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001476 case Intrinsic::invariant_group_barrier:
1477 II->replaceAllUsesWith(II->getArgOperand(0));
1478 II->eraseFromParent();
1479 return true;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001480 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001481
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001482 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001483 // Unknown address space.
1484 // TODO: Target hook to pick which address space the intrinsic cares
1485 // about?
1486 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001487 SmallVector<Value*, 2> PtrOps;
1488 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001489 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001490 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001491 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001492 return true;
1493 }
Pete Cooper615fd892012-03-13 20:59:56 +00001494 }
1495
Eric Christopher4b7948e2010-03-11 02:41:03 +00001496 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001497 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001498
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001499 // Lower all default uses of _chk calls. This is very similar
1500 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001501 // to fortified library functions (e.g. __memcpy_chk) that have the default
1502 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001503 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001504 if (Value *V = Simplifier.optimizeCall(CI)) {
1505 CI->replaceAllUsesWith(V);
1506 CI->eraseFromParent();
1507 return true;
1508 }
1509 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001510}
Chris Lattner1b93be52011-01-15 07:25:29 +00001511
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001512/// Look for opportunities to duplicate return instructions to the predecessor
1513/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001514/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001515/// bb0:
1516/// %tmp0 = tail call i32 @f0()
1517/// br label %return
1518/// bb1:
1519/// %tmp1 = tail call i32 @f1()
1520/// br label %return
1521/// bb2:
1522/// %tmp2 = tail call i32 @f2()
1523/// br label %return
1524/// return:
1525/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1526/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001527/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001528///
1529/// =>
1530///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001531/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001532/// bb0:
1533/// %tmp0 = tail call i32 @f0()
1534/// ret i32 %tmp0
1535/// bb1:
1536/// %tmp1 = tail call i32 @f1()
1537/// ret i32 %tmp1
1538/// bb2:
1539/// %tmp2 = tail call i32 @f2()
1540/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001541/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001542bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001543 if (!TLI)
1544 return false;
1545
Benjamin Kramer455fa352012-11-23 19:17:06 +00001546 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1547 if (!RI)
1548 return false;
1549
Craig Topperc0196b12014-04-14 00:51:57 +00001550 PHINode *PN = nullptr;
1551 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001552 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001553 if (V) {
1554 BCI = dyn_cast<BitCastInst>(V);
1555 if (BCI)
1556 V = BCI->getOperand(0);
1557
1558 PN = dyn_cast<PHINode>(V);
1559 if (!PN)
1560 return false;
1561 }
Evan Cheng0663f232011-03-21 01:19:09 +00001562
Cameron Zwarich4649f172011-03-24 04:52:10 +00001563 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001564 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001565
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001566 // It's not safe to eliminate the sign / zero extension of the return value.
1567 // See llvm::isInTailCallPosition().
1568 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001569 AttributeSet CallerAttrs = F->getAttributes();
1570 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1571 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001572 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001573
Cameron Zwarich4649f172011-03-24 04:52:10 +00001574 // Make sure there are no instructions between the PHI and return, or that the
1575 // return is the first instruction in the block.
1576 if (PN) {
1577 BasicBlock::iterator BI = BB->begin();
1578 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001579 if (&*BI == BCI)
1580 // Also skip over the bitcast.
1581 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001582 if (&*BI != RI)
1583 return false;
1584 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001585 BasicBlock::iterator BI = BB->begin();
1586 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1587 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001588 return false;
1589 }
Evan Cheng0663f232011-03-21 01:19:09 +00001590
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001591 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1592 /// call.
1593 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001594 if (PN) {
1595 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1596 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1597 // Make sure the phi value is indeed produced by the tail call.
1598 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1599 TLI->mayBeEmittedAsTailCall(CI))
1600 TailCalls.push_back(CI);
1601 }
1602 } else {
1603 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001604 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001605 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001606 continue;
1607
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001608 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001609 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1610 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001611 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1612 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001613 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001614
Cameron Zwarich4649f172011-03-24 04:52:10 +00001615 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001616 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001617 TailCalls.push_back(CI);
1618 }
Evan Cheng0663f232011-03-21 01:19:09 +00001619 }
1620
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001621 bool Changed = false;
1622 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1623 CallInst *CI = TailCalls[i];
1624 CallSite CS(CI);
1625
1626 // Conservatively require the attributes of the call to match those of the
1627 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001628 AttributeSet CalleeAttrs = CS.getAttributes();
1629 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001630 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001631 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001632 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001633 continue;
1634
1635 // Make sure the call instruction is followed by an unconditional branch to
1636 // the return block.
1637 BasicBlock *CallBB = CI->getParent();
1638 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1639 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1640 continue;
1641
1642 // Duplicate the return into CallBB.
1643 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001644 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001645 ++NumRetsDup;
1646 }
1647
1648 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001649 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001650 BB->eraseFromParent();
1651
1652 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001653}
1654
Chris Lattner728f9022008-11-25 07:09:13 +00001655//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001656// Memory Optimization
1657//===----------------------------------------------------------------------===//
1658
Chandler Carruthc8925912013-01-05 02:09:22 +00001659namespace {
1660
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001661/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001662/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001663struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001664 Value *BaseReg;
1665 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001666 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001667 void print(raw_ostream &OS) const;
1668 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001669
Chandler Carruthc8925912013-01-05 02:09:22 +00001670 bool operator==(const ExtAddrMode& O) const {
1671 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1672 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1673 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1674 }
1675};
1676
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001677#ifndef NDEBUG
1678static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1679 AM.print(OS);
1680 return OS;
1681}
1682#endif
1683
Chandler Carruthc8925912013-01-05 02:09:22 +00001684void ExtAddrMode::print(raw_ostream &OS) const {
1685 bool NeedPlus = false;
1686 OS << "[";
1687 if (BaseGV) {
1688 OS << (NeedPlus ? " + " : "")
1689 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001690 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001691 NeedPlus = true;
1692 }
1693
Richard Trieuc0f91212014-05-30 03:15:17 +00001694 if (BaseOffs) {
1695 OS << (NeedPlus ? " + " : "")
1696 << BaseOffs;
1697 NeedPlus = true;
1698 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001699
1700 if (BaseReg) {
1701 OS << (NeedPlus ? " + " : "")
1702 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001703 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001704 NeedPlus = true;
1705 }
1706 if (Scale) {
1707 OS << (NeedPlus ? " + " : "")
1708 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001709 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001710 }
1711
1712 OS << ']';
1713}
1714
1715#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1716void ExtAddrMode::dump() const {
1717 print(dbgs());
1718 dbgs() << '\n';
1719}
1720#endif
1721
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001722/// \brief This class provides transaction based operation on the IR.
1723/// Every change made through this class is recorded in the internal state and
1724/// can be undone (rollback) until commit is called.
1725class TypePromotionTransaction {
1726
1727 /// \brief This represents the common interface of the individual transaction.
1728 /// Each class implements the logic for doing one specific modification on
1729 /// the IR via the TypePromotionTransaction.
1730 class TypePromotionAction {
1731 protected:
1732 /// The Instruction modified.
1733 Instruction *Inst;
1734
1735 public:
1736 /// \brief Constructor of the action.
1737 /// The constructor performs the related action on the IR.
1738 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1739
1740 virtual ~TypePromotionAction() {}
1741
1742 /// \brief Undo the modification done by this action.
1743 /// When this method is called, the IR must be in the same state as it was
1744 /// before this action was applied.
1745 /// \pre Undoing the action works if and only if the IR is in the exact same
1746 /// state as it was directly after this action was applied.
1747 virtual void undo() = 0;
1748
1749 /// \brief Advocate every change made by this action.
1750 /// When the results on the IR of the action are to be kept, it is important
1751 /// to call this function, otherwise hidden information may be kept forever.
1752 virtual void commit() {
1753 // Nothing to be done, this action is not doing anything.
1754 }
1755 };
1756
1757 /// \brief Utility to remember the position of an instruction.
1758 class InsertionHandler {
1759 /// Position of an instruction.
1760 /// Either an instruction:
1761 /// - Is the first in a basic block: BB is used.
1762 /// - Has a previous instructon: PrevInst is used.
1763 union {
1764 Instruction *PrevInst;
1765 BasicBlock *BB;
1766 } Point;
1767 /// Remember whether or not the instruction had a previous instruction.
1768 bool HasPrevInstruction;
1769
1770 public:
1771 /// \brief Record the position of \p Inst.
1772 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001773 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001774 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1775 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001776 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001777 else
1778 Point.BB = Inst->getParent();
1779 }
1780
1781 /// \brief Insert \p Inst at the recorded position.
1782 void insert(Instruction *Inst) {
1783 if (HasPrevInstruction) {
1784 if (Inst->getParent())
1785 Inst->removeFromParent();
1786 Inst->insertAfter(Point.PrevInst);
1787 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001788 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001789 if (Inst->getParent())
1790 Inst->moveBefore(Position);
1791 else
1792 Inst->insertBefore(Position);
1793 }
1794 }
1795 };
1796
1797 /// \brief Move an instruction before another.
1798 class InstructionMoveBefore : public TypePromotionAction {
1799 /// Original position of the instruction.
1800 InsertionHandler Position;
1801
1802 public:
1803 /// \brief Move \p Inst before \p Before.
1804 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1805 : TypePromotionAction(Inst), Position(Inst) {
1806 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1807 Inst->moveBefore(Before);
1808 }
1809
1810 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001811 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001812 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1813 Position.insert(Inst);
1814 }
1815 };
1816
1817 /// \brief Set the operand of an instruction with a new value.
1818 class OperandSetter : public TypePromotionAction {
1819 /// Original operand of the instruction.
1820 Value *Origin;
1821 /// Index of the modified instruction.
1822 unsigned Idx;
1823
1824 public:
1825 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1826 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1827 : TypePromotionAction(Inst), Idx(Idx) {
1828 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1829 << "for:" << *Inst << "\n"
1830 << "with:" << *NewVal << "\n");
1831 Origin = Inst->getOperand(Idx);
1832 Inst->setOperand(Idx, NewVal);
1833 }
1834
1835 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001836 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001837 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1838 << "for: " << *Inst << "\n"
1839 << "with: " << *Origin << "\n");
1840 Inst->setOperand(Idx, Origin);
1841 }
1842 };
1843
1844 /// \brief Hide the operands of an instruction.
1845 /// Do as if this instruction was not using any of its operands.
1846 class OperandsHider : public TypePromotionAction {
1847 /// The list of original operands.
1848 SmallVector<Value *, 4> OriginalValues;
1849
1850 public:
1851 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1852 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1853 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1854 unsigned NumOpnds = Inst->getNumOperands();
1855 OriginalValues.reserve(NumOpnds);
1856 for (unsigned It = 0; It < NumOpnds; ++It) {
1857 // Save the current operand.
1858 Value *Val = Inst->getOperand(It);
1859 OriginalValues.push_back(Val);
1860 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00001861 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001862 // that we are not willing to pay.
1863 Inst->setOperand(It, UndefValue::get(Val->getType()));
1864 }
1865 }
1866
1867 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001868 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001869 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1870 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1871 Inst->setOperand(It, OriginalValues[It]);
1872 }
1873 };
1874
1875 /// \brief Build a truncate instruction.
1876 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001877 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001878 public:
1879 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1880 /// result.
1881 /// trunc Opnd to Ty.
1882 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1883 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001884 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1885 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001886 }
1887
Quentin Colombetac55b152014-09-16 22:36:07 +00001888 /// \brief Get the built value.
1889 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001890
1891 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001892 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001893 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1894 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1895 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001896 }
1897 };
1898
1899 /// \brief Build a sign extension instruction.
1900 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001901 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001902 public:
1903 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1904 /// result.
1905 /// sext Opnd to Ty.
1906 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001907 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001908 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001909 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1910 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001911 }
1912
Quentin Colombetac55b152014-09-16 22:36:07 +00001913 /// \brief Get the built value.
1914 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001915
1916 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001917 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001918 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1919 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1920 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001921 }
1922 };
1923
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001924 /// \brief Build a zero extension instruction.
1925 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001926 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001927 public:
1928 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1929 /// result.
1930 /// zext Opnd to Ty.
1931 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001932 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001933 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001934 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1935 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001936 }
1937
Quentin Colombetac55b152014-09-16 22:36:07 +00001938 /// \brief Get the built value.
1939 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001940
1941 /// \brief Remove the built instruction.
1942 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001943 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1944 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1945 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001946 }
1947 };
1948
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001949 /// \brief Mutate an instruction to another type.
1950 class TypeMutator : public TypePromotionAction {
1951 /// Record the original type.
1952 Type *OrigTy;
1953
1954 public:
1955 /// \brief Mutate the type of \p Inst into \p NewTy.
1956 TypeMutator(Instruction *Inst, Type *NewTy)
1957 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1958 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1959 << "\n");
1960 Inst->mutateType(NewTy);
1961 }
1962
1963 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001964 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001965 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1966 << "\n");
1967 Inst->mutateType(OrigTy);
1968 }
1969 };
1970
1971 /// \brief Replace the uses of an instruction by another instruction.
1972 class UsesReplacer : public TypePromotionAction {
1973 /// Helper structure to keep track of the replaced uses.
1974 struct InstructionAndIdx {
1975 /// The instruction using the instruction.
1976 Instruction *Inst;
1977 /// The index where this instruction is used for Inst.
1978 unsigned Idx;
1979 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1980 : Inst(Inst), Idx(Idx) {}
1981 };
1982
1983 /// Keep track of the original uses (pair Instruction, Index).
1984 SmallVector<InstructionAndIdx, 4> OriginalUses;
1985 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1986
1987 public:
1988 /// \brief Replace all the use of \p Inst by \p New.
1989 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1990 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1991 << "\n");
1992 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001993 for (Use &U : Inst->uses()) {
1994 Instruction *UserI = cast<Instruction>(U.getUser());
1995 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001996 }
1997 // Now, we can replace the uses.
1998 Inst->replaceAllUsesWith(New);
1999 }
2000
2001 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002002 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002003 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2004 for (use_iterator UseIt = OriginalUses.begin(),
2005 EndIt = OriginalUses.end();
2006 UseIt != EndIt; ++UseIt) {
2007 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2008 }
2009 }
2010 };
2011
2012 /// \brief Remove an instruction from the IR.
2013 class InstructionRemover : public TypePromotionAction {
2014 /// Original position of the instruction.
2015 InsertionHandler Inserter;
2016 /// Helper structure to hide all the link to the instruction. In other
2017 /// words, this helps to do as if the instruction was removed.
2018 OperandsHider Hider;
2019 /// Keep track of the uses replaced, if any.
2020 UsesReplacer *Replacer;
2021
2022 public:
2023 /// \brief Remove all reference of \p Inst and optinally replace all its
2024 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002025 /// \pre If !Inst->use_empty(), then New != nullptr
2026 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002027 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002028 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002029 if (New)
2030 Replacer = new UsesReplacer(Inst, New);
2031 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2032 Inst->removeFromParent();
2033 }
2034
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002035 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002036
2037 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002038 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002039
2040 /// \brief Resurrect the instruction and reassign it to the proper uses if
2041 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002042 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002043 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2044 Inserter.insert(Inst);
2045 if (Replacer)
2046 Replacer->undo();
2047 Hider.undo();
2048 }
2049 };
2050
2051public:
2052 /// Restoration point.
2053 /// The restoration point is a pointer to an action instead of an iterator
2054 /// because the iterator may be invalidated but not the pointer.
2055 typedef const TypePromotionAction *ConstRestorationPt;
2056 /// Advocate every changes made in that transaction.
2057 void commit();
2058 /// Undo all the changes made after the given point.
2059 void rollback(ConstRestorationPt Point);
2060 /// Get the current restoration point.
2061 ConstRestorationPt getRestorationPoint() const;
2062
2063 /// \name API for IR modification with state keeping to support rollback.
2064 /// @{
2065 /// Same as Instruction::setOperand.
2066 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2067 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002068 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002069 /// Same as Value::replaceAllUsesWith.
2070 void replaceAllUsesWith(Instruction *Inst, Value *New);
2071 /// Same as Value::mutateType.
2072 void mutateType(Instruction *Inst, Type *NewTy);
2073 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002074 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002075 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002076 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002077 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002078 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002079 /// Same as Instruction::moveBefore.
2080 void moveBefore(Instruction *Inst, Instruction *Before);
2081 /// @}
2082
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002083private:
2084 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002085 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2086 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002087};
2088
2089void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2090 Value *NewVal) {
2091 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002092 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002093}
2094
2095void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2096 Value *NewVal) {
2097 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002098 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002099}
2100
2101void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2102 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002103 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002104}
2105
2106void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002107 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002108}
2109
Quentin Colombetac55b152014-09-16 22:36:07 +00002110Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2111 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002112 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002113 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002114 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002115 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002116}
2117
Quentin Colombetac55b152014-09-16 22:36:07 +00002118Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2119 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002120 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002121 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002122 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002123 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002124}
2125
Quentin Colombetac55b152014-09-16 22:36:07 +00002126Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2127 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002128 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002129 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002130 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002131 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002132}
2133
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002134void TypePromotionTransaction::moveBefore(Instruction *Inst,
2135 Instruction *Before) {
2136 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002137 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002138}
2139
2140TypePromotionTransaction::ConstRestorationPt
2141TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002142 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002143}
2144
2145void TypePromotionTransaction::commit() {
2146 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002147 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002148 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002149 Actions.clear();
2150}
2151
2152void TypePromotionTransaction::rollback(
2153 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002154 while (!Actions.empty() && Point != Actions.back().get()) {
2155 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002156 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002157 }
2158}
2159
Chandler Carruthc8925912013-01-05 02:09:22 +00002160/// \brief A helper class for matching addressing modes.
2161///
2162/// This encapsulates the logic for matching the target-legal addressing modes.
2163class AddressingModeMatcher {
2164 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002165 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002166 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002167 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002168
2169 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2170 /// the memory instruction that we're computing this address for.
2171 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002172 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002173 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002174
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002175 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002176 /// part of the return value of this addressing mode matching stuff.
2177 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002178
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002179 /// The instructions inserted by other CodeGenPrepare optimizations.
2180 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002181 /// A map from the instructions to their type before promotion.
2182 InstrToOrigTy &PromotedInsts;
2183 /// The ongoing transaction where every action should be registered.
2184 TypePromotionTransaction &TPT;
2185
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002186 /// This is set to true when we should not do profitability checks.
2187 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002188 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002189
Eric Christopherd75c00c2015-02-26 22:38:34 +00002190 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002191 const TargetMachine &TM, Type *AT, unsigned AS,
2192 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002193 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002194 InstrToOrigTy &PromotedInsts,
2195 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002196 : AddrModeInsts(AMI), TM(TM),
2197 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2198 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002199 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2200 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2201 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002202 IgnoreProfitability = false;
2203 }
2204public:
Stephen Lin837bba12013-07-15 17:55:02 +00002205
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002206 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002207 /// give an access type of AccessTy. This returns a list of involved
2208 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002209 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002210 /// optimizations.
2211 /// \p PromotedInsts maps the instructions to their type before promotion.
2212 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002213 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002214 Instruction *MemoryInst,
2215 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002216 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002217 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002218 InstrToOrigTy &PromotedInsts,
2219 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002220 ExtAddrMode Result;
2221
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002222 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002223 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002224 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002225 (void)Success; assert(Success && "Couldn't select *anything*?");
2226 return Result;
2227 }
2228private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002229 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2230 bool matchAddr(Value *V, unsigned Depth);
2231 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002232 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002233 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002234 ExtAddrMode &AMBefore,
2235 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002236 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2237 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002238 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002239};
2240
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002241/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002242/// Return true and update AddrMode if this addr mode is legal for the target,
2243/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002244bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002245 unsigned Depth) {
2246 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2247 // mode. Just process that directly.
2248 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002249 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002250
Chandler Carruthc8925912013-01-05 02:09:22 +00002251 // If the scale is 0, it takes nothing to add this.
2252 if (Scale == 0)
2253 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002254
Chandler Carruthc8925912013-01-05 02:09:22 +00002255 // If we already have a scale of this value, we can add to it, otherwise, we
2256 // need an available scale field.
2257 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2258 return false;
2259
2260 ExtAddrMode TestAddrMode = AddrMode;
2261
2262 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2263 // [A+B + A*7] -> [B+A*8].
2264 TestAddrMode.Scale += Scale;
2265 TestAddrMode.ScaledReg = ScaleReg;
2266
2267 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002268 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002269 return false;
2270
2271 // It was legal, so commit it.
2272 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002273
Chandler Carruthc8925912013-01-05 02:09:22 +00002274 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2275 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2276 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002277 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002278 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2279 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2280 TestAddrMode.ScaledReg = AddLHS;
2281 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002282
Chandler Carruthc8925912013-01-05 02:09:22 +00002283 // If this addressing mode is legal, commit it and remember that we folded
2284 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002285 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002286 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2287 AddrMode = TestAddrMode;
2288 return true;
2289 }
2290 }
2291
2292 // Otherwise, not (x+c)*scale, just return what we have.
2293 return true;
2294}
2295
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002296/// This is a little filter, which returns true if an addressing computation
2297/// involving I might be folded into a load/store accessing it.
2298/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002299/// the set of instructions that MatchOperationAddr can.
2300static bool MightBeFoldableInst(Instruction *I) {
2301 switch (I->getOpcode()) {
2302 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002303 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002304 // Don't touch identity bitcasts.
2305 if (I->getType() == I->getOperand(0)->getType())
2306 return false;
2307 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2308 case Instruction::PtrToInt:
2309 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2310 return true;
2311 case Instruction::IntToPtr:
2312 // We know the input is intptr_t, so this is foldable.
2313 return true;
2314 case Instruction::Add:
2315 return true;
2316 case Instruction::Mul:
2317 case Instruction::Shl:
2318 // Can only handle X*C and X << C.
2319 return isa<ConstantInt>(I->getOperand(1));
2320 case Instruction::GetElementPtr:
2321 return true;
2322 default:
2323 return false;
2324 }
2325}
2326
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002327/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2328/// \note \p Val is assumed to be the product of some type promotion.
2329/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2330/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002331static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2332 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002333 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2334 if (!PromotedInst)
2335 return false;
2336 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2337 // If the ISDOpcode is undefined, it was undefined before the promotion.
2338 if (!ISDOpcode)
2339 return true;
2340 // Otherwise, check if the promoted instruction is legal or not.
2341 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002342 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002343}
2344
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002345/// \brief Hepler class to perform type promotion.
2346class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002347 /// \brief Utility function to check whether or not a sign or zero extension
2348 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2349 /// either using the operands of \p Inst or promoting \p Inst.
2350 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002351 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002352 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002353 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002354 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002355 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002356 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002357 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002358 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2359 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002360
2361 /// \brief Utility function to determine if \p OpIdx should be promoted when
2362 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002363 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002364 if (isa<SelectInst>(Inst) && OpIdx == 0)
2365 return false;
2366 return true;
2367 }
2368
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002369 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002370 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002371 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002372 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002373 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002374 /// Newly added extensions are inserted in \p Exts.
2375 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002376 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002377 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002378 static Value *promoteOperandForTruncAndAnyExt(
2379 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002380 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002381 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002382 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002383
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002384 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002385 /// operand is promotable and is not a supported trunc or sext.
2386 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002387 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002388 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002389 /// Newly added extensions are inserted in \p Exts.
2390 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002391 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002392 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002393 static Value *promoteOperandForOther(Instruction *Ext,
2394 TypePromotionTransaction &TPT,
2395 InstrToOrigTy &PromotedInsts,
2396 unsigned &CreatedInstsCost,
2397 SmallVectorImpl<Instruction *> *Exts,
2398 SmallVectorImpl<Instruction *> *Truncs,
2399 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002400
2401 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002402 static Value *signExtendOperandForOther(
2403 Instruction *Ext, TypePromotionTransaction &TPT,
2404 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2405 SmallVectorImpl<Instruction *> *Exts,
2406 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2407 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2408 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002409 }
2410
2411 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002412 static Value *zeroExtendOperandForOther(
2413 Instruction *Ext, TypePromotionTransaction &TPT,
2414 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2415 SmallVectorImpl<Instruction *> *Exts,
2416 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2417 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2418 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002419 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002420
2421public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002422 /// Type for the utility function that promotes the operand of Ext.
2423 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002424 InstrToOrigTy &PromotedInsts,
2425 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002426 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002427 SmallVectorImpl<Instruction *> *Truncs,
2428 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002429 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2430 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002431 /// \return NULL if no promotable action is possible with the current
2432 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002433 /// \p InsertedInsts keeps track of all the instructions inserted by the
2434 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002435 /// because we do not want to promote these instructions as CodeGenPrepare
2436 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2437 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002438 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 const TargetLowering &TLI,
2440 const InstrToOrigTy &PromotedInsts);
2441};
2442
2443bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002444 Type *ConsideredExtType,
2445 const InstrToOrigTy &PromotedInsts,
2446 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002447 // The promotion helper does not know how to deal with vector types yet.
2448 // To be able to fix that, we would need to fix the places where we
2449 // statically extend, e.g., constants and such.
2450 if (Inst->getType()->isVectorTy())
2451 return false;
2452
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002453 // We can always get through zext.
2454 if (isa<ZExtInst>(Inst))
2455 return true;
2456
2457 // sext(sext) is ok too.
2458 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459 return true;
2460
2461 // We can get through binary operator, if it is legal. In other words, the
2462 // binary operator must have a nuw or nsw flag.
2463 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2464 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002465 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2466 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002467 return true;
2468
2469 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002470 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002471 if (!isa<TruncInst>(Inst))
2472 return false;
2473
2474 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002475 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002476 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002477 if (!OpndVal->getType()->isIntegerTy() ||
2478 OpndVal->getType()->getIntegerBitWidth() >
2479 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002480 return false;
2481
2482 // If the operand of the truncate is not an instruction, we will not have
2483 // any information on the dropped bits.
2484 // (Actually we could for constant but it is not worth the extra logic).
2485 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2486 if (!Opnd)
2487 return false;
2488
2489 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002490 // I.e., check that trunc just drops extended bits of the same kind of
2491 // the extension.
2492 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002493 const Type *OpndType;
2494 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002495 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2496 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002497 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2498 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002499 else
2500 return false;
2501
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002502 // #2 check that the truncate just drops extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002503 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2504 return true;
2505
2506 return false;
2507}
2508
2509TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002510 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002512 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2513 "Unexpected instruction type");
2514 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2515 Type *ExtTy = Ext->getType();
2516 bool IsSExt = isa<SExtInst>(Ext);
2517 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002518 // get through.
2519 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002520 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002521 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002522
2523 // Do not promote if the operand has been added by codegenprepare.
2524 // Otherwise, it means we are undoing an optimization that is likely to be
2525 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002526 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002527 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002528
2529 // SExt or Trunc instructions.
2530 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002531 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2532 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002533 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002534
2535 // Regular instruction.
2536 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002537 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002538 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002539 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002540}
2541
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002542Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002543 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002544 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002545 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002546 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002547 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2548 // get through it and this method should not be called.
2549 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002550 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002551 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002552 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002553 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002554 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002555 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002556 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002557 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2558 TPT.replaceAllUsesWith(SExt, ZExt);
2559 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002560 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002561 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002562 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2563 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002564 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2565 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002566 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002567
2568 // Remove dead code.
2569 if (SExtOpnd->use_empty())
2570 TPT.eraseInstruction(SExtOpnd);
2571
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002572 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002573 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002574 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002575 if (ExtInst) {
2576 if (Exts)
2577 Exts->push_back(ExtInst);
2578 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2579 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002580 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002581 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002583 // At this point we have: ext ty opnd to ty.
2584 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2585 Value *NextVal = ExtInst->getOperand(0);
2586 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002587 return NextVal;
2588}
2589
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002590Value *TypePromotionHelper::promoteOperandForOther(
2591 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002592 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002593 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002594 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2595 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002596 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002597 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002598 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002599 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002600 if (!ExtOpnd->hasOneUse()) {
2601 // ExtOpnd will be promoted.
2602 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002603 // promoted version.
2604 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002605 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002606 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2607 ITrunc->removeFromParent();
2608 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002609 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002610 if (Truncs)
2611 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002612 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002613
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002614 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002615 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002616 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002617 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002618 }
2619
2620 // Get through the Instruction:
2621 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002622 // 2. Replace the uses of Ext by Inst.
2623 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002624
2625 // Remember the original type of the instruction before promotion.
2626 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002627 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2628 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002629 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002630 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002631 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002632 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002633 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002634 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002635
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002636 DEBUG(dbgs() << "Propagate Ext to operands\n");
2637 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002638 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002639 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2640 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2641 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002642 DEBUG(dbgs() << "No need to propagate\n");
2643 continue;
2644 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002645 // Check if we can statically extend the operand.
2646 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002647 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002648 DEBUG(dbgs() << "Statically extend\n");
2649 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2650 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2651 : Cst->getValue().zext(BitWidth);
2652 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002653 continue;
2654 }
2655 // UndefValue are typed, so we have to statically sign extend them.
2656 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002657 DEBUG(dbgs() << "Statically extend\n");
2658 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002659 continue;
2660 }
2661
2662 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002663 // Check if Ext was reused to extend an operand.
2664 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002665 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002666 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002667 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2668 : TPT.createZExt(Ext, Opnd, Ext->getType());
2669 if (!isa<Instruction>(ValForExtOpnd)) {
2670 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2671 continue;
2672 }
2673 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002674 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002675 if (Exts)
2676 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002677 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002678
2679 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002680 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2681 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002682 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002683 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002684 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002685 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002686 if (ExtForOpnd == Ext) {
2687 DEBUG(dbgs() << "Extension is useless now\n");
2688 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002689 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002690 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002691}
2692
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002693/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002694/// \p NewCost gives the cost of extension instructions created by the
2695/// promotion.
2696/// \p OldCost gives the cost of extension instructions before the promotion
2697/// plus the number of instructions that have been
2698/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00002699/// \p PromotedOperand is the value that has been promoted.
2700/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002701bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00002702 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2703 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2704 // The cost of the new extensions is greater than the cost of the
2705 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00002706 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002707 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002708 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002709 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002710 return true;
2711 // The promotion is neutral but it may help folding the sign extension in
2712 // loads for instance.
2713 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00002714 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002715}
2716
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002717/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002718/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002719/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002720/// If \p MovedAway is not NULL, it contains the information of whether or
2721/// not AddrInst has to be folded into the addressing mode on success.
2722/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2723/// because it has been moved away.
2724/// Thus AddrInst must not be added in the matched instructions.
2725/// This state can happen when AddrInst is a sext, since it may be moved away.
2726/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2727/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002728bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002729 unsigned Depth,
2730 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002731 // Avoid exponential behavior on extremely deep expression trees.
2732 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002733
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002734 // By default, all matched instructions stay in place.
2735 if (MovedAway)
2736 *MovedAway = false;
2737
Chandler Carruthc8925912013-01-05 02:09:22 +00002738 switch (Opcode) {
2739 case Instruction::PtrToInt:
2740 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002741 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00002742 case Instruction::IntToPtr: {
2743 auto AS = AddrInst->getType()->getPointerAddressSpace();
2744 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00002745 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00002746 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002747 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00002748 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00002749 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002750 case Instruction::BitCast:
2751 // BitCast is always a noop, and we can handle it as long as it is
2752 // int->int or pointer->pointer (we don't want int<->fp or something).
2753 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2754 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2755 // Don't touch identity bitcasts. These were probably put here by LSR,
2756 // and we don't want to mess around with them. Assume it knows what it
2757 // is doing.
2758 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00002759 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00002760 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00002761 case Instruction::AddrSpaceCast: {
2762 unsigned SrcAS
2763 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2764 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2765 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00002766 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00002767 return false;
2768 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002769 case Instruction::Add: {
2770 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2771 ExtAddrMode BackupAddrMode = AddrMode;
2772 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002773 // Start a transaction at this point.
2774 // The LHS may match but not the RHS.
2775 // Therefore, we need a higher level restoration point to undo partially
2776 // matched operation.
2777 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2778 TPT.getRestorationPoint();
2779
Sanjay Patelfc580a62015-09-21 23:03:16 +00002780 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
2781 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00002782 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002783
Chandler Carruthc8925912013-01-05 02:09:22 +00002784 // Restore the old addr mode info.
2785 AddrMode = BackupAddrMode;
2786 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002787 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002788
Chandler Carruthc8925912013-01-05 02:09:22 +00002789 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002790 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
2791 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00002792 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002793
Chandler Carruthc8925912013-01-05 02:09:22 +00002794 // Otherwise we definitely can't merge the ADD in.
2795 AddrMode = BackupAddrMode;
2796 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002797 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002798 break;
2799 }
2800 //case Instruction::Or:
2801 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2802 //break;
2803 case Instruction::Mul:
2804 case Instruction::Shl: {
2805 // Can only handle X*C and X << C.
2806 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002807 if (!RHS)
2808 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002809 int64_t Scale = RHS->getSExtValue();
2810 if (Opcode == Instruction::Shl)
2811 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002812
Sanjay Patelfc580a62015-09-21 23:03:16 +00002813 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00002814 }
2815 case Instruction::GetElementPtr: {
2816 // Scan the GEP. We check it if it contains constant offsets and at most
2817 // one variable offset.
2818 int VariableOperand = -1;
2819 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002820
Chandler Carruthc8925912013-01-05 02:09:22 +00002821 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00002822 gep_type_iterator GTI = gep_type_begin(AddrInst);
2823 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2824 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002825 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00002826 unsigned Idx =
2827 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2828 ConstantOffset += SL->getElementOffset(Idx);
2829 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002830 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00002831 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2832 ConstantOffset += CI->getSExtValue()*TypeSize;
2833 } else if (TypeSize) { // Scales of zero don't do anything.
2834 // We only allow one variable index at the moment.
2835 if (VariableOperand != -1)
2836 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002837
Chandler Carruthc8925912013-01-05 02:09:22 +00002838 // Remember the variable index.
2839 VariableOperand = i;
2840 VariableScale = TypeSize;
2841 }
2842 }
2843 }
Stephen Lin837bba12013-07-15 17:55:02 +00002844
Chandler Carruthc8925912013-01-05 02:09:22 +00002845 // A common case is for the GEP to only do a constant offset. In this case,
2846 // just add it to the disp field and check validity.
2847 if (VariableOperand == -1) {
2848 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002849 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002850 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002851 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002852 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00002853 return true;
2854 }
2855 AddrMode.BaseOffs -= ConstantOffset;
2856 return false;
2857 }
2858
2859 // Save the valid addressing mode in case we can't match.
2860 ExtAddrMode BackupAddrMode = AddrMode;
2861 unsigned OldSize = AddrModeInsts.size();
2862
2863 // See if the scale and offset amount is valid for this target.
2864 AddrMode.BaseOffs += ConstantOffset;
2865
2866 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002867 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002868 // If it couldn't be matched, just stuff the value in a register.
2869 if (AddrMode.HasBaseReg) {
2870 AddrMode = BackupAddrMode;
2871 AddrModeInsts.resize(OldSize);
2872 return false;
2873 }
2874 AddrMode.HasBaseReg = true;
2875 AddrMode.BaseReg = AddrInst->getOperand(0);
2876 }
2877
2878 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002879 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002880 Depth)) {
2881 // If it couldn't be matched, try stuffing the base into a register
2882 // instead of matching it, and retrying the match of the scale.
2883 AddrMode = BackupAddrMode;
2884 AddrModeInsts.resize(OldSize);
2885 if (AddrMode.HasBaseReg)
2886 return false;
2887 AddrMode.HasBaseReg = true;
2888 AddrMode.BaseReg = AddrInst->getOperand(0);
2889 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00002890 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00002891 VariableScale, Depth)) {
2892 // If even that didn't work, bail.
2893 AddrMode = BackupAddrMode;
2894 AddrModeInsts.resize(OldSize);
2895 return false;
2896 }
2897 }
2898
2899 return true;
2900 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002901 case Instruction::SExt:
2902 case Instruction::ZExt: {
2903 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2904 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002905 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002906
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002907 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002908 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002909 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002910 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002911 if (!TPH)
2912 return false;
2913
2914 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2915 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00002916 unsigned CreatedInstsCost = 0;
2917 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002918 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00002919 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002920 // SExt has been moved away.
2921 // Thus either it will be rematched later in the recursive calls or it is
2922 // gone. Anyway, we must not fold it into the addressing mode at this point.
2923 // E.g.,
2924 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002925 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002926 // addr = gep base, idx
2927 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002928 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002929 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2930 // addr = gep base, op <- match
2931 if (MovedAway)
2932 *MovedAway = true;
2933
2934 assert(PromotedOperand &&
2935 "TypePromotionHelper should have filtered out those cases");
2936
2937 ExtAddrMode BackupAddrMode = AddrMode;
2938 unsigned OldSize = AddrModeInsts.size();
2939
Sanjay Patelfc580a62015-09-21 23:03:16 +00002940 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002941 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00002942 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002943 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00002944 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002945 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002946 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00002947 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002948 AddrMode = BackupAddrMode;
2949 AddrModeInsts.resize(OldSize);
2950 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2951 TPT.rollback(LastKnownGood);
2952 return false;
2953 }
2954 return true;
2955 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002956 }
2957 return false;
2958}
2959
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002960/// If we can, try to add the value of 'Addr' into the current addressing mode.
2961/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
2962/// unmodified. This assumes that Addr is either a pointer type or intptr_t
2963/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00002964///
Sanjay Patelfc580a62015-09-21 23:03:16 +00002965bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002966 // Start a transaction at this point that we will rollback if the matching
2967 // fails.
2968 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2969 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002970 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2971 // Fold in immediates if legal for the target.
2972 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002973 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002974 return true;
2975 AddrMode.BaseOffs -= CI->getSExtValue();
2976 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2977 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002978 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002979 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002980 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002981 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002982 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002983 }
2984 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2985 ExtAddrMode BackupAddrMode = AddrMode;
2986 unsigned OldSize = AddrModeInsts.size();
2987
2988 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002989 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00002990 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002991 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002992 // to check here.
2993 if (MovedAway)
2994 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002995 // Okay, it's possible to fold this. Check to see if it is actually
2996 // *profitable* to do so. We use a simple cost model to avoid increasing
2997 // register pressure too much.
2998 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00002999 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003000 AddrModeInsts.push_back(I);
3001 return true;
3002 }
Stephen Lin837bba12013-07-15 17:55:02 +00003003
Chandler Carruthc8925912013-01-05 02:09:22 +00003004 // It isn't profitable to do this, roll back.
3005 //cerr << "NOT FOLDING: " << *I;
3006 AddrMode = BackupAddrMode;
3007 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003008 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003009 }
3010 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003011 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003012 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003013 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003014 } else if (isa<ConstantPointerNull>(Addr)) {
3015 // Null pointer gets folded without affecting the addressing mode.
3016 return true;
3017 }
3018
3019 // Worse case, the target should support [reg] addressing modes. :)
3020 if (!AddrMode.HasBaseReg) {
3021 AddrMode.HasBaseReg = true;
3022 AddrMode.BaseReg = Addr;
3023 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003024 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003025 return true;
3026 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003027 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003028 }
3029
3030 // If the base register is already taken, see if we can do [r+r].
3031 if (AddrMode.Scale == 0) {
3032 AddrMode.Scale = 1;
3033 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003034 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003035 return true;
3036 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003037 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003038 }
3039 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003040 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003041 return false;
3042}
3043
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003044/// Check to see if all uses of OpVal by the specified inline asm call are due
3045/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003046static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003047 const TargetMachine &TM) {
3048 const Function *F = CI->getParent()->getParent();
3049 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3050 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003051 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003052 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3053 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003054 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3055 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003056
Chandler Carruthc8925912013-01-05 02:09:22 +00003057 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003058 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003059
3060 // If this asm operand is our Value*, and if it isn't an indirect memory
3061 // operand, we can't fold it!
3062 if (OpInfo.CallOperandVal == OpVal &&
3063 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3064 !OpInfo.isIndirect))
3065 return false;
3066 }
3067
3068 return true;
3069}
3070
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003071/// Recursively walk all the uses of I until we find a memory use.
3072/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003073/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003074static bool FindAllMemoryUses(
3075 Instruction *I,
3076 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3077 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003078 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003079 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003080 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003081
Chandler Carruthc8925912013-01-05 02:09:22 +00003082 // If this is an obviously unfoldable instruction, bail out.
3083 if (!MightBeFoldableInst(I))
3084 return true;
3085
3086 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003087 for (Use &U : I->uses()) {
3088 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003089
Chandler Carruthcdf47882014-03-09 03:16:01 +00003090 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3091 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003092 continue;
3093 }
Stephen Lin837bba12013-07-15 17:55:02 +00003094
Chandler Carruthcdf47882014-03-09 03:16:01 +00003095 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3096 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003097 if (opNo == 0) return true; // Storing addr, not into addr.
3098 MemoryUses.push_back(std::make_pair(SI, opNo));
3099 continue;
3100 }
Stephen Lin837bba12013-07-15 17:55:02 +00003101
Chandler Carruthcdf47882014-03-09 03:16:01 +00003102 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003103 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3104 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003105
Chandler Carruthc8925912013-01-05 02:09:22 +00003106 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003107 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003108 return true;
3109 continue;
3110 }
Stephen Lin837bba12013-07-15 17:55:02 +00003111
Eric Christopher11e4df72015-02-26 22:38:43 +00003112 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003113 return true;
3114 }
3115
3116 return false;
3117}
3118
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003119/// Return true if Val is already known to be live at the use site that we're
3120/// folding it into. If so, there is no cost to include it in the addressing
3121/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3122/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003123bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003124 Value *KnownLive2) {
3125 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003126 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003127 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003128
Chandler Carruthc8925912013-01-05 02:09:22 +00003129 // All values other than instructions and arguments (e.g. constants) are live.
3130 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003131
Chandler Carruthc8925912013-01-05 02:09:22 +00003132 // If Val is a constant sized alloca in the entry block, it is live, this is
3133 // true because it is just a reference to the stack/frame pointer, which is
3134 // live for the whole function.
3135 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3136 if (AI->isStaticAlloca())
3137 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003138
Chandler Carruthc8925912013-01-05 02:09:22 +00003139 // Check to see if this value is already used in the memory instruction's
3140 // block. If so, it's already live into the block at the very least, so we
3141 // can reasonably fold it.
3142 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3143}
3144
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003145/// It is possible for the addressing mode of the machine to fold the specified
3146/// instruction into a load or store that ultimately uses it.
3147/// However, the specified instruction has multiple uses.
3148/// Given this, it may actually increase register pressure to fold it
3149/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003150///
3151/// X = ...
3152/// Y = X+1
3153/// use(Y) -> nonload/store
3154/// Z = Y+1
3155/// load Z
3156///
3157/// In this case, Y has multiple uses, and can be folded into the load of Z
3158/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3159/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3160/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3161/// number of computations either.
3162///
3163/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3164/// X was live across 'load Z' for other reasons, we actually *would* want to
3165/// fold the addressing mode in the Z case. This would make Y die earlier.
3166bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003167isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003168 ExtAddrMode &AMAfter) {
3169 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003170
Chandler Carruthc8925912013-01-05 02:09:22 +00003171 // AMBefore is the addressing mode before this instruction was folded into it,
3172 // and AMAfter is the addressing mode after the instruction was folded. Get
3173 // the set of registers referenced by AMAfter and subtract out those
3174 // referenced by AMBefore: this is the set of values which folding in this
3175 // address extends the lifetime of.
3176 //
3177 // Note that there are only two potential values being referenced here,
3178 // BaseReg and ScaleReg (global addresses are always available, as are any
3179 // folded immediates).
3180 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003181
Chandler Carruthc8925912013-01-05 02:09:22 +00003182 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3183 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003184 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003185 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003186 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003187 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003188
3189 // If folding this instruction (and it's subexprs) didn't extend any live
3190 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003191 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003192 return true;
3193
3194 // If all uses of this instruction are ultimately load/store/inlineasm's,
3195 // check to see if their addressing modes will include this instruction. If
3196 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3197 // uses.
3198 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3199 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003200 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003201 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003202
Chandler Carruthc8925912013-01-05 02:09:22 +00003203 // Now that we know that all uses of this instruction are part of a chain of
3204 // computation involving only operations that could theoretically be folded
3205 // into a memory use, loop over each of these uses and see if they could
3206 // *actually* fold the instruction.
3207 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3208 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3209 Instruction *User = MemoryUses[i].first;
3210 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003211
Chandler Carruthc8925912013-01-05 02:09:22 +00003212 // Get the access type of this use. If the use isn't a pointer, we don't
3213 // know what it accesses.
3214 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003215 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3216 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003217 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003218 Type *AddressAccessTy = AddrTy->getElementType();
3219 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003220
Chandler Carruthc8925912013-01-05 02:09:22 +00003221 // Do a match against the root of this address, ignoring profitability. This
3222 // will tell us if the addressing mode for the memory operation will
3223 // *actually* cover the shared instruction.
3224 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003225 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3226 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003227 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003228 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003229 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003230 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003231 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003232 (void)Success; assert(Success && "Couldn't select *anything*?");
3233
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003234 // The match was to check the profitability, the changes made are not
3235 // part of the original matcher. Therefore, they should be dropped
3236 // otherwise the original matcher will not present the right state.
3237 TPT.rollback(LastKnownGood);
3238
Chandler Carruthc8925912013-01-05 02:09:22 +00003239 // If the match didn't cover I, then it won't be shared by it.
3240 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3241 I) == MatchedAddrModeInsts.end())
3242 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003243
Chandler Carruthc8925912013-01-05 02:09:22 +00003244 MatchedAddrModeInsts.clear();
3245 }
Stephen Lin837bba12013-07-15 17:55:02 +00003246
Chandler Carruthc8925912013-01-05 02:09:22 +00003247 return true;
3248}
3249
3250} // end anonymous namespace
3251
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003252/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003253/// different basic block than BB.
3254static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3255 if (Instruction *I = dyn_cast<Instruction>(V))
3256 return I->getParent() != BB;
3257 return false;
3258}
3259
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003260/// Load and Store Instructions often have addressing modes that can do
3261/// significant amounts of computation. As such, instruction selection will try
3262/// to get the load or store to do as much computation as possible for the
3263/// program. The problem is that isel can only see within a single block. As
3264/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003265///
3266/// This method is used to optimize both load/store and inline asms with memory
3267/// operands.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003268bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003269 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003270 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003271
3272 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003273 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003274 SmallVector<Value*, 8> worklist;
3275 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003276 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003277
Owen Anderson8ba5f392010-11-27 08:15:55 +00003278 // Use a worklist to iteratively look through PHI nodes, and ensure that
3279 // the addressing mode obtained from the non-PHI roots of the graph
3280 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003281 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003282 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003283 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003284 SmallVector<Instruction*, 16> AddrModeInsts;
3285 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003286 TypePromotionTransaction TPT;
3287 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3288 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003289 while (!worklist.empty()) {
3290 Value *V = worklist.back();
3291 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003292
Owen Anderson8ba5f392010-11-27 08:15:55 +00003293 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003294 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003295 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003296 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003297 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003298
Owen Anderson8ba5f392010-11-27 08:15:55 +00003299 // For a PHI node, push all of its incoming values.
3300 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003301 for (Value *IncValue : P->incoming_values())
3302 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003303 continue;
3304 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003305
Owen Anderson8ba5f392010-11-27 08:15:55 +00003306 // For non-PHIs, determine the addressing mode being computed.
3307 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003308 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003309 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003310 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003311
3312 // This check is broken into two cases with very similar code to avoid using
3313 // getNumUses() as much as possible. Some values have a lot of uses, so
3314 // calling getNumUses() unconditionally caused a significant compile-time
3315 // regression.
3316 if (!Consensus) {
3317 Consensus = V;
3318 AddrMode = NewAddrMode;
3319 AddrModeInsts = NewAddrModeInsts;
3320 continue;
3321 } else if (NewAddrMode == AddrMode) {
3322 if (!IsNumUsesConsensusValid) {
3323 NumUsesConsensus = Consensus->getNumUses();
3324 IsNumUsesConsensusValid = true;
3325 }
3326
3327 // Ensure that the obtained addressing mode is equivalent to that obtained
3328 // for all other roots of the PHI traversal. Also, when choosing one
3329 // such root as representative, select the one with the most uses in order
3330 // to keep the cost modeling heuristics in AddressingModeMatcher
3331 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003332 unsigned NumUses = V->getNumUses();
3333 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003334 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003335 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003336 AddrModeInsts = NewAddrModeInsts;
3337 }
3338 continue;
3339 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003340
Craig Topperc0196b12014-04-14 00:51:57 +00003341 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003342 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003343 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003344
Owen Anderson8ba5f392010-11-27 08:15:55 +00003345 // If the addressing mode couldn't be determined, or if multiple different
3346 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003347 if (!Consensus) {
3348 TPT.rollback(LastKnownGood);
3349 return false;
3350 }
3351 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003352
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003353 // Check to see if any of the instructions supersumed by this addr mode are
3354 // non-local to I's BB.
3355 bool AnyNonLocal = false;
3356 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003357 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003358 AnyNonLocal = true;
3359 break;
3360 }
3361 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003362
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003363 // If all the instructions matched are already in this BB, don't do anything.
3364 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003365 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003366 return false;
3367 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003368
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003369 // Insert this computation right after this user. Since our caller is
3370 // scanning from the top of the BB to the bottom, reuse of the expr are
3371 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003372 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003373
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003374 // Now that we determined the addressing expression we want to use and know
3375 // that we have to sink it into this block. Check to see if we have already
3376 // done this for some other load/store instr in this block. If so, reuse the
3377 // computation.
3378 Value *&SunkAddr = SunkAddrs[Addr];
3379 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003380 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003381 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003382 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003383 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003384 } else if (AddrSinkUsingGEPs ||
3385 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003386 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3387 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003388 // By default, we use the GEP-based method when AA is used later. This
3389 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3390 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003391 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003392 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003393 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003394
3395 // First, find the pointer.
3396 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3397 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003398 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003399 }
3400
3401 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3402 // We can't add more than one pointer together, nor can we scale a
3403 // pointer (both of which seem meaningless).
3404 if (ResultPtr || AddrMode.Scale != 1)
3405 return false;
3406
3407 ResultPtr = AddrMode.ScaledReg;
3408 AddrMode.Scale = 0;
3409 }
3410
3411 if (AddrMode.BaseGV) {
3412 if (ResultPtr)
3413 return false;
3414
3415 ResultPtr = AddrMode.BaseGV;
3416 }
3417
3418 // If the real base value actually came from an inttoptr, then the matcher
3419 // will look through it and provide only the integer value. In that case,
3420 // use it here.
3421 if (!ResultPtr && AddrMode.BaseReg) {
3422 ResultPtr =
3423 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003424 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003425 } else if (!ResultPtr && AddrMode.Scale == 1) {
3426 ResultPtr =
3427 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3428 AddrMode.Scale = 0;
3429 }
3430
3431 if (!ResultPtr &&
3432 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3433 SunkAddr = Constant::getNullValue(Addr->getType());
3434 } else if (!ResultPtr) {
3435 return false;
3436 } else {
3437 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003438 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3439 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003440
3441 // Start with the base register. Do this first so that subsequent address
3442 // matching finds it last, which will prevent it from trying to match it
3443 // as the scaled value in case it happens to be a mul. That would be
3444 // problematic if we've sunk a different mul for the scale, because then
3445 // we'd end up sinking both muls.
3446 if (AddrMode.BaseReg) {
3447 Value *V = AddrMode.BaseReg;
3448 if (V->getType() != IntPtrTy)
3449 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3450
3451 ResultIndex = V;
3452 }
3453
3454 // Add the scale value.
3455 if (AddrMode.Scale) {
3456 Value *V = AddrMode.ScaledReg;
3457 if (V->getType() == IntPtrTy) {
3458 // done.
3459 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3460 cast<IntegerType>(V->getType())->getBitWidth()) {
3461 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3462 } else {
3463 // It is only safe to sign extend the BaseReg if we know that the math
3464 // required to create it did not overflow before we extend it. Since
3465 // the original IR value was tossed in favor of a constant back when
3466 // the AddrMode was created we need to bail out gracefully if widths
3467 // do not match instead of extending it.
3468 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3469 if (I && (ResultIndex != AddrMode.BaseReg))
3470 I->eraseFromParent();
3471 return false;
3472 }
3473
3474 if (AddrMode.Scale != 1)
3475 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3476 "sunkaddr");
3477 if (ResultIndex)
3478 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3479 else
3480 ResultIndex = V;
3481 }
3482
3483 // Add in the Base Offset if present.
3484 if (AddrMode.BaseOffs) {
3485 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3486 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003487 // We need to add this separately from the scale above to help with
3488 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003489 if (ResultPtr->getType() != I8PtrTy)
3490 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003491 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003492 }
3493
3494 ResultIndex = V;
3495 }
3496
3497 if (!ResultIndex) {
3498 SunkAddr = ResultPtr;
3499 } else {
3500 if (ResultPtr->getType() != I8PtrTy)
3501 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003502 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003503 }
3504
3505 if (SunkAddr->getType() != Addr->getType())
3506 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3507 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003508 } else {
David Greene74e2d492010-01-05 01:27:11 +00003509 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003510 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003511 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003512 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003513
3514 // Start with the base register. Do this first so that subsequent address
3515 // matching finds it last, which will prevent it from trying to match it
3516 // as the scaled value in case it happens to be a mul. That would be
3517 // problematic if we've sunk a different mul for the scale, because then
3518 // we'd end up sinking both muls.
3519 if (AddrMode.BaseReg) {
3520 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003521 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003522 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003523 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003524 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003525 Result = V;
3526 }
3527
3528 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003529 if (AddrMode.Scale) {
3530 Value *V = AddrMode.ScaledReg;
3531 if (V->getType() == IntPtrTy) {
3532 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003533 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003534 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003535 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3536 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003537 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003538 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003539 // It is only safe to sign extend the BaseReg if we know that the math
3540 // required to create it did not overflow before we extend it. Since
3541 // the original IR value was tossed in favor of a constant back when
3542 // the AddrMode was created we need to bail out gracefully if widths
3543 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003544 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003545 if (I && (Result != AddrMode.BaseReg))
3546 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003547 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003548 }
3549 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003550 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3551 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003552 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003553 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003554 else
3555 Result = V;
3556 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003557
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003558 // Add in the BaseGV if present.
3559 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003560 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003561 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003562 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003563 else
3564 Result = V;
3565 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003566
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003567 // Add in the Base Offset if present.
3568 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003569 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003570 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003571 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003572 else
3573 Result = V;
3574 }
3575
Craig Topperc0196b12014-04-14 00:51:57 +00003576 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003577 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003578 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003579 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003580 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003581
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003582 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003583
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003584 // If we have no uses, recursively delete the value and all dead instructions
3585 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003586 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003587 // This can cause recursive deletion, which can invalidate our iterator.
3588 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003589 WeakVH IterHandle(&*CurInstIterator);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003590 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003591
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003592 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003593
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003594 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003595 // If the iterator instruction was recursively deleted, start over at the
3596 // start of the block.
3597 CurInstIterator = BB->begin();
3598 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003599 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003600 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003601 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003602 return true;
3603}
3604
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003605/// If there are any memory operands, use OptimizeMemoryInst to sink their
3606/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003607bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003608 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003609
Eric Christopher11e4df72015-02-26 22:38:43 +00003610 const TargetRegisterInfo *TRI =
3611 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003612 TargetLowering::AsmOperandInfoVector TargetConstraints =
3613 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003614 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003615 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3616 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003617
Evan Cheng1da25002008-02-26 02:42:37 +00003618 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003619 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003620
Eli Friedman666bbe32008-02-26 18:37:49 +00003621 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3622 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003623 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003624 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003625 } else if (OpInfo.Type == InlineAsm::isInput)
3626 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003627 }
3628
3629 return MadeChange;
3630}
3631
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003632/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3633/// sign extensions.
3634static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3635 assert(!Inst->use_empty() && "Input must have at least one use");
3636 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3637 bool IsSExt = isa<SExtInst>(FirstUser);
3638 Type *ExtTy = FirstUser->getType();
3639 for (const User *U : Inst->users()) {
3640 const Instruction *UI = cast<Instruction>(U);
3641 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3642 return false;
3643 Type *CurTy = UI->getType();
3644 // Same input and output types: Same instruction after CSE.
3645 if (CurTy == ExtTy)
3646 continue;
3647
3648 // If IsSExt is true, we are in this situation:
3649 // a = Inst
3650 // b = sext ty1 a to ty2
3651 // c = sext ty1 a to ty3
3652 // Assuming ty2 is shorter than ty3, this could be turned into:
3653 // a = Inst
3654 // b = sext ty1 a to ty2
3655 // c = sext ty2 b to ty3
3656 // However, the last sext is not free.
3657 if (IsSExt)
3658 return false;
3659
3660 // This is a ZExt, maybe this is free to extend from one type to another.
3661 // In that case, we would not account for a different use.
3662 Type *NarrowTy;
3663 Type *LargeTy;
3664 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3665 CurTy->getScalarType()->getIntegerBitWidth()) {
3666 NarrowTy = CurTy;
3667 LargeTy = ExtTy;
3668 } else {
3669 NarrowTy = ExtTy;
3670 LargeTy = CurTy;
3671 }
3672
3673 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3674 return false;
3675 }
3676 // All uses are the same or can be derived from one another for free.
3677 return true;
3678}
3679
3680/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3681/// load instruction.
3682/// If an ext(load) can be formed, it is returned via \p LI for the load
3683/// and \p Inst for the extension.
3684/// Otherwise LI == nullptr and Inst == nullptr.
3685/// When some promotion happened, \p TPT contains the proper state to
3686/// revert them.
3687///
3688/// \return true when promoting was necessary to expose the ext(load)
3689/// opportunity, false otherwise.
3690///
3691/// Example:
3692/// \code
3693/// %ld = load i32* %addr
3694/// %add = add nuw i32 %ld, 4
3695/// %zext = zext i32 %add to i64
3696/// \endcode
3697/// =>
3698/// \code
3699/// %ld = load i32* %addr
3700/// %zext = zext i32 %ld to i64
3701/// %add = add nuw i64 %zext, 4
3702/// \encode
3703/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003704bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003705 LoadInst *&LI, Instruction *&Inst,
3706 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003707 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003708 // Iterate over all the extensions to see if one form an ext(load).
3709 for (auto I : Exts) {
3710 // Check if we directly have ext(load).
3711 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3712 Inst = I;
3713 // No promotion happened here.
3714 return false;
3715 }
3716 // Check whether or not we want to do any promotion.
3717 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3718 continue;
3719 // Get the action to perform the promotion.
3720 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003721 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003722 // Check if we can promote.
3723 if (!TPH)
3724 continue;
3725 // Save the current state.
3726 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3727 TPT.getRestorationPoint();
3728 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003729 unsigned NewCreatedInstsCost = 0;
3730 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003731 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003732 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3733 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003734 assert(PromotedVal &&
3735 "TypePromotionHelper should have filtered out those cases");
3736
3737 // We would be able to merge only one extension in a load.
3738 // Therefore, if we have more than 1 new extension we heuristically
3739 // cut this search path, because it means we degrade the code quality.
3740 // With exactly 2, the transformation is neutral, because we will merge
3741 // one extension but leave one. However, we optimistically keep going,
3742 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003743 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3744 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003745 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00003746 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00003747 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003748 // The promotion is not profitable, rollback to the previous state.
3749 TPT.rollback(LastKnownGood);
3750 continue;
3751 }
3752 // The promotion is profitable.
3753 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003754 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003755 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003756 // If we have created a new extension, i.e., now we have two
3757 // extensions. We must make sure one of them is merged with
3758 // the load, otherwise we may degrade the code quality.
3759 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3760 // Promotion happened.
3761 return true;
3762 // If this does not help to expose an ext(load) then, rollback.
3763 TPT.rollback(LastKnownGood);
3764 }
3765 // None of the extension can form an ext(load).
3766 LI = nullptr;
3767 Inst = nullptr;
3768 return false;
3769}
3770
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003771/// Move a zext or sext fed by a load into the same basic block as the load,
3772/// unless conditions are unfavorable. This allows SelectionDAG to fold the
3773/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003774/// \p I[in/out] the extension may be modified during the process if some
3775/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003776///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003777bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003778 // Try to promote a chain of computation if it allows to form
3779 // an extended load.
3780 TypePromotionTransaction TPT;
3781 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3782 TPT.getRestorationPoint();
3783 SmallVector<Instruction *, 1> Exts;
3784 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003785 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003786 LoadInst *LI = nullptr;
3787 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003788 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003789 if (!LI || !I) {
3790 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3791 "the code must remain the same");
3792 I = OldExt;
3793 return false;
3794 }
Dan Gohman99429a02009-10-16 20:59:35 +00003795
3796 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003797 // Make the cheap checks first if we did not promote.
3798 // If we promoted, we need to check if it is indeed profitable.
3799 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003800 return false;
3801
Mehdi Amini44ede332015-07-09 02:09:04 +00003802 EVT VT = TLI->getValueType(*DL, I->getType());
3803 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003804
Dan Gohman99429a02009-10-16 20:59:35 +00003805 // If the load has other users and the truncate is not free, this probably
3806 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003807 if (!LI->hasOneUse() && TLI &&
3808 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003809 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3810 I = OldExt;
3811 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003812 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003813 }
Dan Gohman99429a02009-10-16 20:59:35 +00003814
3815 // Check whether the target supports casts folded into loads.
3816 unsigned LType;
3817 if (isa<ZExtInst>(I))
3818 LType = ISD::ZEXTLOAD;
3819 else {
3820 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3821 LType = ISD::SEXTLOAD;
3822 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003823 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003824 I = OldExt;
3825 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003826 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003827 }
Dan Gohman99429a02009-10-16 20:59:35 +00003828
3829 // Move the extend into the same block as the load, so that SelectionDAG
3830 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003831 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003832 I->removeFromParent();
3833 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003834 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003835 return true;
3836}
3837
Sanjay Patelfc580a62015-09-21 23:03:16 +00003838bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00003839 BasicBlock *DefBB = I->getParent();
3840
Bob Wilsonff714f92010-09-21 21:44:14 +00003841 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003842 // other uses of the source with result of extension.
3843 Value *Src = I->getOperand(0);
3844 if (Src->hasOneUse())
3845 return false;
3846
Evan Cheng2011df42007-12-13 07:50:36 +00003847 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003848 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003849 return false;
3850
Evan Cheng7bc89422007-12-12 00:51:06 +00003851 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003852 // this block.
3853 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003854 return false;
3855
Evan Chengd3d80172007-12-05 23:58:20 +00003856 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003857 for (User *U : I->users()) {
3858 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003859
3860 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003861 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003862 if (UserBB == DefBB) continue;
3863 DefIsLiveOut = true;
3864 break;
3865 }
3866 if (!DefIsLiveOut)
3867 return false;
3868
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003869 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003870 for (User *U : Src->users()) {
3871 Instruction *UI = cast<Instruction>(U);
3872 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003873 if (UserBB == DefBB) continue;
3874 // Be conservative. We don't want this xform to end up introducing
3875 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003876 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003877 return false;
3878 }
3879
Evan Chengd3d80172007-12-05 23:58:20 +00003880 // InsertedTruncs - Only insert one trunc in each block once.
3881 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3882
3883 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003884 for (Use &U : Src->uses()) {
3885 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003886
3887 // Figure out which BB this ext is used in.
3888 BasicBlock *UserBB = User->getParent();
3889 if (UserBB == DefBB) continue;
3890
3891 // Both src and def are live in this block. Rewrite the use.
3892 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3893
3894 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003895 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003896 assert(InsertPt != UserBB->end());
3897 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003898 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003899 }
3900
3901 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003902 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003903 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003904 MadeChange = true;
3905 }
3906
3907 return MadeChange;
3908}
3909
Sanjay Patel69a50a12015-10-19 21:59:12 +00003910/// Check if V (an operand of a select instruction) is an expensive instruction
3911/// that is only used once.
3912static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
3913 auto *I = dyn_cast<Instruction>(V);
3914 // If it's safe to speculatively execute, then it should not have side
3915 // effects; therefore, it's safe to sink and possibly *not* execute.
3916 if (I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
3917 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive)
3918 return true;
3919
3920 return false;
3921}
3922
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003923/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00003924static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
3925 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003926 // FIXME: This should use the same heuristics as IfConversion to determine
3927 // whether a select is better represented as a branch. This requires that
3928 // branch probability metadata is preserved for the select, which is not the
3929 // case currently.
3930
3931 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3932
Sanjay Patel4e652762015-09-28 22:14:51 +00003933 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
3934 // comparison condition. If the compare has more than one use, there's
3935 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00003936 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003937 return false;
3938
3939 Value *CmpOp0 = Cmp->getOperand(0);
3940 Value *CmpOp1 = Cmp->getOperand(1);
3941
Sanjay Patel4e652762015-09-28 22:14:51 +00003942 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
3943 // on a load from memory. But if the load is used more than once, do not
3944 // change the select to a branch because the load is probably needed
3945 // regardless of whether the branch is taken or not.
Sanjay Patel69a50a12015-10-19 21:59:12 +00003946 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3947 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
3948 return true;
3949
3950 // If either operand of the select is expensive and only needed on one side
3951 // of the select, we should form a branch.
3952 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
3953 sinkSelectOperand(TTI, SI->getFalseValue()))
3954 return true;
3955
3956 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003957}
3958
3959
Nadav Rotem9d832022012-09-02 12:10:19 +00003960/// If we have a SelectInst that will likely profit from branch prediction,
3961/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003962bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003963 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3964
3965 // Can we convert the 'select' to CF ?
3966 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003967 return false;
3968
Nadav Rotem9d832022012-09-02 12:10:19 +00003969 TargetLowering::SelectSupportKind SelectKind;
3970 if (VectorCond)
3971 SelectKind = TargetLowering::VectorMaskSelect;
3972 else if (SI->getType()->isVectorTy())
3973 SelectKind = TargetLowering::ScalarCondVectorVal;
3974 else
3975 SelectKind = TargetLowering::ScalarValSelect;
3976
3977 // Do we have efficient codegen support for this kind of 'selects' ?
3978 if (TLI->isSelectSupported(SelectKind)) {
3979 // We have efficient codegen support for the select instruction.
3980 // Check if it is profitable to keep this 'select'.
3981 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00003982 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00003983 return false;
3984 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003985
3986 ModifiedDT = true;
3987
Sanjay Patel69a50a12015-10-19 21:59:12 +00003988 // Transform a sequence like this:
3989 // start:
3990 // %cmp = cmp uge i32 %a, %b
3991 // %sel = select i1 %cmp, i32 %c, i32 %d
3992 //
3993 // Into:
3994 // start:
3995 // %cmp = cmp uge i32 %a, %b
3996 // br i1 %cmp, label %select.true, label %select.false
3997 // select.true:
3998 // br label %select.end
3999 // select.false:
4000 // br label %select.end
4001 // select.end:
4002 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4003 //
4004 // In addition, we may sink instructions that produce %c or %d from
4005 // the entry block into the destination(s) of the new branch.
4006 // If the true or false blocks do not contain a sunken instruction, that
4007 // block and its branch may be optimized away. In that case, one side of the
4008 // first branch will point directly to select.end, and the corresponding PHI
4009 // predecessor block will be the start block.
4010
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004011 // First, we split the block containing the select into 2 blocks.
4012 BasicBlock *StartBlock = SI->getParent();
4013 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004014 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004015
Sanjay Patel69a50a12015-10-19 21:59:12 +00004016 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004017 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004018
4019 // These are the new basic blocks for the conditional branch.
4020 // At least one will become an actual new basic block.
4021 BasicBlock *TrueBlock = nullptr;
4022 BasicBlock *FalseBlock = nullptr;
4023
4024 // Sink expensive instructions into the conditional blocks to avoid executing
4025 // them speculatively.
4026 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4027 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4028 EndBlock->getParent(), EndBlock);
4029 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4030 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4031 TrueInst->moveBefore(TrueBranch);
4032 }
4033 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4034 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4035 EndBlock->getParent(), EndBlock);
4036 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4037 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4038 FalseInst->moveBefore(FalseBranch);
4039 }
4040
4041 // If there was nothing to sink, then arbitrarily choose the 'false' side
4042 // for a new input value to the PHI.
4043 if (TrueBlock == FalseBlock) {
4044 assert(TrueBlock == nullptr &&
4045 "Unexpected basic block transform while optimizing select");
4046
4047 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4048 EndBlock->getParent(), EndBlock);
4049 BranchInst::Create(EndBlock, FalseBlock);
4050 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004051
4052 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004053 // If we did not create a new block for one of the 'true' or 'false' paths
4054 // of the condition, it means that side of the branch goes to the end block
4055 // directly and the path originates from the start block from the point of
4056 // view of the new PHI.
4057 if (TrueBlock == nullptr) {
4058 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
4059 TrueBlock = StartBlock;
4060 } else if (FalseBlock == nullptr) {
4061 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4062 FalseBlock = StartBlock;
4063 } else {
4064 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4065 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004066
4067 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004068 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004069 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004070 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4071 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4072
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004073 SI->replaceAllUsesWith(PN);
4074 SI->eraseFromParent();
4075
4076 // Instruct OptimizeBlock to skip to the next block.
4077 CurInstIterator = StartBlock->end();
4078 ++NumSelectsExpanded;
4079 return true;
4080}
4081
Benjamin Kramer573ff362014-03-01 17:24:40 +00004082static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004083 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4084 int SplatElem = -1;
4085 for (unsigned i = 0; i < Mask.size(); ++i) {
4086 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4087 return false;
4088 SplatElem = Mask[i];
4089 }
4090
4091 return true;
4092}
4093
4094/// Some targets have expensive vector shifts if the lanes aren't all the same
4095/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4096/// it's often worth sinking a shufflevector splat down to its use so that
4097/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004098bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004099 BasicBlock *DefBB = SVI->getParent();
4100
4101 // Only do this xform if variable vector shifts are particularly expensive.
4102 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4103 return false;
4104
4105 // We only expect better codegen by sinking a shuffle if we can recognise a
4106 // constant splat.
4107 if (!isBroadcastShuffle(SVI))
4108 return false;
4109
4110 // InsertedShuffles - Only insert a shuffle in each block once.
4111 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4112
4113 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004114 for (User *U : SVI->users()) {
4115 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004116
4117 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004118 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004119 if (UserBB == DefBB) continue;
4120
4121 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004122 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004123
4124 // Everything checks out, sink the shuffle if the user's block doesn't
4125 // already have a copy.
4126 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4127
4128 if (!InsertedShuffle) {
4129 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004130 assert(InsertPt != UserBB->end());
4131 InsertedShuffle =
4132 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4133 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004134 }
4135
Chandler Carruthcdf47882014-03-09 03:16:01 +00004136 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004137 MadeChange = true;
4138 }
4139
4140 // If we removed all uses, nuke the shuffle.
4141 if (SVI->use_empty()) {
4142 SVI->eraseFromParent();
4143 MadeChange = true;
4144 }
4145
4146 return MadeChange;
4147}
4148
Quentin Colombetc32615d2014-10-31 17:52:53 +00004149namespace {
4150/// \brief Helper class to promote a scalar operation to a vector one.
4151/// This class is used to move downward extractelement transition.
4152/// E.g.,
4153/// a = vector_op <2 x i32>
4154/// b = extractelement <2 x i32> a, i32 0
4155/// c = scalar_op b
4156/// store c
4157///
4158/// =>
4159/// a = vector_op <2 x i32>
4160/// c = vector_op a (equivalent to scalar_op on the related lane)
4161/// * d = extractelement <2 x i32> c, i32 0
4162/// * store d
4163/// Assuming both extractelement and store can be combine, we get rid of the
4164/// transition.
4165class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004166 /// DataLayout associated with the current module.
4167 const DataLayout &DL;
4168
Quentin Colombetc32615d2014-10-31 17:52:53 +00004169 /// Used to perform some checks on the legality of vector operations.
4170 const TargetLowering &TLI;
4171
4172 /// Used to estimated the cost of the promoted chain.
4173 const TargetTransformInfo &TTI;
4174
4175 /// The transition being moved downwards.
4176 Instruction *Transition;
4177 /// The sequence of instructions to be promoted.
4178 SmallVector<Instruction *, 4> InstsToBePromoted;
4179 /// Cost of combining a store and an extract.
4180 unsigned StoreExtractCombineCost;
4181 /// Instruction that will be combined with the transition.
4182 Instruction *CombineInst;
4183
4184 /// \brief The instruction that represents the current end of the transition.
4185 /// Since we are faking the promotion until we reach the end of the chain
4186 /// of computation, we need a way to get the current end of the transition.
4187 Instruction *getEndOfTransition() const {
4188 if (InstsToBePromoted.empty())
4189 return Transition;
4190 return InstsToBePromoted.back();
4191 }
4192
4193 /// \brief Return the index of the original value in the transition.
4194 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4195 /// c, is at index 0.
4196 unsigned getTransitionOriginalValueIdx() const {
4197 assert(isa<ExtractElementInst>(Transition) &&
4198 "Other kind of transitions are not supported yet");
4199 return 0;
4200 }
4201
4202 /// \brief Return the index of the index in the transition.
4203 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4204 /// is at index 1.
4205 unsigned getTransitionIdx() const {
4206 assert(isa<ExtractElementInst>(Transition) &&
4207 "Other kind of transitions are not supported yet");
4208 return 1;
4209 }
4210
4211 /// \brief Get the type of the transition.
4212 /// This is the type of the original value.
4213 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4214 /// transition is <2 x i32>.
4215 Type *getTransitionType() const {
4216 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4217 }
4218
4219 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4220 /// I.e., we have the following sequence:
4221 /// Def = Transition <ty1> a to <ty2>
4222 /// b = ToBePromoted <ty2> Def, ...
4223 /// =>
4224 /// b = ToBePromoted <ty1> a, ...
4225 /// Def = Transition <ty1> ToBePromoted to <ty2>
4226 void promoteImpl(Instruction *ToBePromoted);
4227
4228 /// \brief Check whether or not it is profitable to promote all the
4229 /// instructions enqueued to be promoted.
4230 bool isProfitableToPromote() {
4231 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4232 unsigned Index = isa<ConstantInt>(ValIdx)
4233 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4234 : -1;
4235 Type *PromotedType = getTransitionType();
4236
4237 StoreInst *ST = cast<StoreInst>(CombineInst);
4238 unsigned AS = ST->getPointerAddressSpace();
4239 unsigned Align = ST->getAlignment();
4240 // Check if this store is supported.
4241 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004242 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4243 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004244 // If this is not supported, there is no way we can combine
4245 // the extract with the store.
4246 return false;
4247 }
4248
4249 // The scalar chain of computation has to pay for the transition
4250 // scalar to vector.
4251 // The vector chain has to account for the combining cost.
4252 uint64_t ScalarCost =
4253 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4254 uint64_t VectorCost = StoreExtractCombineCost;
4255 for (const auto &Inst : InstsToBePromoted) {
4256 // Compute the cost.
4257 // By construction, all instructions being promoted are arithmetic ones.
4258 // Moreover, one argument is a constant that can be viewed as a splat
4259 // constant.
4260 Value *Arg0 = Inst->getOperand(0);
4261 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4262 isa<ConstantFP>(Arg0);
4263 TargetTransformInfo::OperandValueKind Arg0OVK =
4264 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4265 : TargetTransformInfo::OK_AnyValue;
4266 TargetTransformInfo::OperandValueKind Arg1OVK =
4267 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4268 : TargetTransformInfo::OK_AnyValue;
4269 ScalarCost += TTI.getArithmeticInstrCost(
4270 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4271 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4272 Arg0OVK, Arg1OVK);
4273 }
4274 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4275 << ScalarCost << "\nVector: " << VectorCost << '\n');
4276 return ScalarCost > VectorCost;
4277 }
4278
4279 /// \brief Generate a constant vector with \p Val with the same
4280 /// number of elements as the transition.
4281 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004282 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004283 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4284 /// otherwise we generate a vector with as many undef as possible:
4285 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4286 /// used at the index of the extract.
4287 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4288 unsigned ExtractIdx = UINT_MAX;
4289 if (!UseSplat) {
4290 // If we cannot determine where the constant must be, we have to
4291 // use a splat constant.
4292 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4293 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4294 ExtractIdx = CstVal->getSExtValue();
4295 else
4296 UseSplat = true;
4297 }
4298
4299 unsigned End = getTransitionType()->getVectorNumElements();
4300 if (UseSplat)
4301 return ConstantVector::getSplat(End, Val);
4302
4303 SmallVector<Constant *, 4> ConstVec;
4304 UndefValue *UndefVal = UndefValue::get(Val->getType());
4305 for (unsigned Idx = 0; Idx != End; ++Idx) {
4306 if (Idx == ExtractIdx)
4307 ConstVec.push_back(Val);
4308 else
4309 ConstVec.push_back(UndefVal);
4310 }
4311 return ConstantVector::get(ConstVec);
4312 }
4313
4314 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4315 /// in \p Use can trigger undefined behavior.
4316 static bool canCauseUndefinedBehavior(const Instruction *Use,
4317 unsigned OperandIdx) {
4318 // This is not safe to introduce undef when the operand is on
4319 // the right hand side of a division-like instruction.
4320 if (OperandIdx != 1)
4321 return false;
4322 switch (Use->getOpcode()) {
4323 default:
4324 return false;
4325 case Instruction::SDiv:
4326 case Instruction::UDiv:
4327 case Instruction::SRem:
4328 case Instruction::URem:
4329 return true;
4330 case Instruction::FDiv:
4331 case Instruction::FRem:
4332 return !Use->hasNoNaNs();
4333 }
4334 llvm_unreachable(nullptr);
4335 }
4336
4337public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004338 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4339 const TargetTransformInfo &TTI, Instruction *Transition,
4340 unsigned CombineCost)
4341 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004342 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4343 assert(Transition && "Do not know how to promote null");
4344 }
4345
4346 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4347 bool canPromote(const Instruction *ToBePromoted) const {
4348 // We could support CastInst too.
4349 return isa<BinaryOperator>(ToBePromoted);
4350 }
4351
4352 /// \brief Check if it is profitable to promote \p ToBePromoted
4353 /// by moving downward the transition through.
4354 bool shouldPromote(const Instruction *ToBePromoted) const {
4355 // Promote only if all the operands can be statically expanded.
4356 // Indeed, we do not want to introduce any new kind of transitions.
4357 for (const Use &U : ToBePromoted->operands()) {
4358 const Value *Val = U.get();
4359 if (Val == getEndOfTransition()) {
4360 // If the use is a division and the transition is on the rhs,
4361 // we cannot promote the operation, otherwise we may create a
4362 // division by zero.
4363 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4364 return false;
4365 continue;
4366 }
4367 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4368 !isa<ConstantFP>(Val))
4369 return false;
4370 }
4371 // Check that the resulting operation is legal.
4372 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4373 if (!ISDOpcode)
4374 return false;
4375 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004376 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004377 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004378 }
4379
4380 /// \brief Check whether or not \p Use can be combined
4381 /// with the transition.
4382 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4383 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4384
4385 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4386 void enqueueForPromotion(Instruction *ToBePromoted) {
4387 InstsToBePromoted.push_back(ToBePromoted);
4388 }
4389
4390 /// \brief Set the instruction that will be combined with the transition.
4391 void recordCombineInstruction(Instruction *ToBeCombined) {
4392 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4393 CombineInst = ToBeCombined;
4394 }
4395
4396 /// \brief Promote all the instructions enqueued for promotion if it is
4397 /// is profitable.
4398 /// \return True if the promotion happened, false otherwise.
4399 bool promote() {
4400 // Check if there is something to promote.
4401 // Right now, if we do not have anything to combine with,
4402 // we assume the promotion is not profitable.
4403 if (InstsToBePromoted.empty() || !CombineInst)
4404 return false;
4405
4406 // Check cost.
4407 if (!StressStoreExtract && !isProfitableToPromote())
4408 return false;
4409
4410 // Promote.
4411 for (auto &ToBePromoted : InstsToBePromoted)
4412 promoteImpl(ToBePromoted);
4413 InstsToBePromoted.clear();
4414 return true;
4415 }
4416};
4417} // End of anonymous namespace.
4418
4419void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4420 // At this point, we know that all the operands of ToBePromoted but Def
4421 // can be statically promoted.
4422 // For Def, we need to use its parameter in ToBePromoted:
4423 // b = ToBePromoted ty1 a
4424 // Def = Transition ty1 b to ty2
4425 // Move the transition down.
4426 // 1. Replace all uses of the promoted operation by the transition.
4427 // = ... b => = ... Def.
4428 assert(ToBePromoted->getType() == Transition->getType() &&
4429 "The type of the result of the transition does not match "
4430 "the final type");
4431 ToBePromoted->replaceAllUsesWith(Transition);
4432 // 2. Update the type of the uses.
4433 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4434 Type *TransitionTy = getTransitionType();
4435 ToBePromoted->mutateType(TransitionTy);
4436 // 3. Update all the operands of the promoted operation with promoted
4437 // operands.
4438 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4439 for (Use &U : ToBePromoted->operands()) {
4440 Value *Val = U.get();
4441 Value *NewVal = nullptr;
4442 if (Val == Transition)
4443 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4444 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4445 isa<ConstantFP>(Val)) {
4446 // Use a splat constant if it is not safe to use undef.
4447 NewVal = getConstantVector(
4448 cast<Constant>(Val),
4449 isa<UndefValue>(Val) ||
4450 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4451 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004452 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4453 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004454 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4455 }
4456 Transition->removeFromParent();
4457 Transition->insertAfter(ToBePromoted);
4458 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4459}
4460
4461/// Some targets can do store(extractelement) with one instruction.
4462/// Try to push the extractelement towards the stores when the target
4463/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004464bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004465 unsigned CombineCost = UINT_MAX;
4466 if (DisableStoreExtract || !TLI ||
4467 (!StressStoreExtract &&
4468 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4469 Inst->getOperand(1), CombineCost)))
4470 return false;
4471
4472 // At this point we know that Inst is a vector to scalar transition.
4473 // Try to move it down the def-use chain, until:
4474 // - We can combine the transition with its single use
4475 // => we got rid of the transition.
4476 // - We escape the current basic block
4477 // => we would need to check that we are moving it at a cheaper place and
4478 // we do not do that for now.
4479 BasicBlock *Parent = Inst->getParent();
4480 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00004481 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00004482 // If the transition has more than one use, assume this is not going to be
4483 // beneficial.
4484 while (Inst->hasOneUse()) {
4485 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4486 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4487
4488 if (ToBePromoted->getParent() != Parent) {
4489 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4490 << ToBePromoted->getParent()->getName()
4491 << ") than the transition (" << Parent->getName() << ").\n");
4492 return false;
4493 }
4494
4495 if (VPH.canCombine(ToBePromoted)) {
4496 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4497 << "will be combined with: " << *ToBePromoted << '\n');
4498 VPH.recordCombineInstruction(ToBePromoted);
4499 bool Changed = VPH.promote();
4500 NumStoreExtractExposed += Changed;
4501 return Changed;
4502 }
4503
4504 DEBUG(dbgs() << "Try promoting.\n");
4505 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4506 return false;
4507
4508 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4509
4510 VPH.enqueueForPromotion(ToBePromoted);
4511 Inst = ToBePromoted;
4512 }
4513 return false;
4514}
4515
Sanjay Patelfc580a62015-09-21 23:03:16 +00004516bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004517 // Bail out if we inserted the instruction to prevent optimizations from
4518 // stepping on each other's toes.
4519 if (InsertedInsts.count(I))
4520 return false;
4521
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004522 if (PHINode *P = dyn_cast<PHINode>(I)) {
4523 // It is possible for very late stage optimizations (such as SimplifyCFG)
4524 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4525 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00004526 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004527 P->replaceAllUsesWith(V);
4528 P->eraseFromParent();
4529 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004530 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004531 }
Chris Lattneree588de2011-01-15 07:29:01 +00004532 return false;
4533 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004534
Chris Lattneree588de2011-01-15 07:29:01 +00004535 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004536 // If the source of the cast is a constant, then this should have
4537 // already been constant folded. The only reason NOT to constant fold
4538 // it is if something (e.g. LSR) was careful to place the constant
4539 // evaluation in a block other than then one that uses it (e.g. to hoist
4540 // the address of globals out of a loop). If this is the case, we don't
4541 // want to forward-subst the cast.
4542 if (isa<Constant>(CI->getOperand(0)))
4543 return false;
4544
Mehdi Amini44ede332015-07-09 02:09:04 +00004545 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00004546 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004547
Chris Lattneree588de2011-01-15 07:29:01 +00004548 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004549 /// Sink a zext or sext into its user blocks if the target type doesn't
4550 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00004551 if (TLI &&
4552 TLI->getTypeAction(CI->getContext(),
4553 TLI->getValueType(*DL, CI->getType())) ==
4554 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004555 return SinkCast(CI);
4556 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004557 bool MadeChange = moveExtToFormExtLoad(I);
4558 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004559 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004560 }
Chris Lattneree588de2011-01-15 07:29:01 +00004561 return false;
4562 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004563
Chris Lattneree588de2011-01-15 07:29:01 +00004564 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004565 if (!TLI || !TLI->hasMultipleConditionRegisters())
4566 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004567
Chris Lattneree588de2011-01-15 07:29:01 +00004568 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004569 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004570 if (TLI) {
4571 unsigned AS = LI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00004572 return optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004573 }
Hans Wennborgf3254832012-10-30 11:23:25 +00004574 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004575 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004576
Chris Lattneree588de2011-01-15 07:29:01 +00004577 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004578 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004579 if (TLI) {
4580 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00004581 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004582 SI->getOperand(0)->getType(), AS);
4583 }
Chris Lattneree588de2011-01-15 07:29:01 +00004584 return false;
4585 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004586
Yi Jiangd069f632014-04-21 19:34:27 +00004587 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4588
4589 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4590 BinOp->getOpcode() == Instruction::LShr)) {
4591 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4592 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00004593 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00004594
4595 return false;
4596 }
4597
Chris Lattneree588de2011-01-15 07:29:01 +00004598 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004599 if (GEPI->hasAllZeroIndices()) {
4600 /// The GEP operand must be a pointer, so must its result -> BitCast
4601 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4602 GEPI->getName(), GEPI);
4603 GEPI->replaceAllUsesWith(NC);
4604 GEPI->eraseFromParent();
4605 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004606 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004607 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004608 }
Chris Lattneree588de2011-01-15 07:29:01 +00004609 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004610 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004611
Chris Lattneree588de2011-01-15 07:29:01 +00004612 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004613 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004614
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004615 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004616 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004617
Tim Northoveraeb8e062014-02-19 10:02:43 +00004618 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004619 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004620
Quentin Colombetc32615d2014-10-31 17:52:53 +00004621 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004622 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00004623
Chris Lattneree588de2011-01-15 07:29:01 +00004624 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004625}
4626
Chris Lattnerf2836d12007-03-31 04:06:36 +00004627// In this pass we look for GEP and cast instructions that are used
4628// across basic blocks and rewrite them to improve basic-block-at-a-time
4629// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004630bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004631 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004632 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004633
Chris Lattner7a277142011-01-15 07:14:54 +00004634 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004635 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004636 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004637 if (ModifiedDT)
4638 return true;
4639 }
Sanjay Patelfc580a62015-09-21 23:03:16 +00004640 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Benjamin Kramer455fa352012-11-23 19:17:06 +00004641
Chris Lattnerf2836d12007-03-31 04:06:36 +00004642 return MadeChange;
4643}
Devang Patel53771ba2011-08-18 00:50:51 +00004644
4645// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004646// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004647// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004648bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00004649 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004650 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004651 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004652 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004653 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00004654 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004655 // Leave dbg.values that refer to an alloca alone. These
4656 // instrinsics describe the address of a variable (= the alloca)
4657 // being taken. They should not be moved next to the alloca
4658 // (and to the beginning of the scope), but rather stay close to
4659 // where said address is used.
4660 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004661 PrevNonDbgInst = Insn;
4662 continue;
4663 }
4664
4665 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4666 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4667 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4668 DVI->removeFromParent();
4669 if (isa<PHINode>(VI))
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004670 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
Devang Patel53771ba2011-08-18 00:50:51 +00004671 else
4672 DVI->insertAfter(VI);
4673 MadeChange = true;
4674 ++NumDbgValueMoved;
4675 }
4676 }
4677 }
4678 return MadeChange;
4679}
Tim Northovercea0abb2014-03-29 08:22:29 +00004680
4681// If there is a sequence that branches based on comparing a single bit
4682// against zero that can be combined into a single instruction, and the
4683// target supports folding these into a single instruction, sink the
4684// mask and compare into the branch uses. Do this before OptimizeBlock ->
4685// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4686// searched for.
4687bool CodeGenPrepare::sinkAndCmp(Function &F) {
4688 if (!EnableAndCmpSinking)
4689 return false;
4690 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4691 return false;
4692 bool MadeChange = false;
4693 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004694 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00004695
4696 // Does this BB end with the following?
4697 // %andVal = and %val, #single-bit-set
4698 // %icmpVal = icmp %andResult, 0
4699 // br i1 %cmpVal label %dest1, label %dest2"
4700 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4701 if (!Brcc || !Brcc->isConditional())
4702 continue;
4703 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4704 if (!Cmp || Cmp->getParent() != BB)
4705 continue;
4706 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4707 if (!Zero || !Zero->isZero())
4708 continue;
4709 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4710 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4711 continue;
4712 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4713 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4714 continue;
4715 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4716
4717 // Push the "and; icmp" for any users that are conditional branches.
4718 // Since there can only be one branch use per BB, we don't need to keep
4719 // track of which BBs we insert into.
4720 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4721 UI != E; ) {
4722 Use &TheUse = *UI;
4723 // Find brcc use.
4724 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4725 ++UI;
4726 if (!BrccUser || !BrccUser->isConditional())
4727 continue;
4728 BasicBlock *UserBB = BrccUser->getParent();
4729 if (UserBB == BB) continue;
4730 DEBUG(dbgs() << "found Brcc use\n");
4731
4732 // Sink the "and; icmp" to use.
4733 MadeChange = true;
4734 BinaryOperator *NewAnd =
4735 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4736 BrccUser);
4737 CmpInst *NewCmp =
4738 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4739 "", BrccUser);
4740 TheUse = NewCmp;
4741 ++NumAndCmpsMoved;
4742 DEBUG(BrccUser->getParent()->dump());
4743 }
4744 }
4745 return MadeChange;
4746}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004747
Juergen Ributzka194350a2014-12-09 17:32:12 +00004748/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4749/// success, or returns false if no or invalid metadata was found.
4750static bool extractBranchMetadata(BranchInst *BI,
4751 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4752 assert(BI->isConditional() &&
4753 "Looking for probabilities on unconditional branch?");
4754 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4755 if (!ProfileData || ProfileData->getNumOperands() != 3)
4756 return false;
4757
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004758 const auto *CITrue =
4759 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4760 const auto *CIFalse =
4761 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004762 if (!CITrue || !CIFalse)
4763 return false;
4764
4765 ProbTrue = CITrue->getValue().getZExtValue();
4766 ProbFalse = CIFalse->getValue().getZExtValue();
4767
4768 return true;
4769}
4770
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004771/// \brief Scale down both weights to fit into uint32_t.
4772static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4773 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4774 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4775 NewTrue = NewTrue / Scale;
4776 NewFalse = NewFalse / Scale;
4777}
4778
4779/// \brief Some targets prefer to split a conditional branch like:
4780/// \code
4781/// %0 = icmp ne i32 %a, 0
4782/// %1 = icmp ne i32 %b, 0
4783/// %or.cond = or i1 %0, %1
4784/// br i1 %or.cond, label %TrueBB, label %FalseBB
4785/// \endcode
4786/// into multiple branch instructions like:
4787/// \code
4788/// bb1:
4789/// %0 = icmp ne i32 %a, 0
4790/// br i1 %0, label %TrueBB, label %bb2
4791/// bb2:
4792/// %1 = icmp ne i32 %b, 0
4793/// br i1 %1, label %TrueBB, label %FalseBB
4794/// \endcode
4795/// This usually allows instruction selection to do even further optimizations
4796/// and combine the compare with the branch instruction. Currently this is
4797/// applied for targets which have "cheap" jump instructions.
4798///
4799/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4800///
4801bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00004802 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004803 return false;
4804
4805 bool MadeChange = false;
4806 for (auto &BB : F) {
4807 // Does this BB end with the following?
4808 // %cond1 = icmp|fcmp|binary instruction ...
4809 // %cond2 = icmp|fcmp|binary instruction ...
4810 // %cond.or = or|and i1 %cond1, cond2
4811 // br i1 %cond.or label %dest1, label %dest2"
4812 BinaryOperator *LogicOp;
4813 BasicBlock *TBB, *FBB;
4814 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4815 continue;
4816
Sanjay Patel42574202015-09-02 19:23:23 +00004817 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4818 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
4819 continue;
4820
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004821 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004822 Value *Cond1, *Cond2;
4823 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4824 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004825 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004826 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4827 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004828 Opc = Instruction::Or;
4829 else
4830 continue;
4831
4832 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4833 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4834 continue;
4835
4836 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4837
4838 // Create a new BB.
4839 auto *InsertBefore = std::next(Function::iterator(BB))
4840 .getNodePtrUnchecked();
4841 auto TmpBB = BasicBlock::Create(BB.getContext(),
4842 BB.getName() + ".cond.split",
4843 BB.getParent(), InsertBefore);
4844
4845 // Update original basic block by using the first condition directly by the
4846 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004847 Br1->setCondition(Cond1);
4848 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004849
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004850 // Depending on the conditon we have to either replace the true or the false
4851 // successor of the original branch instruction.
4852 if (Opc == Instruction::And)
4853 Br1->setSuccessor(0, TmpBB);
4854 else
4855 Br1->setSuccessor(1, TmpBB);
4856
4857 // Fill in the new basic block.
4858 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004859 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4860 I->removeFromParent();
4861 I->insertBefore(Br2);
4862 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004863
4864 // Update PHI nodes in both successors. The original BB needs to be
4865 // replaced in one succesor's PHI nodes, because the branch comes now from
4866 // the newly generated BB (NewBB). In the other successor we need to add one
4867 // incoming edge to the PHI nodes, because both branch instructions target
4868 // now the same successor. Depending on the original branch condition
4869 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4870 // we perfrom the correct update for the PHI nodes.
4871 // This doesn't change the successor order of the just created branch
4872 // instruction (or any other instruction).
4873 if (Opc == Instruction::Or)
4874 std::swap(TBB, FBB);
4875
4876 // Replace the old BB with the new BB.
4877 for (auto &I : *TBB) {
4878 PHINode *PN = dyn_cast<PHINode>(&I);
4879 if (!PN)
4880 break;
4881 int i;
4882 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4883 PN->setIncomingBlock(i, TmpBB);
4884 }
4885
4886 // Add another incoming edge form the new BB.
4887 for (auto &I : *FBB) {
4888 PHINode *PN = dyn_cast<PHINode>(&I);
4889 if (!PN)
4890 break;
4891 auto *Val = PN->getIncomingValueForBlock(&BB);
4892 PN->addIncoming(Val, TmpBB);
4893 }
4894
4895 // Update the branch weights (from SelectionDAGBuilder::
4896 // FindMergedConditions).
4897 if (Opc == Instruction::Or) {
4898 // Codegen X | Y as:
4899 // BB1:
4900 // jmp_if_X TBB
4901 // jmp TmpBB
4902 // TmpBB:
4903 // jmp_if_Y TBB
4904 // jmp FBB
4905 //
4906
4907 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4908 // The requirement is that
4909 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4910 // = TrueProb for orignal BB.
4911 // Assuming the orignal weights are A and B, one choice is to set BB1's
4912 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4913 // assumes that
4914 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4915 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4916 // TmpBB, but the math is more complicated.
4917 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004918 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004919 uint64_t NewTrueWeight = TrueWeight;
4920 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4921 scaleWeights(NewTrueWeight, NewFalseWeight);
4922 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4923 .createBranchWeights(TrueWeight, FalseWeight));
4924
4925 NewTrueWeight = TrueWeight;
4926 NewFalseWeight = 2 * FalseWeight;
4927 scaleWeights(NewTrueWeight, NewFalseWeight);
4928 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4929 .createBranchWeights(TrueWeight, FalseWeight));
4930 }
4931 } else {
4932 // Codegen X & Y as:
4933 // BB1:
4934 // jmp_if_X TmpBB
4935 // jmp FBB
4936 // TmpBB:
4937 // jmp_if_Y TBB
4938 // jmp FBB
4939 //
4940 // This requires creation of TmpBB after CurBB.
4941
4942 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4943 // The requirement is that
4944 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4945 // = FalseProb for orignal BB.
4946 // Assuming the orignal weights are A and B, one choice is to set BB1's
4947 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4948 // assumes that
4949 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4950 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004951 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004952 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4953 uint64_t NewFalseWeight = FalseWeight;
4954 scaleWeights(NewTrueWeight, NewFalseWeight);
4955 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4956 .createBranchWeights(TrueWeight, FalseWeight));
4957
4958 NewTrueWeight = 2 * TrueWeight;
4959 NewFalseWeight = FalseWeight;
4960 scaleWeights(NewTrueWeight, NewFalseWeight);
4961 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4962 .createBranchWeights(TrueWeight, FalseWeight));
4963 }
4964 }
4965
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004966 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00004967 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004968 ModifiedDT = true;
4969
4970 MadeChange = true;
4971
4972 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4973 TmpBB->dump());
4974 }
4975 return MadeChange;
4976}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004977
4978void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00004979 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004980 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
4981}