blob: d0c8fb95d4845300c0862093f4c20652a319fd66 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000023#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InlineAsm.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000034#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000035#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000036#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000038#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000039#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000040#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000041#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000044#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000047#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000050using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000051using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000052
Chandler Carruth1b9dde02014-04-22 02:02:50 +000053#define DEBUG_TYPE "codegenprepare"
54
Cameron Zwarichced753f2011-01-05 17:27:27 +000055STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000056STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
57STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000058STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
59 "sunken Cmps");
60STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
61 "of sunken Casts");
62STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
63 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000064STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
65STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
66STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000067STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000068STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000069STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000070STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000071
Cameron Zwarich338d3622011-03-11 21:52:04 +000072static cl::opt<bool> DisableBranchOpts(
73 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
74 cl::desc("Disable branch optimizations in CodeGenPrepare"));
75
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000076static cl::opt<bool>
77 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
78 cl::desc("Disable GC optimizations in CodeGenPrepare"));
79
Benjamin Kramer3d38c172012-05-06 14:25:16 +000080static cl::opt<bool> DisableSelectToBranch(
81 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
82 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000083
Hal Finkelc3998302014-04-12 00:59:48 +000084static cl::opt<bool> AddrSinkUsingGEPs(
85 "addr-sink-using-gep", cl::Hidden, cl::init(false),
86 cl::desc("Address sinking in CGP using GEPs."));
87
Tim Northovercea0abb2014-03-29 08:22:29 +000088static cl::opt<bool> EnableAndCmpSinking(
89 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
90 cl::desc("Enable sinkinig and/cmp into branches."));
91
Quentin Colombetc32615d2014-10-31 17:52:53 +000092static cl::opt<bool> DisableStoreExtract(
93 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
94 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
95
96static cl::opt<bool> StressStoreExtract(
97 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
98 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
99
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000100static cl::opt<bool> DisableExtLdPromotion(
101 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
103 "CodeGenPrepare"));
104
105static cl::opt<bool> StressExtLdPromotion(
106 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
107 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
108 "optimization in CodeGenPrepare"));
109
Eric Christopherc1ea1492008-09-24 05:32:41 +0000110namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000111typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000112typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000113typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000114class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000115
Chris Lattner2dd09db2009-09-02 06:11:42 +0000116 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000117 /// TLI - Keep a pointer of a TargetLowering to consult for determining
118 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000119 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000120 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000121 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000122 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000123
Chris Lattner7a277142011-01-15 07:14:54 +0000124 /// CurInstIterator - As we scan instructions optimizing them, this is the
125 /// next instruction to optimize. Xforms that can invalidate this should
126 /// update it.
127 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000128
Evan Cheng0663f232011-03-21 01:19:09 +0000129 /// Keeps track of non-local addresses that have been sunk into a block.
130 /// This allows us to avoid inserting duplicate code for blocks with
131 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000132 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000133
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000134 /// Keeps track of all instructions inserted for the current function.
135 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000136 /// Keeps track of the type of the related instruction before their
137 /// promotion for the current function.
138 InstrToOrigTy PromotedInsts;
139
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000140 /// ModifiedDT - If CFG is modified in anyway.
Devang Patel8f606d72011-03-24 15:35:25 +0000141 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000142
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000143 /// OptSize - True if optimizing for size.
144 bool OptSize;
145
Mehdi Amini4fe37982015-07-07 18:45:17 +0000146 /// DataLayout for the Function being processed.
147 const DataLayout *DL;
148
Chris Lattnerf2836d12007-03-31 04:06:36 +0000149 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000150 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000151 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000152 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000153 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
154 }
Craig Topper4584cd52014-03-07 09:26:03 +0000155 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000156
Craig Topper4584cd52014-03-07 09:26:03 +0000157 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000158
Craig Topper4584cd52014-03-07 09:26:03 +0000159 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000160 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000161 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000162 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000163 }
164
Chris Lattnerf2836d12007-03-31 04:06:36 +0000165 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000166 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000167 bool EliminateMostlyEmptyBlocks(Function &F);
168 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
169 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000170 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
171 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000172 bool OptimizeMemoryInst(Instruction *I, Value *Addr,
173 Type *AccessTy, unsigned AS);
Chris Lattner7a277142011-01-15 07:14:54 +0000174 bool OptimizeInlineAsmInst(CallInst *CS);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000175 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000176 bool MoveExtToFormExtLoad(Instruction *&I);
Evan Chengd3d80172007-12-05 23:58:20 +0000177 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000178 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000179 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000180 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000181 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000182 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000183 bool sinkAndCmp(Function &F);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000184 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
185 Instruction *&Inst,
186 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000187 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000188 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000189 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000190 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000191 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000192}
Devang Patel09f162c2007-05-01 21:15:47 +0000193
Devang Patel8c78a0b2007-05-03 01:11:54 +0000194char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000195INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
196 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000197
Bill Wendling7a639ea2013-06-19 21:07:11 +0000198FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
199 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000200}
201
Chris Lattnerf2836d12007-03-31 04:06:36 +0000202bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000203 if (skipOptnoneFunction(F))
204 return false;
205
Mehdi Amini4fe37982015-07-07 18:45:17 +0000206 DL = &F.getParent()->getDataLayout();
207
Chris Lattnerf2836d12007-03-31 04:06:36 +0000208 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000209 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000210 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000211 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000212
Devang Patel8f606d72011-03-24 15:35:25 +0000213 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000214 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000215 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000216 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000217 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000218 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000219
Preston Gurdcdf540d2012-09-04 18:22:17 +0000220 /// This optimization identifies DIV instructions that can be
221 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000222 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000223 const DenseMap<unsigned int, unsigned int> &BypassWidths =
224 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000225 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000226 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000227 }
228
229 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000230 // unconditional branch.
231 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000232
Devang Patel53771ba2011-08-18 00:50:51 +0000233 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000234 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000235 // find a node corresponding to the value.
236 EverMadeChange |= PlaceDbgValues(F);
237
Tim Northovercea0abb2014-03-29 08:22:29 +0000238 // If there is a mask, compare against zero, and branch that can be combined
239 // into a single target instruction, push the mask and compare into branch
240 // users. Do this before OptimizeBlock -> OptimizeInst ->
241 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000242 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000243 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000244 EverMadeChange |= splitBranchCondition(F);
245 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000246
Chris Lattnerc3748562007-04-02 01:35:34 +0000247 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000248 while (MadeChange) {
249 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000250 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000251 BasicBlock *BB = I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000252 bool ModifiedDTOnIteration = false;
253 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000254
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000255 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000256 if (ModifiedDTOnIteration)
257 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000258 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000259 EverMadeChange |= MadeChange;
260 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000261
262 SunkAddrs.clear();
263
Cameron Zwarich338d3622011-03-11 21:52:04 +0000264 if (!DisableBranchOpts) {
265 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000266 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000267 for (BasicBlock &BB : F) {
268 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
269 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000270 if (!MadeChange) continue;
271
272 for (SmallVectorImpl<BasicBlock*>::iterator
273 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
274 if (pred_begin(*II) == pred_end(*II))
275 WorkList.insert(*II);
276 }
277
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000278 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000279 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000280 while (!WorkList.empty()) {
281 BasicBlock *BB = *WorkList.begin();
282 WorkList.erase(BB);
283 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
284
285 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000286
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000287 for (SmallVectorImpl<BasicBlock*>::iterator
288 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
289 if (pred_begin(*II) == pred_end(*II))
290 WorkList.insert(*II);
291 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000292
Nadav Rotem70409992012-08-14 05:19:07 +0000293 // Merge pairs of basic blocks with unconditional branches, connected by
294 // a single edge.
295 if (EverMadeChange || MadeChange)
296 MadeChange |= EliminateFallThrough(F);
297
Cameron Zwarich338d3622011-03-11 21:52:04 +0000298 EverMadeChange |= MadeChange;
299 }
300
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000301 if (!DisableGCOpts) {
302 SmallVector<Instruction *, 2> Statepoints;
303 for (BasicBlock &BB : F)
304 for (Instruction &I : BB)
305 if (isStatepoint(I))
306 Statepoints.push_back(&I);
307 for (auto &I : Statepoints)
308 EverMadeChange |= simplifyOffsetableRelocate(*I);
309 }
310
Chris Lattnerf2836d12007-03-31 04:06:36 +0000311 return EverMadeChange;
312}
313
Nadav Rotem70409992012-08-14 05:19:07 +0000314/// EliminateFallThrough - Merge basic blocks which are connected
315/// by a single edge, where one of the basic blocks has a single successor
316/// pointing to the other basic block, which has a single predecessor.
317bool CodeGenPrepare::EliminateFallThrough(Function &F) {
318 bool Changed = false;
319 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000320 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000321 BasicBlock *BB = I++;
322 // If the destination block has a single pred, then this is a trivial
323 // edge, just collapse it.
324 BasicBlock *SinglePred = BB->getSinglePredecessor();
325
Evan Cheng64a223a2012-09-28 23:58:57 +0000326 // Don't merge if BB's address is taken.
327 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000328
329 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
330 if (Term && !Term->isConditional()) {
331 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000332 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000333 // Remember if SinglePred was the entry block of the function.
334 // If so, we will need to move BB back to the entry position.
335 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000336 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000337
338 if (isEntry && BB != &BB->getParent()->getEntryBlock())
339 BB->moveBefore(&BB->getParent()->getEntryBlock());
340
341 // We have erased a block. Update the iterator.
342 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000343 }
344 }
345 return Changed;
346}
347
Dale Johannesen4026b042009-03-27 01:13:37 +0000348/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
349/// debug info directives, and an unconditional branch. Passes before isel
350/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
351/// isel. Start by eliminating these blocks so we can split them the way we
352/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000353bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
354 bool MadeChange = false;
355 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000356 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000357 BasicBlock *BB = I++;
358
359 // If this block doesn't end with an uncond branch, ignore it.
360 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
361 if (!BI || !BI->isUnconditional())
362 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000363
Dale Johannesen4026b042009-03-27 01:13:37 +0000364 // If the instruction before the branch (skipping debug info) isn't a phi
365 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000366 BasicBlock::iterator BBI = BI;
367 if (BBI != BB->begin()) {
368 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000369 while (isa<DbgInfoIntrinsic>(BBI)) {
370 if (BBI == BB->begin())
371 break;
372 --BBI;
373 }
374 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
375 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000376 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000377
Chris Lattnerc3748562007-04-02 01:35:34 +0000378 // Do not break infinite loops.
379 BasicBlock *DestBB = BI->getSuccessor(0);
380 if (DestBB == BB)
381 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000382
Chris Lattnerc3748562007-04-02 01:35:34 +0000383 if (!CanMergeBlocks(BB, DestBB))
384 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000385
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 EliminateMostlyEmptyBlock(BB);
387 MadeChange = true;
388 }
389 return MadeChange;
390}
391
392/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
393/// single uncond branch between them, and BB contains no other non-phi
394/// instructions.
395bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
396 const BasicBlock *DestBB) const {
397 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
398 // the successor. If there are more complex condition (e.g. preheaders),
399 // don't mess around with them.
400 BasicBlock::const_iterator BBI = BB->begin();
401 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000402 for (const User *U : PN->users()) {
403 const Instruction *UI = cast<Instruction>(U);
404 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000405 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000406 // If User is inside DestBB block and it is a PHINode then check
407 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000408 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000409 if (UI->getParent() == DestBB) {
410 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000411 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
412 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
413 if (Insn && Insn->getParent() == BB &&
414 Insn->getParent() != UPN->getIncomingBlock(I))
415 return false;
416 }
417 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000418 }
419 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000420
Chris Lattnerc3748562007-04-02 01:35:34 +0000421 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
422 // and DestBB may have conflicting incoming values for the block. If so, we
423 // can't merge the block.
424 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
425 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000426
Chris Lattnerc3748562007-04-02 01:35:34 +0000427 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000428 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000429 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
430 // It is faster to get preds from a PHI than with pred_iterator.
431 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
432 BBPreds.insert(BBPN->getIncomingBlock(i));
433 } else {
434 BBPreds.insert(pred_begin(BB), pred_end(BB));
435 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000436
Chris Lattnerc3748562007-04-02 01:35:34 +0000437 // Walk the preds of DestBB.
438 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
439 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
440 if (BBPreds.count(Pred)) { // Common predecessor?
441 BBI = DestBB->begin();
442 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
443 const Value *V1 = PN->getIncomingValueForBlock(Pred);
444 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000445
Chris Lattnerc3748562007-04-02 01:35:34 +0000446 // If V2 is a phi node in BB, look up what the mapped value will be.
447 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
448 if (V2PN->getParent() == BB)
449 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000450
Chris Lattnerc3748562007-04-02 01:35:34 +0000451 // If there is a conflict, bail out.
452 if (V1 != V2) return false;
453 }
454 }
455 }
456
457 return true;
458}
459
460
461/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
462/// an unconditional branch in it.
463void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
464 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
465 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000466
David Greene74e2d492010-01-05 01:27:11 +0000467 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000468
Chris Lattnerc3748562007-04-02 01:35:34 +0000469 // If the destination block has a single pred, then this is a trivial edge,
470 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000471 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000472 if (SinglePred != DestBB) {
473 // Remember if SinglePred was the entry block of the function. If so, we
474 // will need to move BB back to the entry position.
475 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000476 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000477
Chris Lattner8a172da2008-11-28 19:54:49 +0000478 if (isEntry && BB != &BB->getParent()->getEntryBlock())
479 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000480
David Greene74e2d492010-01-05 01:27:11 +0000481 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000482 return;
483 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000484 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000485
Chris Lattnerc3748562007-04-02 01:35:34 +0000486 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
487 // to handle the new incoming edges it is about to have.
488 PHINode *PN;
489 for (BasicBlock::iterator BBI = DestBB->begin();
490 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
491 // Remove the incoming value for BB, and remember it.
492 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000493
Chris Lattnerc3748562007-04-02 01:35:34 +0000494 // Two options: either the InVal is a phi node defined in BB or it is some
495 // value that dominates BB.
496 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
497 if (InValPhi && InValPhi->getParent() == BB) {
498 // Add all of the input values of the input PHI as inputs of this phi.
499 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
500 PN->addIncoming(InValPhi->getIncomingValue(i),
501 InValPhi->getIncomingBlock(i));
502 } else {
503 // Otherwise, add one instance of the dominating value for each edge that
504 // we will be adding.
505 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
506 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
507 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
508 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000509 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
510 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000511 }
512 }
513 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000514
Chris Lattnerc3748562007-04-02 01:35:34 +0000515 // The PHIs are now updated, change everything that refers to BB to use
516 // DestBB and remove BB.
517 BB->replaceAllUsesWith(DestBB);
518 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000519 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000520
David Greene74e2d492010-01-05 01:27:11 +0000521 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000522}
523
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000524// Computes a map of base pointer relocation instructions to corresponding
525// derived pointer relocation instructions given a vector of all relocate calls
526static void computeBaseDerivedRelocateMap(
527 const SmallVectorImpl<User *> &AllRelocateCalls,
528 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
529 RelocateInstMap) {
530 // Collect information in two maps: one primarily for locating the base object
531 // while filling the second map; the second map is the final structure holding
532 // a mapping between Base and corresponding Derived relocate calls
533 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
534 for (auto &U : AllRelocateCalls) {
535 GCRelocateOperands ThisRelocate(U);
536 IntrinsicInst *I = cast<IntrinsicInst>(U);
Sanjoy Das499d7032015-05-06 02:36:26 +0000537 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
538 ThisRelocate.getDerivedPtrIndex());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000539 RelocateIdxMap.insert(std::make_pair(K, I));
540 }
541 for (auto &Item : RelocateIdxMap) {
542 std::pair<unsigned, unsigned> Key = Item.first;
543 if (Key.first == Key.second)
544 // Base relocation: nothing to insert
545 continue;
546
547 IntrinsicInst *I = Item.second;
548 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000549
550 // We're iterating over RelocateIdxMap so we cannot modify it.
551 auto MaybeBase = RelocateIdxMap.find(BaseKey);
552 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000553 // TODO: We might want to insert a new base object relocate and gep off
554 // that, if there are enough derived object relocates.
555 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000556
557 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000558 }
559}
560
561// Accepts a GEP and extracts the operands into a vector provided they're all
562// small integer constants
563static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
564 SmallVectorImpl<Value *> &OffsetV) {
565 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
566 // Only accept small constant integer operands
567 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
568 if (!Op || Op->getZExtValue() > 20)
569 return false;
570 }
571
572 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
573 OffsetV.push_back(GEP->getOperand(i));
574 return true;
575}
576
577// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
578// replace, computes a replacement, and affects it.
579static bool
580simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
581 const SmallVectorImpl<IntrinsicInst *> &Targets) {
582 bool MadeChange = false;
583 for (auto &ToReplace : Targets) {
584 GCRelocateOperands MasterRelocate(RelocatedBase);
585 GCRelocateOperands ThisRelocate(ToReplace);
586
Sanjoy Das499d7032015-05-06 02:36:26 +0000587 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000588 "Not relocating a derived object of the original base object");
Sanjoy Das499d7032015-05-06 02:36:26 +0000589 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000590 // A duplicate relocate call. TODO: coalesce duplicates.
591 continue;
592 }
593
Sanjoy Das499d7032015-05-06 02:36:26 +0000594 Value *Base = ThisRelocate.getBasePtr();
595 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000596 if (!Derived || Derived->getPointerOperand() != Base)
597 continue;
598
599 SmallVector<Value *, 2> OffsetV;
600 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
601 continue;
602
603 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000604 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
605
606 // Insert after RelocatedBase
607 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000608 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000609
610 // If gc_relocate does not match the actual type, cast it to the right type.
611 // In theory, there must be a bitcast after gc_relocate if the type does not
612 // match, and we should reuse it to get the derived pointer. But it could be
613 // cases like this:
614 // bb1:
615 // ...
616 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
617 // br label %merge
618 //
619 // bb2:
620 // ...
621 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
622 // br label %merge
623 //
624 // merge:
625 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
626 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
627 //
628 // In this case, we can not find the bitcast any more. So we insert a new bitcast
629 // no matter there is already one or not. In this way, we can handle all cases, and
630 // the extra bitcast should be optimized away in later passes.
631 Instruction *ActualRelocatedBase = RelocatedBase;
632 if (RelocatedBase->getType() != Base->getType()) {
633 ActualRelocatedBase =
634 cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000635 }
David Blaikie68d535c2015-03-24 22:38:16 +0000636 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000637 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000638 Instruction *ReplacementInst = cast<Instruction>(Replacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000639 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000640 // If the newly generated derived pointer's type does not match the original derived
641 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
642 Instruction *ActualReplacement = ReplacementInst;
643 if (ReplacementInst->getType() != ToReplace->getType()) {
644 ActualReplacement =
645 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000646 }
647 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000648 ToReplace->eraseFromParent();
649
650 MadeChange = true;
651 }
652 return MadeChange;
653}
654
655// Turns this:
656//
657// %base = ...
658// %ptr = gep %base + 15
659// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
660// %base' = relocate(%tok, i32 4, i32 4)
661// %ptr' = relocate(%tok, i32 4, i32 5)
662// %val = load %ptr'
663//
664// into this:
665//
666// %base = ...
667// %ptr = gep %base + 15
668// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
669// %base' = gc.relocate(%tok, i32 4, i32 4)
670// %ptr' = gep %base' + 15
671// %val = load %ptr'
672bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
673 bool MadeChange = false;
674 SmallVector<User *, 2> AllRelocateCalls;
675
676 for (auto *U : I.users())
677 if (isGCRelocate(dyn_cast<Instruction>(U)))
678 // Collect all the relocate calls associated with a statepoint
679 AllRelocateCalls.push_back(U);
680
681 // We need atleast one base pointer relocation + one derived pointer
682 // relocation to mangle
683 if (AllRelocateCalls.size() < 2)
684 return false;
685
686 // RelocateInstMap is a mapping from the base relocate instruction to the
687 // corresponding derived relocate instructions
688 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
689 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
690 if (RelocateInstMap.empty())
691 return false;
692
693 for (auto &Item : RelocateInstMap)
694 // Item.first is the RelocatedBase to offset against
695 // Item.second is the vector of Targets to replace
696 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
697 return MadeChange;
698}
699
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000700/// SinkCast - Sink the specified cast instruction into its user blocks
701static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000702 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000703
Chris Lattnerf2836d12007-03-31 04:06:36 +0000704 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000705 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000706
Chris Lattnerf2836d12007-03-31 04:06:36 +0000707 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000708 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000709 UI != E; ) {
710 Use &TheUse = UI.getUse();
711 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000712
Chris Lattnerf2836d12007-03-31 04:06:36 +0000713 // Figure out which BB this cast is used in. For PHI's this is the
714 // appropriate predecessor block.
715 BasicBlock *UserBB = User->getParent();
716 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000717 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000718 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000719
Chris Lattnerf2836d12007-03-31 04:06:36 +0000720 // Preincrement use iterator so we don't invalidate it.
721 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000722
Chris Lattnerf2836d12007-03-31 04:06:36 +0000723 // If this user is in the same block as the cast, don't change the cast.
724 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000725
Chris Lattnerf2836d12007-03-31 04:06:36 +0000726 // If we have already inserted a cast into this block, use it.
727 CastInst *&InsertedCast = InsertedCasts[UserBB];
728
729 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000730 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000731 InsertedCast =
732 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000733 InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000734 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000735
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000736 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000737 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000738 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000739 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000740 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000741
Chris Lattnerf2836d12007-03-31 04:06:36 +0000742 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000743 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000744 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000745 MadeChange = true;
746 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000747
Chris Lattnerf2836d12007-03-31 04:06:36 +0000748 return MadeChange;
749}
750
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000751/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
752/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
753/// sink it into user blocks to reduce the number of virtual
754/// registers that must be created and coalesced.
755///
756/// Return true if any changes are made.
757///
Mehdi Amini44ede332015-07-09 02:09:04 +0000758static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
759 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000760 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000761 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
762 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000763
764 // This is an fp<->int conversion?
765 if (SrcVT.isInteger() != DstVT.isInteger())
766 return false;
767
768 // If this is an extension, it will be a zero or sign extension, which
769 // isn't a noop.
770 if (SrcVT.bitsLT(DstVT)) return false;
771
772 // If these values will be promoted, find out what they will be promoted
773 // to. This helps us consider truncates on PPC as noop copies when they
774 // are.
775 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
776 TargetLowering::TypePromoteInteger)
777 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
778 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
779 TargetLowering::TypePromoteInteger)
780 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
781
782 // If, after promotion, these are the same types, this is a noop copy.
783 if (SrcVT != DstVT)
784 return false;
785
786 return SinkCast(CI);
787}
788
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000789/// CombineUAddWithOverflow - try to combine CI into a call to the
790/// llvm.uadd.with.overflow intrinsic if possible.
791///
792/// Return true if any changes were made.
793static bool CombineUAddWithOverflow(CmpInst *CI) {
794 Value *A, *B;
795 Instruction *AddI;
796 if (!match(CI,
797 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
798 return false;
799
800 Type *Ty = AddI->getType();
801 if (!isa<IntegerType>(Ty))
802 return false;
803
804 // We don't want to move around uses of condition values this late, so we we
805 // check if it is legal to create the call to the intrinsic in the basic
806 // block containing the icmp:
807
808 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
809 return false;
810
811#ifndef NDEBUG
812 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
813 // for now:
814 if (AddI->hasOneUse())
815 assert(*AddI->user_begin() == CI && "expected!");
816#endif
817
818 Module *M = CI->getParent()->getParent()->getParent();
819 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
820
821 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
822
823 auto *UAddWithOverflow =
824 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
825 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
826 auto *Overflow =
827 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
828
829 CI->replaceAllUsesWith(Overflow);
830 AddI->replaceAllUsesWith(UAdd);
831 CI->eraseFromParent();
832 AddI->eraseFromParent();
833 return true;
834}
835
836/// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000837/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000838/// a clear win except on targets with multiple condition code registers
839/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000840///
841/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000842static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000843 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000844
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000845 /// InsertedCmp - Only insert a cmp in each block once.
846 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000847
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000848 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000849 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000850 UI != E; ) {
851 Use &TheUse = UI.getUse();
852 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000853
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000854 // Preincrement use iterator so we don't invalidate it.
855 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000856
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000857 // Don't bother for PHI nodes.
858 if (isa<PHINode>(User))
859 continue;
860
861 // Figure out which BB this cmp is used in.
862 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000863
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000864 // If this user is in the same block as the cmp, don't change the cmp.
865 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000866
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000867 // If we have already inserted a cmp into this block, use it.
868 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
869
870 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000871 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000872 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000873 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000874 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000875 CI->getOperand(1), "", InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000876 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000877
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000878 // Replace a use of the cmp with a use of the new cmp.
879 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000880 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000881 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000882 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000883
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000884 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000885 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000886 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000887 MadeChange = true;
888 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000889
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000890 return MadeChange;
891}
892
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000893static bool OptimizeCmpExpression(CmpInst *CI) {
894 if (SinkCmpExpression(CI))
895 return true;
896
897 if (CombineUAddWithOverflow(CI))
898 return true;
899
900 return false;
901}
902
Yi Jiangd069f632014-04-21 19:34:27 +0000903/// isExtractBitsCandidateUse - Check if the candidates could
904/// be combined with shift instruction, which includes:
905/// 1. Truncate instruction
906/// 2. And instruction and the imm is a mask of the low bits:
907/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000908static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000909 if (!isa<TruncInst>(User)) {
910 if (User->getOpcode() != Instruction::And ||
911 !isa<ConstantInt>(User->getOperand(1)))
912 return false;
913
Quentin Colombetd4f44692014-04-22 01:20:34 +0000914 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000915
Quentin Colombetd4f44692014-04-22 01:20:34 +0000916 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000917 return false;
918 }
919 return true;
920}
921
922/// SinkShiftAndTruncate - sink both shift and truncate instruction
923/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000924static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000925SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
926 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000927 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000928 BasicBlock *UserBB = User->getParent();
929 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
930 TruncInst *TruncI = dyn_cast<TruncInst>(User);
931 bool MadeChange = false;
932
933 for (Value::user_iterator TruncUI = TruncI->user_begin(),
934 TruncE = TruncI->user_end();
935 TruncUI != TruncE;) {
936
937 Use &TruncTheUse = TruncUI.getUse();
938 Instruction *TruncUser = cast<Instruction>(*TruncUI);
939 // Preincrement use iterator so we don't invalidate it.
940
941 ++TruncUI;
942
943 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
944 if (!ISDOpcode)
945 continue;
946
Tim Northovere2239ff2014-07-29 10:20:22 +0000947 // If the use is actually a legal node, there will not be an
948 // implicit truncate.
949 // FIXME: always querying the result type is just an
950 // approximation; some nodes' legality is determined by the
951 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000952 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000953 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000954 continue;
955
956 // Don't bother for PHI nodes.
957 if (isa<PHINode>(TruncUser))
958 continue;
959
960 BasicBlock *TruncUserBB = TruncUser->getParent();
961
962 if (UserBB == TruncUserBB)
963 continue;
964
965 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
966 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
967
968 if (!InsertedShift && !InsertedTrunc) {
969 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
970 // Sink the shift
971 if (ShiftI->getOpcode() == Instruction::AShr)
972 InsertedShift =
973 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
974 else
975 InsertedShift =
976 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
977
978 // Sink the trunc
979 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
980 TruncInsertPt++;
981
982 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
983 TruncI->getType(), "", TruncInsertPt);
984
985 MadeChange = true;
986
987 TruncTheUse = InsertedTrunc;
988 }
989 }
990 return MadeChange;
991}
992
993/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
994/// the uses could potentially be combined with this shift instruction and
995/// generate BitExtract instruction. It will only be applied if the architecture
996/// supports BitExtract instruction. Here is an example:
997/// BB1:
998/// %x.extract.shift = lshr i64 %arg1, 32
999/// BB2:
1000/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1001/// ==>
1002///
1003/// BB2:
1004/// %x.extract.shift.1 = lshr i64 %arg1, 32
1005/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1006///
1007/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1008/// instruction.
1009/// Return true if any changes are made.
1010static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001011 const TargetLowering &TLI,
1012 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001013 BasicBlock *DefBB = ShiftI->getParent();
1014
1015 /// Only insert instructions in each block once.
1016 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1017
Mehdi Amini44ede332015-07-09 02:09:04 +00001018 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001019
1020 bool MadeChange = false;
1021 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1022 UI != E;) {
1023 Use &TheUse = UI.getUse();
1024 Instruction *User = cast<Instruction>(*UI);
1025 // Preincrement use iterator so we don't invalidate it.
1026 ++UI;
1027
1028 // Don't bother for PHI nodes.
1029 if (isa<PHINode>(User))
1030 continue;
1031
1032 if (!isExtractBitsCandidateUse(User))
1033 continue;
1034
1035 BasicBlock *UserBB = User->getParent();
1036
1037 if (UserBB == DefBB) {
1038 // If the shift and truncate instruction are in the same BB. The use of
1039 // the truncate(TruncUse) may still introduce another truncate if not
1040 // legal. In this case, we would like to sink both shift and truncate
1041 // instruction to the BB of TruncUse.
1042 // for example:
1043 // BB1:
1044 // i64 shift.result = lshr i64 opnd, imm
1045 // trunc.result = trunc shift.result to i16
1046 //
1047 // BB2:
1048 // ----> We will have an implicit truncate here if the architecture does
1049 // not have i16 compare.
1050 // cmp i16 trunc.result, opnd2
1051 //
1052 if (isa<TruncInst>(User) && shiftIsLegal
1053 // If the type of the truncate is legal, no trucate will be
1054 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001055 &&
1056 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001057 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001058 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001059
1060 continue;
1061 }
1062 // If we have already inserted a shift into this block, use it.
1063 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1064
1065 if (!InsertedShift) {
1066 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1067
1068 if (ShiftI->getOpcode() == Instruction::AShr)
1069 InsertedShift =
1070 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
1071 else
1072 InsertedShift =
1073 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
1074
1075 MadeChange = true;
1076 }
1077
1078 // Replace a use of the shift with a use of the new shift.
1079 TheUse = InsertedShift;
1080 }
1081
1082 // If we removed all uses, nuke the shift.
1083 if (ShiftI->use_empty())
1084 ShiftI->eraseFromParent();
1085
1086 return MadeChange;
1087}
1088
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001089// ScalarizeMaskedLoad() translates masked load intrinsic, like
1090// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1091// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001092// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001093// the appropriate mask bit is set
1094//
1095// %1 = bitcast i8* %addr to i32*
1096// %2 = extractelement <16 x i1> %mask, i32 0
1097// %3 = icmp eq i1 %2, true
1098// br i1 %3, label %cond.load, label %else
1099//
1100//cond.load: ; preds = %0
1101// %4 = getelementptr i32* %1, i32 0
1102// %5 = load i32* %4
1103// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1104// br label %else
1105//
1106//else: ; preds = %0, %cond.load
1107// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1108// %7 = extractelement <16 x i1> %mask, i32 1
1109// %8 = icmp eq i1 %7, true
1110// br i1 %8, label %cond.load1, label %else2
1111//
1112//cond.load1: ; preds = %else
1113// %9 = getelementptr i32* %1, i32 1
1114// %10 = load i32* %9
1115// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1116// br label %else2
1117//
1118//else2: ; preds = %else, %cond.load1
1119// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1120// %12 = extractelement <16 x i1> %mask, i32 2
1121// %13 = icmp eq i1 %12, true
1122// br i1 %13, label %cond.load4, label %else5
1123//
1124static void ScalarizeMaskedLoad(CallInst *CI) {
1125 Value *Ptr = CI->getArgOperand(0);
1126 Value *Src0 = CI->getArgOperand(3);
1127 Value *Mask = CI->getArgOperand(2);
1128 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1129 Type *EltTy = VecType->getElementType();
1130
1131 assert(VecType && "Unexpected return type of masked load intrinsic");
1132
1133 IRBuilder<> Builder(CI->getContext());
1134 Instruction *InsertPt = CI;
1135 BasicBlock *IfBlock = CI->getParent();
1136 BasicBlock *CondBlock = nullptr;
1137 BasicBlock *PrevIfBlock = CI->getParent();
1138 Builder.SetInsertPoint(InsertPt);
1139
1140 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1141
1142 // Bitcast %addr fron i8* to EltTy*
1143 Type *NewPtrType =
1144 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1145 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1146 Value *UndefVal = UndefValue::get(VecType);
1147
1148 // The result vector
1149 Value *VResult = UndefVal;
1150
1151 PHINode *Phi = nullptr;
1152 Value *PrevPhi = UndefVal;
1153
1154 unsigned VectorWidth = VecType->getNumElements();
1155 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1156
1157 // Fill the "else" block, created in the previous iteration
1158 //
1159 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1160 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1161 // %to_load = icmp eq i1 %mask_1, true
1162 // br i1 %to_load, label %cond.load, label %else
1163 //
1164 if (Idx > 0) {
1165 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1166 Phi->addIncoming(VResult, CondBlock);
1167 Phi->addIncoming(PrevPhi, PrevIfBlock);
1168 PrevPhi = Phi;
1169 VResult = Phi;
1170 }
1171
1172 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1173 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1174 ConstantInt::get(Predicate->getType(), 1));
1175
1176 // Create "cond" block
1177 //
1178 // %EltAddr = getelementptr i32* %1, i32 0
1179 // %Elt = load i32* %EltAddr
1180 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1181 //
1182 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1183 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001184
1185 Value *Gep =
1186 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001187 LoadInst* Load = Builder.CreateLoad(Gep, false);
1188 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1189
1190 // Create "else" block, fill it in the next iteration
1191 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1192 Builder.SetInsertPoint(InsertPt);
1193 Instruction *OldBr = IfBlock->getTerminator();
1194 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1195 OldBr->eraseFromParent();
1196 PrevIfBlock = IfBlock;
1197 IfBlock = NewIfBlock;
1198 }
1199
1200 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1201 Phi->addIncoming(VResult, CondBlock);
1202 Phi->addIncoming(PrevPhi, PrevIfBlock);
1203 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1204 CI->replaceAllUsesWith(NewI);
1205 CI->eraseFromParent();
1206}
1207
1208// ScalarizeMaskedStore() translates masked store intrinsic, like
1209// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1210// <16 x i1> %mask)
1211// to a chain of basic blocks, that stores element one-by-one if
1212// the appropriate mask bit is set
1213//
1214// %1 = bitcast i8* %addr to i32*
1215// %2 = extractelement <16 x i1> %mask, i32 0
1216// %3 = icmp eq i1 %2, true
1217// br i1 %3, label %cond.store, label %else
1218//
1219// cond.store: ; preds = %0
1220// %4 = extractelement <16 x i32> %val, i32 0
1221// %5 = getelementptr i32* %1, i32 0
1222// store i32 %4, i32* %5
1223// br label %else
1224//
1225// else: ; preds = %0, %cond.store
1226// %6 = extractelement <16 x i1> %mask, i32 1
1227// %7 = icmp eq i1 %6, true
1228// br i1 %7, label %cond.store1, label %else2
1229//
1230// cond.store1: ; preds = %else
1231// %8 = extractelement <16 x i32> %val, i32 1
1232// %9 = getelementptr i32* %1, i32 1
1233// store i32 %8, i32* %9
1234// br label %else2
1235// . . .
1236static void ScalarizeMaskedStore(CallInst *CI) {
1237 Value *Ptr = CI->getArgOperand(1);
1238 Value *Src = CI->getArgOperand(0);
1239 Value *Mask = CI->getArgOperand(3);
1240
1241 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1242 Type *EltTy = VecType->getElementType();
1243
1244 assert(VecType && "Unexpected data type in masked store intrinsic");
1245
1246 IRBuilder<> Builder(CI->getContext());
1247 Instruction *InsertPt = CI;
1248 BasicBlock *IfBlock = CI->getParent();
1249 Builder.SetInsertPoint(InsertPt);
1250 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1251
1252 // Bitcast %addr fron i8* to EltTy*
1253 Type *NewPtrType =
1254 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1255 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1256
1257 unsigned VectorWidth = VecType->getNumElements();
1258 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1259
1260 // Fill the "else" block, created in the previous iteration
1261 //
1262 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1263 // %to_store = icmp eq i1 %mask_1, true
1264 // br i1 %to_load, label %cond.store, label %else
1265 //
1266 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1267 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1268 ConstantInt::get(Predicate->getType(), 1));
1269
1270 // Create "cond" block
1271 //
1272 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1273 // %EltAddr = getelementptr i32* %1, i32 0
1274 // %store i32 %OneElt, i32* %EltAddr
1275 //
1276 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1277 Builder.SetInsertPoint(InsertPt);
1278
1279 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001280 Value *Gep =
1281 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001282 Builder.CreateStore(OneElt, Gep);
1283
1284 // Create "else" block, fill it in the next iteration
1285 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1286 Builder.SetInsertPoint(InsertPt);
1287 Instruction *OldBr = IfBlock->getTerminator();
1288 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1289 OldBr->eraseFromParent();
1290 IfBlock = NewIfBlock;
1291 }
1292 CI->eraseFromParent();
1293}
1294
1295bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001296 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001297
Chris Lattner7a277142011-01-15 07:14:54 +00001298 // Lower inline assembly if we can.
1299 // If we found an inline asm expession, and if the target knows how to
1300 // lower it to normal LLVM code, do so now.
1301 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1302 if (TLI->ExpandInlineAsm(CI)) {
1303 // Avoid invalidating the iterator.
1304 CurInstIterator = BB->begin();
1305 // Avoid processing instructions out of order, which could cause
1306 // reuse before a value is defined.
1307 SunkAddrs.clear();
1308 return true;
1309 }
1310 // Sink address computing for memory operands into the block.
1311 if (OptimizeInlineAsmInst(CI))
1312 return true;
1313 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001314
John Brawn0dbcd652015-03-18 12:01:59 +00001315 // Align the pointer arguments to this call if the target thinks it's a good
1316 // idea
1317 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001318 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001319 for (auto &Arg : CI->arg_operands()) {
1320 // We want to align both objects whose address is used directly and
1321 // objects whose address is used in casts and GEPs, though it only makes
1322 // sense for GEPs if the offset is a multiple of the desired alignment and
1323 // if size - offset meets the size threshold.
1324 if (!Arg->getType()->isPointerTy())
1325 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001326 APInt Offset(DL->getPointerSizeInBits(
1327 cast<PointerType>(Arg->getType())->getAddressSpace()),
1328 0);
1329 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001330 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001331 if ((Offset2 & (PrefAlign-1)) != 0)
1332 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001333 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001334 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1335 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001336 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001337 // Global variables can only be aligned if they are defined in this
1338 // object (i.e. they are uniquely initialized in this object), and
1339 // over-aligning global variables that have an explicit section is
1340 // forbidden.
1341 GlobalVariable *GV;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001342 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1343 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1344 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1345 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001346 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001347 }
1348 // If this is a memcpy (or similar) then we may be able to improve the
1349 // alignment
1350 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001351 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001352 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001353 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
John Brawn0dbcd652015-03-18 12:01:59 +00001354 if (Align > MI->getAlignment())
1355 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1356 }
1357 }
1358
Eric Christopher4b7948e2010-03-11 02:41:03 +00001359 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001360 if (II) {
1361 switch (II->getIntrinsicID()) {
1362 default: break;
1363 case Intrinsic::objectsize: {
1364 // Lower all uses of llvm.objectsize.*
1365 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1366 Type *ReturnTy = CI->getType();
1367 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001368
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001369 // Substituting this can cause recursive simplifications, which can
1370 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1371 // happens.
1372 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001373
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001374 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001375 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001376
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001377 // If the iterator instruction was recursively deleted, start over at the
1378 // start of the block.
1379 if (IterHandle != CurInstIterator) {
1380 CurInstIterator = BB->begin();
1381 SunkAddrs.clear();
1382 }
1383 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001384 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001385 case Intrinsic::masked_load: {
1386 // Scalarize unsupported vector masked load
1387 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1388 ScalarizeMaskedLoad(CI);
1389 ModifiedDT = true;
1390 return true;
1391 }
1392 return false;
1393 }
1394 case Intrinsic::masked_store: {
1395 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1396 ScalarizeMaskedStore(CI);
1397 ModifiedDT = true;
1398 return true;
1399 }
1400 return false;
1401 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001402 case Intrinsic::aarch64_stlxr:
1403 case Intrinsic::aarch64_stxr: {
1404 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1405 if (!ExtVal || !ExtVal->hasOneUse() ||
1406 ExtVal->getParent() == CI->getParent())
1407 return false;
1408 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1409 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001410 // Mark this instruction as "inserted by CGP", so that other
1411 // optimizations don't touch it.
1412 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001413 return true;
1414 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001415 case Intrinsic::invariant_group_barrier:
1416 II->replaceAllUsesWith(II->getArgOperand(0));
1417 II->eraseFromParent();
1418 return true;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001419 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001420
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001421 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001422 // Unknown address space.
1423 // TODO: Target hook to pick which address space the intrinsic cares
1424 // about?
1425 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001426 SmallVector<Value*, 2> PtrOps;
1427 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001428 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001429 while (!PtrOps.empty())
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001430 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001431 return true;
1432 }
Pete Cooper615fd892012-03-13 20:59:56 +00001433 }
1434
Eric Christopher4b7948e2010-03-11 02:41:03 +00001435 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001436 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001437
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001438 // Lower all default uses of _chk calls. This is very similar
1439 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001440 // to fortified library functions (e.g. __memcpy_chk) that have the default
1441 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001442 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001443 if (Value *V = Simplifier.optimizeCall(CI)) {
1444 CI->replaceAllUsesWith(V);
1445 CI->eraseFromParent();
1446 return true;
1447 }
1448 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001449}
Chris Lattner1b93be52011-01-15 07:25:29 +00001450
Evan Cheng0663f232011-03-21 01:19:09 +00001451/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1452/// instructions to the predecessor to enable tail call optimizations. The
1453/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001454/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001455/// bb0:
1456/// %tmp0 = tail call i32 @f0()
1457/// br label %return
1458/// bb1:
1459/// %tmp1 = tail call i32 @f1()
1460/// br label %return
1461/// bb2:
1462/// %tmp2 = tail call i32 @f2()
1463/// br label %return
1464/// return:
1465/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1466/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001467/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001468///
1469/// =>
1470///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001471/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001472/// bb0:
1473/// %tmp0 = tail call i32 @f0()
1474/// ret i32 %tmp0
1475/// bb1:
1476/// %tmp1 = tail call i32 @f1()
1477/// ret i32 %tmp1
1478/// bb2:
1479/// %tmp2 = tail call i32 @f2()
1480/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001481/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +00001482bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001483 if (!TLI)
1484 return false;
1485
Benjamin Kramer455fa352012-11-23 19:17:06 +00001486 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1487 if (!RI)
1488 return false;
1489
Craig Topperc0196b12014-04-14 00:51:57 +00001490 PHINode *PN = nullptr;
1491 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001492 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001493 if (V) {
1494 BCI = dyn_cast<BitCastInst>(V);
1495 if (BCI)
1496 V = BCI->getOperand(0);
1497
1498 PN = dyn_cast<PHINode>(V);
1499 if (!PN)
1500 return false;
1501 }
Evan Cheng0663f232011-03-21 01:19:09 +00001502
Cameron Zwarich4649f172011-03-24 04:52:10 +00001503 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001504 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001505
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001506 // It's not safe to eliminate the sign / zero extension of the return value.
1507 // See llvm::isInTailCallPosition().
1508 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001509 AttributeSet CallerAttrs = F->getAttributes();
1510 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1511 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001512 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001513
Cameron Zwarich4649f172011-03-24 04:52:10 +00001514 // Make sure there are no instructions between the PHI and return, or that the
1515 // return is the first instruction in the block.
1516 if (PN) {
1517 BasicBlock::iterator BI = BB->begin();
1518 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001519 if (&*BI == BCI)
1520 // Also skip over the bitcast.
1521 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001522 if (&*BI != RI)
1523 return false;
1524 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001525 BasicBlock::iterator BI = BB->begin();
1526 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1527 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001528 return false;
1529 }
Evan Cheng0663f232011-03-21 01:19:09 +00001530
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001531 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1532 /// call.
1533 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001534 if (PN) {
1535 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1536 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1537 // Make sure the phi value is indeed produced by the tail call.
1538 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1539 TLI->mayBeEmittedAsTailCall(CI))
1540 TailCalls.push_back(CI);
1541 }
1542 } else {
1543 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001544 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001545 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001546 continue;
1547
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001548 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001549 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1550 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001551 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1552 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001553 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001554
Cameron Zwarich4649f172011-03-24 04:52:10 +00001555 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001556 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001557 TailCalls.push_back(CI);
1558 }
Evan Cheng0663f232011-03-21 01:19:09 +00001559 }
1560
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001561 bool Changed = false;
1562 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1563 CallInst *CI = TailCalls[i];
1564 CallSite CS(CI);
1565
1566 // Conservatively require the attributes of the call to match those of the
1567 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001568 AttributeSet CalleeAttrs = CS.getAttributes();
1569 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001570 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001571 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001572 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001573 continue;
1574
1575 // Make sure the call instruction is followed by an unconditional branch to
1576 // the return block.
1577 BasicBlock *CallBB = CI->getParent();
1578 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1579 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1580 continue;
1581
1582 // Duplicate the return into CallBB.
1583 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001584 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001585 ++NumRetsDup;
1586 }
1587
1588 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001589 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001590 BB->eraseFromParent();
1591
1592 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001593}
1594
Chris Lattner728f9022008-11-25 07:09:13 +00001595//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001596// Memory Optimization
1597//===----------------------------------------------------------------------===//
1598
Chandler Carruthc8925912013-01-05 02:09:22 +00001599namespace {
1600
1601/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1602/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001603struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001604 Value *BaseReg;
1605 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001606 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001607 void print(raw_ostream &OS) const;
1608 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001609
Chandler Carruthc8925912013-01-05 02:09:22 +00001610 bool operator==(const ExtAddrMode& O) const {
1611 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1612 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1613 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1614 }
1615};
1616
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001617#ifndef NDEBUG
1618static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1619 AM.print(OS);
1620 return OS;
1621}
1622#endif
1623
Chandler Carruthc8925912013-01-05 02:09:22 +00001624void ExtAddrMode::print(raw_ostream &OS) const {
1625 bool NeedPlus = false;
1626 OS << "[";
1627 if (BaseGV) {
1628 OS << (NeedPlus ? " + " : "")
1629 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001630 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001631 NeedPlus = true;
1632 }
1633
Richard Trieuc0f91212014-05-30 03:15:17 +00001634 if (BaseOffs) {
1635 OS << (NeedPlus ? " + " : "")
1636 << BaseOffs;
1637 NeedPlus = true;
1638 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001639
1640 if (BaseReg) {
1641 OS << (NeedPlus ? " + " : "")
1642 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001643 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001644 NeedPlus = true;
1645 }
1646 if (Scale) {
1647 OS << (NeedPlus ? " + " : "")
1648 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001649 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001650 }
1651
1652 OS << ']';
1653}
1654
1655#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1656void ExtAddrMode::dump() const {
1657 print(dbgs());
1658 dbgs() << '\n';
1659}
1660#endif
1661
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001662/// \brief This class provides transaction based operation on the IR.
1663/// Every change made through this class is recorded in the internal state and
1664/// can be undone (rollback) until commit is called.
1665class TypePromotionTransaction {
1666
1667 /// \brief This represents the common interface of the individual transaction.
1668 /// Each class implements the logic for doing one specific modification on
1669 /// the IR via the TypePromotionTransaction.
1670 class TypePromotionAction {
1671 protected:
1672 /// The Instruction modified.
1673 Instruction *Inst;
1674
1675 public:
1676 /// \brief Constructor of the action.
1677 /// The constructor performs the related action on the IR.
1678 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1679
1680 virtual ~TypePromotionAction() {}
1681
1682 /// \brief Undo the modification done by this action.
1683 /// When this method is called, the IR must be in the same state as it was
1684 /// before this action was applied.
1685 /// \pre Undoing the action works if and only if the IR is in the exact same
1686 /// state as it was directly after this action was applied.
1687 virtual void undo() = 0;
1688
1689 /// \brief Advocate every change made by this action.
1690 /// When the results on the IR of the action are to be kept, it is important
1691 /// to call this function, otherwise hidden information may be kept forever.
1692 virtual void commit() {
1693 // Nothing to be done, this action is not doing anything.
1694 }
1695 };
1696
1697 /// \brief Utility to remember the position of an instruction.
1698 class InsertionHandler {
1699 /// Position of an instruction.
1700 /// Either an instruction:
1701 /// - Is the first in a basic block: BB is used.
1702 /// - Has a previous instructon: PrevInst is used.
1703 union {
1704 Instruction *PrevInst;
1705 BasicBlock *BB;
1706 } Point;
1707 /// Remember whether or not the instruction had a previous instruction.
1708 bool HasPrevInstruction;
1709
1710 public:
1711 /// \brief Record the position of \p Inst.
1712 InsertionHandler(Instruction *Inst) {
1713 BasicBlock::iterator It = Inst;
1714 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1715 if (HasPrevInstruction)
1716 Point.PrevInst = --It;
1717 else
1718 Point.BB = Inst->getParent();
1719 }
1720
1721 /// \brief Insert \p Inst at the recorded position.
1722 void insert(Instruction *Inst) {
1723 if (HasPrevInstruction) {
1724 if (Inst->getParent())
1725 Inst->removeFromParent();
1726 Inst->insertAfter(Point.PrevInst);
1727 } else {
1728 Instruction *Position = Point.BB->getFirstInsertionPt();
1729 if (Inst->getParent())
1730 Inst->moveBefore(Position);
1731 else
1732 Inst->insertBefore(Position);
1733 }
1734 }
1735 };
1736
1737 /// \brief Move an instruction before another.
1738 class InstructionMoveBefore : public TypePromotionAction {
1739 /// Original position of the instruction.
1740 InsertionHandler Position;
1741
1742 public:
1743 /// \brief Move \p Inst before \p Before.
1744 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1745 : TypePromotionAction(Inst), Position(Inst) {
1746 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1747 Inst->moveBefore(Before);
1748 }
1749
1750 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001751 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001752 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1753 Position.insert(Inst);
1754 }
1755 };
1756
1757 /// \brief Set the operand of an instruction with a new value.
1758 class OperandSetter : public TypePromotionAction {
1759 /// Original operand of the instruction.
1760 Value *Origin;
1761 /// Index of the modified instruction.
1762 unsigned Idx;
1763
1764 public:
1765 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1766 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1767 : TypePromotionAction(Inst), Idx(Idx) {
1768 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1769 << "for:" << *Inst << "\n"
1770 << "with:" << *NewVal << "\n");
1771 Origin = Inst->getOperand(Idx);
1772 Inst->setOperand(Idx, NewVal);
1773 }
1774
1775 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001776 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001777 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1778 << "for: " << *Inst << "\n"
1779 << "with: " << *Origin << "\n");
1780 Inst->setOperand(Idx, Origin);
1781 }
1782 };
1783
1784 /// \brief Hide the operands of an instruction.
1785 /// Do as if this instruction was not using any of its operands.
1786 class OperandsHider : public TypePromotionAction {
1787 /// The list of original operands.
1788 SmallVector<Value *, 4> OriginalValues;
1789
1790 public:
1791 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1792 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1793 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1794 unsigned NumOpnds = Inst->getNumOperands();
1795 OriginalValues.reserve(NumOpnds);
1796 for (unsigned It = 0; It < NumOpnds; ++It) {
1797 // Save the current operand.
1798 Value *Val = Inst->getOperand(It);
1799 OriginalValues.push_back(Val);
1800 // Set a dummy one.
1801 // We could use OperandSetter here, but that would implied an overhead
1802 // that we are not willing to pay.
1803 Inst->setOperand(It, UndefValue::get(Val->getType()));
1804 }
1805 }
1806
1807 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001808 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001809 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1810 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1811 Inst->setOperand(It, OriginalValues[It]);
1812 }
1813 };
1814
1815 /// \brief Build a truncate instruction.
1816 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001817 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001818 public:
1819 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1820 /// result.
1821 /// trunc Opnd to Ty.
1822 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1823 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001824 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1825 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001826 }
1827
Quentin Colombetac55b152014-09-16 22:36:07 +00001828 /// \brief Get the built value.
1829 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001830
1831 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001832 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001833 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1834 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1835 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001836 }
1837 };
1838
1839 /// \brief Build a sign extension instruction.
1840 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001841 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001842 public:
1843 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1844 /// result.
1845 /// sext Opnd to Ty.
1846 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001847 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001848 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001849 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1850 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001851 }
1852
Quentin Colombetac55b152014-09-16 22:36:07 +00001853 /// \brief Get the built value.
1854 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001855
1856 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001857 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001858 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1859 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1860 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001861 }
1862 };
1863
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001864 /// \brief Build a zero extension instruction.
1865 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001866 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001867 public:
1868 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1869 /// result.
1870 /// zext Opnd to Ty.
1871 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001872 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001873 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001874 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1875 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001876 }
1877
Quentin Colombetac55b152014-09-16 22:36:07 +00001878 /// \brief Get the built value.
1879 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001880
1881 /// \brief Remove the built instruction.
1882 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001883 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1884 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1885 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001886 }
1887 };
1888
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001889 /// \brief Mutate an instruction to another type.
1890 class TypeMutator : public TypePromotionAction {
1891 /// Record the original type.
1892 Type *OrigTy;
1893
1894 public:
1895 /// \brief Mutate the type of \p Inst into \p NewTy.
1896 TypeMutator(Instruction *Inst, Type *NewTy)
1897 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1898 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1899 << "\n");
1900 Inst->mutateType(NewTy);
1901 }
1902
1903 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001904 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001905 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1906 << "\n");
1907 Inst->mutateType(OrigTy);
1908 }
1909 };
1910
1911 /// \brief Replace the uses of an instruction by another instruction.
1912 class UsesReplacer : public TypePromotionAction {
1913 /// Helper structure to keep track of the replaced uses.
1914 struct InstructionAndIdx {
1915 /// The instruction using the instruction.
1916 Instruction *Inst;
1917 /// The index where this instruction is used for Inst.
1918 unsigned Idx;
1919 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1920 : Inst(Inst), Idx(Idx) {}
1921 };
1922
1923 /// Keep track of the original uses (pair Instruction, Index).
1924 SmallVector<InstructionAndIdx, 4> OriginalUses;
1925 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1926
1927 public:
1928 /// \brief Replace all the use of \p Inst by \p New.
1929 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1930 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1931 << "\n");
1932 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001933 for (Use &U : Inst->uses()) {
1934 Instruction *UserI = cast<Instruction>(U.getUser());
1935 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001936 }
1937 // Now, we can replace the uses.
1938 Inst->replaceAllUsesWith(New);
1939 }
1940
1941 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001942 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001943 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1944 for (use_iterator UseIt = OriginalUses.begin(),
1945 EndIt = OriginalUses.end();
1946 UseIt != EndIt; ++UseIt) {
1947 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1948 }
1949 }
1950 };
1951
1952 /// \brief Remove an instruction from the IR.
1953 class InstructionRemover : public TypePromotionAction {
1954 /// Original position of the instruction.
1955 InsertionHandler Inserter;
1956 /// Helper structure to hide all the link to the instruction. In other
1957 /// words, this helps to do as if the instruction was removed.
1958 OperandsHider Hider;
1959 /// Keep track of the uses replaced, if any.
1960 UsesReplacer *Replacer;
1961
1962 public:
1963 /// \brief Remove all reference of \p Inst and optinally replace all its
1964 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001965 /// \pre If !Inst->use_empty(), then New != nullptr
1966 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001967 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001968 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001969 if (New)
1970 Replacer = new UsesReplacer(Inst, New);
1971 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1972 Inst->removeFromParent();
1973 }
1974
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00001975 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001976
1977 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001978 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001979
1980 /// \brief Resurrect the instruction and reassign it to the proper uses if
1981 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001982 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001983 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1984 Inserter.insert(Inst);
1985 if (Replacer)
1986 Replacer->undo();
1987 Hider.undo();
1988 }
1989 };
1990
1991public:
1992 /// Restoration point.
1993 /// The restoration point is a pointer to an action instead of an iterator
1994 /// because the iterator may be invalidated but not the pointer.
1995 typedef const TypePromotionAction *ConstRestorationPt;
1996 /// Advocate every changes made in that transaction.
1997 void commit();
1998 /// Undo all the changes made after the given point.
1999 void rollback(ConstRestorationPt Point);
2000 /// Get the current restoration point.
2001 ConstRestorationPt getRestorationPoint() const;
2002
2003 /// \name API for IR modification with state keeping to support rollback.
2004 /// @{
2005 /// Same as Instruction::setOperand.
2006 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2007 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002008 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002009 /// Same as Value::replaceAllUsesWith.
2010 void replaceAllUsesWith(Instruction *Inst, Value *New);
2011 /// Same as Value::mutateType.
2012 void mutateType(Instruction *Inst, Type *NewTy);
2013 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002014 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002015 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002016 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002017 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002018 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002019 /// Same as Instruction::moveBefore.
2020 void moveBefore(Instruction *Inst, Instruction *Before);
2021 /// @}
2022
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002023private:
2024 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002025 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2026 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002027};
2028
2029void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2030 Value *NewVal) {
2031 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002032 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002033}
2034
2035void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2036 Value *NewVal) {
2037 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002038 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002039}
2040
2041void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2042 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002043 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002044}
2045
2046void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002047 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002048}
2049
Quentin Colombetac55b152014-09-16 22:36:07 +00002050Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2051 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002052 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002053 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002054 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002055 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002056}
2057
Quentin Colombetac55b152014-09-16 22:36:07 +00002058Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2059 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002060 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002061 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002062 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002063 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002064}
2065
Quentin Colombetac55b152014-09-16 22:36:07 +00002066Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2067 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002068 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002069 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002070 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002071 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002072}
2073
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002074void TypePromotionTransaction::moveBefore(Instruction *Inst,
2075 Instruction *Before) {
2076 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002077 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002078}
2079
2080TypePromotionTransaction::ConstRestorationPt
2081TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002082 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002083}
2084
2085void TypePromotionTransaction::commit() {
2086 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002087 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002088 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002089 Actions.clear();
2090}
2091
2092void TypePromotionTransaction::rollback(
2093 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002094 while (!Actions.empty() && Point != Actions.back().get()) {
2095 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002096 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002097 }
2098}
2099
Chandler Carruthc8925912013-01-05 02:09:22 +00002100/// \brief A helper class for matching addressing modes.
2101///
2102/// This encapsulates the logic for matching the target-legal addressing modes.
2103class AddressingModeMatcher {
2104 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002105 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002106 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002107 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002108
2109 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2110 /// the memory instruction that we're computing this address for.
2111 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002112 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002113 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002114
Chandler Carruthc8925912013-01-05 02:09:22 +00002115 /// AddrMode - This is the addressing mode that we're building up. This is
2116 /// part of the return value of this addressing mode matching stuff.
2117 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002118
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002119 /// The instructions inserted by other CodeGenPrepare optimizations.
2120 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002121 /// A map from the instructions to their type before promotion.
2122 InstrToOrigTy &PromotedInsts;
2123 /// The ongoing transaction where every action should be registered.
2124 TypePromotionTransaction &TPT;
2125
Chandler Carruthc8925912013-01-05 02:09:22 +00002126 /// IgnoreProfitability - This is set to true when we should not do
2127 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
2128 /// always returns true.
2129 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002130
Eric Christopherd75c00c2015-02-26 22:38:34 +00002131 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002132 const TargetMachine &TM, Type *AT, unsigned AS,
2133 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002134 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002135 InstrToOrigTy &PromotedInsts,
2136 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002137 : AddrModeInsts(AMI), TM(TM),
2138 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2139 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002140 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2141 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2142 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002143 IgnoreProfitability = false;
2144 }
2145public:
Stephen Lin837bba12013-07-15 17:55:02 +00002146
Chandler Carruthc8925912013-01-05 02:09:22 +00002147 /// Match - Find the maximal addressing mode that a load/store of V can fold,
2148 /// give an access type of AccessTy. This returns a list of involved
2149 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002150 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002151 /// optimizations.
2152 /// \p PromotedInsts maps the instructions to their type before promotion.
2153 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002154 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002155 Instruction *MemoryInst,
2156 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002157 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002158 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002159 InstrToOrigTy &PromotedInsts,
2160 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002161 ExtAddrMode Result;
2162
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002163 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002164 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002165 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002166 (void)Success; assert(Success && "Couldn't select *anything*?");
2167 return Result;
2168 }
2169private:
2170 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2171 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002172 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002173 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00002174 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
2175 ExtAddrMode &AMBefore,
2176 ExtAddrMode &AMAfter);
2177 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002178 bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002179 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002180};
2181
2182/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
2183/// Return true and update AddrMode if this addr mode is legal for the target,
2184/// false if not.
2185bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
2186 unsigned Depth) {
2187 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2188 // mode. Just process that directly.
2189 if (Scale == 1)
2190 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002191
Chandler Carruthc8925912013-01-05 02:09:22 +00002192 // If the scale is 0, it takes nothing to add this.
2193 if (Scale == 0)
2194 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002195
Chandler Carruthc8925912013-01-05 02:09:22 +00002196 // If we already have a scale of this value, we can add to it, otherwise, we
2197 // need an available scale field.
2198 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2199 return false;
2200
2201 ExtAddrMode TestAddrMode = AddrMode;
2202
2203 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2204 // [A+B + A*7] -> [B+A*8].
2205 TestAddrMode.Scale += Scale;
2206 TestAddrMode.ScaledReg = ScaleReg;
2207
2208 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002209 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002210 return false;
2211
2212 // It was legal, so commit it.
2213 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002214
Chandler Carruthc8925912013-01-05 02:09:22 +00002215 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2216 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2217 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002218 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002219 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2220 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2221 TestAddrMode.ScaledReg = AddLHS;
2222 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002223
Chandler Carruthc8925912013-01-05 02:09:22 +00002224 // If this addressing mode is legal, commit it and remember that we folded
2225 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002226 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002227 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2228 AddrMode = TestAddrMode;
2229 return true;
2230 }
2231 }
2232
2233 // Otherwise, not (x+c)*scale, just return what we have.
2234 return true;
2235}
2236
2237/// MightBeFoldableInst - This is a little filter, which returns true if an
2238/// addressing computation involving I might be folded into a load/store
2239/// accessing it. This doesn't need to be perfect, but needs to accept at least
2240/// the set of instructions that MatchOperationAddr can.
2241static bool MightBeFoldableInst(Instruction *I) {
2242 switch (I->getOpcode()) {
2243 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002244 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002245 // Don't touch identity bitcasts.
2246 if (I->getType() == I->getOperand(0)->getType())
2247 return false;
2248 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2249 case Instruction::PtrToInt:
2250 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2251 return true;
2252 case Instruction::IntToPtr:
2253 // We know the input is intptr_t, so this is foldable.
2254 return true;
2255 case Instruction::Add:
2256 return true;
2257 case Instruction::Mul:
2258 case Instruction::Shl:
2259 // Can only handle X*C and X << C.
2260 return isa<ConstantInt>(I->getOperand(1));
2261 case Instruction::GetElementPtr:
2262 return true;
2263 default:
2264 return false;
2265 }
2266}
2267
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002268/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2269/// \note \p Val is assumed to be the product of some type promotion.
2270/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2271/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002272static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2273 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002274 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2275 if (!PromotedInst)
2276 return false;
2277 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2278 // If the ISDOpcode is undefined, it was undefined before the promotion.
2279 if (!ISDOpcode)
2280 return true;
2281 // Otherwise, check if the promoted instruction is legal or not.
2282 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002283 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002284}
2285
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002286/// \brief Hepler class to perform type promotion.
2287class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002288 /// \brief Utility function to check whether or not a sign or zero extension
2289 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2290 /// either using the operands of \p Inst or promoting \p Inst.
2291 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002292 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002293 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002294 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002295 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002297 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002298 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002299 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2300 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002301
2302 /// \brief Utility function to determine if \p OpIdx should be promoted when
2303 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002304 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002305 if (isa<SelectInst>(Inst) && OpIdx == 0)
2306 return false;
2307 return true;
2308 }
2309
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002310 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002311 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002313 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002314 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002315 /// Newly added extensions are inserted in \p Exts.
2316 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002317 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002318 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002319 static Value *promoteOperandForTruncAndAnyExt(
2320 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002321 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002322 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002323 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002324
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002325 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326 /// operand is promotable and is not a supported trunc or sext.
2327 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002328 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002329 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002330 /// Newly added extensions are inserted in \p Exts.
2331 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002332 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002333 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002334 static Value *promoteOperandForOther(Instruction *Ext,
2335 TypePromotionTransaction &TPT,
2336 InstrToOrigTy &PromotedInsts,
2337 unsigned &CreatedInstsCost,
2338 SmallVectorImpl<Instruction *> *Exts,
2339 SmallVectorImpl<Instruction *> *Truncs,
2340 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002341
2342 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002343 static Value *signExtendOperandForOther(
2344 Instruction *Ext, TypePromotionTransaction &TPT,
2345 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2346 SmallVectorImpl<Instruction *> *Exts,
2347 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2348 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2349 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002350 }
2351
2352 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002353 static Value *zeroExtendOperandForOther(
2354 Instruction *Ext, TypePromotionTransaction &TPT,
2355 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2356 SmallVectorImpl<Instruction *> *Exts,
2357 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2358 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2359 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002360 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002361
2362public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002363 /// Type for the utility function that promotes the operand of Ext.
2364 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002365 InstrToOrigTy &PromotedInsts,
2366 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002367 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002368 SmallVectorImpl<Instruction *> *Truncs,
2369 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002370 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2371 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002372 /// \return NULL if no promotable action is possible with the current
2373 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002374 /// \p InsertedInsts keeps track of all the instructions inserted by the
2375 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002376 /// because we do not want to promote these instructions as CodeGenPrepare
2377 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2378 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002379 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002380 const TargetLowering &TLI,
2381 const InstrToOrigTy &PromotedInsts);
2382};
2383
2384bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002385 Type *ConsideredExtType,
2386 const InstrToOrigTy &PromotedInsts,
2387 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002388 // The promotion helper does not know how to deal with vector types yet.
2389 // To be able to fix that, we would need to fix the places where we
2390 // statically extend, e.g., constants and such.
2391 if (Inst->getType()->isVectorTy())
2392 return false;
2393
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002394 // We can always get through zext.
2395 if (isa<ZExtInst>(Inst))
2396 return true;
2397
2398 // sext(sext) is ok too.
2399 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002400 return true;
2401
2402 // We can get through binary operator, if it is legal. In other words, the
2403 // binary operator must have a nuw or nsw flag.
2404 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2405 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002406 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2407 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002408 return true;
2409
2410 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002411 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002412 if (!isa<TruncInst>(Inst))
2413 return false;
2414
2415 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002416 // Check if we can use this operand in the extension.
2417 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002418 // we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002419 if (!OpndVal->getType()->isIntegerTy() ||
2420 OpndVal->getType()->getIntegerBitWidth() >
2421 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002422 return false;
2423
2424 // If the operand of the truncate is not an instruction, we will not have
2425 // any information on the dropped bits.
2426 // (Actually we could for constant but it is not worth the extra logic).
2427 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2428 if (!Opnd)
2429 return false;
2430
2431 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002432 // I.e., check that trunc just drops extended bits of the same kind of
2433 // the extension.
2434 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002435 const Type *OpndType;
2436 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002437 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2438 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002439 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2440 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002441 else
2442 return false;
2443
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002444 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2446 return true;
2447
2448 return false;
2449}
2450
2451TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002452 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002453 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002454 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2455 "Unexpected instruction type");
2456 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2457 Type *ExtTy = Ext->getType();
2458 bool IsSExt = isa<SExtInst>(Ext);
2459 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002460 // get through.
2461 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002462 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002463 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464
2465 // Do not promote if the operand has been added by codegenprepare.
2466 // Otherwise, it means we are undoing an optimization that is likely to be
2467 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002468 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002469 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002470
2471 // SExt or Trunc instructions.
2472 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002473 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2474 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002475 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002476
2477 // Regular instruction.
2478 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002479 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002480 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002481 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002482}
2483
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002484Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002485 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002486 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002487 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002488 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002489 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2490 // get through it and this method should not be called.
2491 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002492 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002493 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002494 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002495 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002496 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002497 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002498 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002499 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2500 TPT.replaceAllUsesWith(SExt, ZExt);
2501 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002502 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002503 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002504 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2505 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002506 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2507 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002508 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002509
2510 // Remove dead code.
2511 if (SExtOpnd->use_empty())
2512 TPT.eraseInstruction(SExtOpnd);
2513
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002514 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002515 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002516 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002517 if (ExtInst) {
2518 if (Exts)
2519 Exts->push_back(ExtInst);
2520 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2521 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002522 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002523 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002525 // At this point we have: ext ty opnd to ty.
2526 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2527 Value *NextVal = ExtInst->getOperand(0);
2528 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002529 return NextVal;
2530}
2531
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002532Value *TypePromotionHelper::promoteOperandForOther(
2533 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002534 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002535 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002536 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2537 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002538 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002539 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002540 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002541 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002542 if (!ExtOpnd->hasOneUse()) {
2543 // ExtOpnd will be promoted.
2544 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002545 // promoted version.
2546 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002547 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002548 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2549 ITrunc->removeFromParent();
2550 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002551 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002552 if (Truncs)
2553 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002554 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002555
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002556 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2557 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002558 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002559 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002560 }
2561
2562 // Get through the Instruction:
2563 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002564 // 2. Replace the uses of Ext by Inst.
2565 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002566
2567 // Remember the original type of the instruction before promotion.
2568 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002569 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2570 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002571 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002572 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002573 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002574 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002575 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002576 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002577
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002578 DEBUG(dbgs() << "Propagate Ext to operands\n");
2579 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002580 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002581 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2582 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2583 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002584 DEBUG(dbgs() << "No need to propagate\n");
2585 continue;
2586 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002587 // Check if we can statically extend the operand.
2588 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002589 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002590 DEBUG(dbgs() << "Statically extend\n");
2591 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2592 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2593 : Cst->getValue().zext(BitWidth);
2594 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002595 continue;
2596 }
2597 // UndefValue are typed, so we have to statically sign extend them.
2598 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002599 DEBUG(dbgs() << "Statically extend\n");
2600 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002601 continue;
2602 }
2603
2604 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002605 // Check if Ext was reused to extend an operand.
2606 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002607 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002608 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002609 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2610 : TPT.createZExt(Ext, Opnd, Ext->getType());
2611 if (!isa<Instruction>(ValForExtOpnd)) {
2612 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2613 continue;
2614 }
2615 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002616 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002617 if (Exts)
2618 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002619 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002620
2621 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002622 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2623 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002624 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002625 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002626 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002627 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002628 if (ExtForOpnd == Ext) {
2629 DEBUG(dbgs() << "Extension is useless now\n");
2630 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002631 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002632 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002633}
2634
Quentin Colombet867c5502014-02-14 22:23:22 +00002635/// IsPromotionProfitable - Check whether or not promoting an instruction
2636/// to a wider type was profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002637/// \p NewCost gives the cost of extension instructions created by the
2638/// promotion.
2639/// \p OldCost gives the cost of extension instructions before the promotion
2640/// plus the number of instructions that have been
2641/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00002642/// \p PromotedOperand is the value that has been promoted.
2643/// \return True if the promotion is profitable, false otherwise.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002644bool AddressingModeMatcher::IsPromotionProfitable(
2645 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2646 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2647 // The cost of the new extensions is greater than the cost of the
2648 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00002649 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002650 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002651 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002652 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002653 return true;
2654 // The promotion is neutral but it may help folding the sign extension in
2655 // loads for instance.
2656 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00002657 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002658}
2659
Chandler Carruthc8925912013-01-05 02:09:22 +00002660/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2661/// fold the operation into the addressing mode. If so, update the addressing
2662/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002663/// If \p MovedAway is not NULL, it contains the information of whether or
2664/// not AddrInst has to be folded into the addressing mode on success.
2665/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2666/// because it has been moved away.
2667/// Thus AddrInst must not be added in the matched instructions.
2668/// This state can happen when AddrInst is a sext, since it may be moved away.
2669/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2670/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002671bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002672 unsigned Depth,
2673 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002674 // Avoid exponential behavior on extremely deep expression trees.
2675 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002676
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002677 // By default, all matched instructions stay in place.
2678 if (MovedAway)
2679 *MovedAway = false;
2680
Chandler Carruthc8925912013-01-05 02:09:22 +00002681 switch (Opcode) {
2682 case Instruction::PtrToInt:
2683 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2684 return MatchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00002685 case Instruction::IntToPtr: {
2686 auto AS = AddrInst->getType()->getPointerAddressSpace();
2687 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00002688 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00002689 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00002690 return MatchAddr(AddrInst->getOperand(0), Depth);
2691 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00002692 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002693 case Instruction::BitCast:
2694 // BitCast is always a noop, and we can handle it as long as it is
2695 // int->int or pointer->pointer (we don't want int<->fp or something).
2696 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2697 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2698 // Don't touch identity bitcasts. These were probably put here by LSR,
2699 // and we don't want to mess around with them. Assume it knows what it
2700 // is doing.
2701 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2702 return MatchAddr(AddrInst->getOperand(0), Depth);
2703 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00002704 case Instruction::AddrSpaceCast: {
2705 unsigned SrcAS
2706 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2707 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2708 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2709 return MatchAddr(AddrInst->getOperand(0), Depth);
2710 return false;
2711 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002712 case Instruction::Add: {
2713 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2714 ExtAddrMode BackupAddrMode = AddrMode;
2715 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002716 // Start a transaction at this point.
2717 // The LHS may match but not the RHS.
2718 // Therefore, we need a higher level restoration point to undo partially
2719 // matched operation.
2720 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2721 TPT.getRestorationPoint();
2722
Chandler Carruthc8925912013-01-05 02:09:22 +00002723 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2724 MatchAddr(AddrInst->getOperand(0), Depth+1))
2725 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002726
Chandler Carruthc8925912013-01-05 02:09:22 +00002727 // Restore the old addr mode info.
2728 AddrMode = BackupAddrMode;
2729 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002730 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002731
Chandler Carruthc8925912013-01-05 02:09:22 +00002732 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2733 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2734 MatchAddr(AddrInst->getOperand(1), Depth+1))
2735 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002736
Chandler Carruthc8925912013-01-05 02:09:22 +00002737 // Otherwise we definitely can't merge the ADD in.
2738 AddrMode = BackupAddrMode;
2739 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002740 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002741 break;
2742 }
2743 //case Instruction::Or:
2744 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2745 //break;
2746 case Instruction::Mul:
2747 case Instruction::Shl: {
2748 // Can only handle X*C and X << C.
2749 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002750 if (!RHS)
2751 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002752 int64_t Scale = RHS->getSExtValue();
2753 if (Opcode == Instruction::Shl)
2754 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002755
Chandler Carruthc8925912013-01-05 02:09:22 +00002756 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2757 }
2758 case Instruction::GetElementPtr: {
2759 // Scan the GEP. We check it if it contains constant offsets and at most
2760 // one variable offset.
2761 int VariableOperand = -1;
2762 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002763
Chandler Carruthc8925912013-01-05 02:09:22 +00002764 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00002765 gep_type_iterator GTI = gep_type_begin(AddrInst);
2766 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2767 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002768 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00002769 unsigned Idx =
2770 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2771 ConstantOffset += SL->getElementOffset(Idx);
2772 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002773 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00002774 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2775 ConstantOffset += CI->getSExtValue()*TypeSize;
2776 } else if (TypeSize) { // Scales of zero don't do anything.
2777 // We only allow one variable index at the moment.
2778 if (VariableOperand != -1)
2779 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002780
Chandler Carruthc8925912013-01-05 02:09:22 +00002781 // Remember the variable index.
2782 VariableOperand = i;
2783 VariableScale = TypeSize;
2784 }
2785 }
2786 }
Stephen Lin837bba12013-07-15 17:55:02 +00002787
Chandler Carruthc8925912013-01-05 02:09:22 +00002788 // A common case is for the GEP to only do a constant offset. In this case,
2789 // just add it to the disp field and check validity.
2790 if (VariableOperand == -1) {
2791 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002792 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002793 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002794 // Check to see if we can fold the base pointer in too.
2795 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2796 return true;
2797 }
2798 AddrMode.BaseOffs -= ConstantOffset;
2799 return false;
2800 }
2801
2802 // Save the valid addressing mode in case we can't match.
2803 ExtAddrMode BackupAddrMode = AddrMode;
2804 unsigned OldSize = AddrModeInsts.size();
2805
2806 // See if the scale and offset amount is valid for this target.
2807 AddrMode.BaseOffs += ConstantOffset;
2808
2809 // Match the base operand of the GEP.
2810 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2811 // If it couldn't be matched, just stuff the value in a register.
2812 if (AddrMode.HasBaseReg) {
2813 AddrMode = BackupAddrMode;
2814 AddrModeInsts.resize(OldSize);
2815 return false;
2816 }
2817 AddrMode.HasBaseReg = true;
2818 AddrMode.BaseReg = AddrInst->getOperand(0);
2819 }
2820
2821 // Match the remaining variable portion of the GEP.
2822 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2823 Depth)) {
2824 // If it couldn't be matched, try stuffing the base into a register
2825 // instead of matching it, and retrying the match of the scale.
2826 AddrMode = BackupAddrMode;
2827 AddrModeInsts.resize(OldSize);
2828 if (AddrMode.HasBaseReg)
2829 return false;
2830 AddrMode.HasBaseReg = true;
2831 AddrMode.BaseReg = AddrInst->getOperand(0);
2832 AddrMode.BaseOffs += ConstantOffset;
2833 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2834 VariableScale, Depth)) {
2835 // If even that didn't work, bail.
2836 AddrMode = BackupAddrMode;
2837 AddrModeInsts.resize(OldSize);
2838 return false;
2839 }
2840 }
2841
2842 return true;
2843 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002844 case Instruction::SExt:
2845 case Instruction::ZExt: {
2846 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2847 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002848 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002849
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002850 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002851 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002852 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002853 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002854 if (!TPH)
2855 return false;
2856
2857 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2858 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00002859 unsigned CreatedInstsCost = 0;
2860 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002861 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00002862 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002863 // SExt has been moved away.
2864 // Thus either it will be rematched later in the recursive calls or it is
2865 // gone. Anyway, we must not fold it into the addressing mode at this point.
2866 // E.g.,
2867 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002868 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002869 // addr = gep base, idx
2870 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002871 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002872 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2873 // addr = gep base, op <- match
2874 if (MovedAway)
2875 *MovedAway = true;
2876
2877 assert(PromotedOperand &&
2878 "TypePromotionHelper should have filtered out those cases");
2879
2880 ExtAddrMode BackupAddrMode = AddrMode;
2881 unsigned OldSize = AddrModeInsts.size();
2882
2883 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet1b274f92015-03-10 21:48:15 +00002884 // The total of the new cost is equals to the cost of the created
2885 // instructions.
2886 // The total of the old cost is equals to the cost of the extension plus
2887 // what we have saved in the addressing mode.
2888 !IsPromotionProfitable(CreatedInstsCost,
2889 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00002890 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002891 AddrMode = BackupAddrMode;
2892 AddrModeInsts.resize(OldSize);
2893 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2894 TPT.rollback(LastKnownGood);
2895 return false;
2896 }
2897 return true;
2898 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002899 }
2900 return false;
2901}
2902
2903/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2904/// addressing mode. If Addr can't be added to AddrMode this returns false and
2905/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2906/// or intptr_t for the target.
2907///
2908bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002909 // Start a transaction at this point that we will rollback if the matching
2910 // fails.
2911 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2912 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002913 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2914 // Fold in immediates if legal for the target.
2915 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002916 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002917 return true;
2918 AddrMode.BaseOffs -= CI->getSExtValue();
2919 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2920 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002921 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002922 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002923 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002924 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002925 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002926 }
2927 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2928 ExtAddrMode BackupAddrMode = AddrMode;
2929 unsigned OldSize = AddrModeInsts.size();
2930
2931 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002932 bool MovedAway = false;
2933 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2934 // This instruction may have been move away. If so, there is nothing
2935 // to check here.
2936 if (MovedAway)
2937 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002938 // Okay, it's possible to fold this. Check to see if it is actually
2939 // *profitable* to do so. We use a simple cost model to avoid increasing
2940 // register pressure too much.
2941 if (I->hasOneUse() ||
2942 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2943 AddrModeInsts.push_back(I);
2944 return true;
2945 }
Stephen Lin837bba12013-07-15 17:55:02 +00002946
Chandler Carruthc8925912013-01-05 02:09:22 +00002947 // It isn't profitable to do this, roll back.
2948 //cerr << "NOT FOLDING: " << *I;
2949 AddrMode = BackupAddrMode;
2950 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002951 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002952 }
2953 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2954 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2955 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002956 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002957 } else if (isa<ConstantPointerNull>(Addr)) {
2958 // Null pointer gets folded without affecting the addressing mode.
2959 return true;
2960 }
2961
2962 // Worse case, the target should support [reg] addressing modes. :)
2963 if (!AddrMode.HasBaseReg) {
2964 AddrMode.HasBaseReg = true;
2965 AddrMode.BaseReg = Addr;
2966 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002967 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002968 return true;
2969 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002970 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002971 }
2972
2973 // If the base register is already taken, see if we can do [r+r].
2974 if (AddrMode.Scale == 0) {
2975 AddrMode.Scale = 1;
2976 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002977 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002978 return true;
2979 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002980 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002981 }
2982 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002983 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002984 return false;
2985}
2986
2987/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2988/// inline asm call are due to memory operands. If so, return true, otherwise
2989/// return false.
2990static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00002991 const TargetMachine &TM) {
2992 const Function *F = CI->getParent()->getParent();
2993 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2994 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00002995 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002996 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
2997 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00002998 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2999 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003000
Chandler Carruthc8925912013-01-05 02:09:22 +00003001 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003002 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003003
3004 // If this asm operand is our Value*, and if it isn't an indirect memory
3005 // operand, we can't fold it!
3006 if (OpInfo.CallOperandVal == OpVal &&
3007 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3008 !OpInfo.isIndirect))
3009 return false;
3010 }
3011
3012 return true;
3013}
3014
3015/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
3016/// memory use. If we find an obviously non-foldable instruction, return true.
3017/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003018static bool FindAllMemoryUses(
3019 Instruction *I,
3020 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3021 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003022 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003023 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003024 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003025
Chandler Carruthc8925912013-01-05 02:09:22 +00003026 // If this is an obviously unfoldable instruction, bail out.
3027 if (!MightBeFoldableInst(I))
3028 return true;
3029
3030 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003031 for (Use &U : I->uses()) {
3032 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003033
Chandler Carruthcdf47882014-03-09 03:16:01 +00003034 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3035 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003036 continue;
3037 }
Stephen Lin837bba12013-07-15 17:55:02 +00003038
Chandler Carruthcdf47882014-03-09 03:16:01 +00003039 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3040 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003041 if (opNo == 0) return true; // Storing addr, not into addr.
3042 MemoryUses.push_back(std::make_pair(SI, opNo));
3043 continue;
3044 }
Stephen Lin837bba12013-07-15 17:55:02 +00003045
Chandler Carruthcdf47882014-03-09 03:16:01 +00003046 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003047 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3048 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003049
Chandler Carruthc8925912013-01-05 02:09:22 +00003050 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003051 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003052 return true;
3053 continue;
3054 }
Stephen Lin837bba12013-07-15 17:55:02 +00003055
Eric Christopher11e4df72015-02-26 22:38:43 +00003056 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003057 return true;
3058 }
3059
3060 return false;
3061}
3062
3063/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
3064/// the use site that we're folding it into. If so, there is no cost to
3065/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
3066/// that we know are live at the instruction already.
3067bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
3068 Value *KnownLive2) {
3069 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003070 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003071 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003072
Chandler Carruthc8925912013-01-05 02:09:22 +00003073 // All values other than instructions and arguments (e.g. constants) are live.
3074 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003075
Chandler Carruthc8925912013-01-05 02:09:22 +00003076 // If Val is a constant sized alloca in the entry block, it is live, this is
3077 // true because it is just a reference to the stack/frame pointer, which is
3078 // live for the whole function.
3079 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3080 if (AI->isStaticAlloca())
3081 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003082
Chandler Carruthc8925912013-01-05 02:09:22 +00003083 // Check to see if this value is already used in the memory instruction's
3084 // block. If so, it's already live into the block at the very least, so we
3085 // can reasonably fold it.
3086 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3087}
3088
3089/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
3090/// mode of the machine to fold the specified instruction into a load or store
3091/// that ultimately uses it. However, the specified instruction has multiple
3092/// uses. Given this, it may actually increase register pressure to fold it
3093/// into the load. For example, consider this code:
3094///
3095/// X = ...
3096/// Y = X+1
3097/// use(Y) -> nonload/store
3098/// Z = Y+1
3099/// load Z
3100///
3101/// In this case, Y has multiple uses, and can be folded into the load of Z
3102/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3103/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3104/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3105/// number of computations either.
3106///
3107/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3108/// X was live across 'load Z' for other reasons, we actually *would* want to
3109/// fold the addressing mode in the Z case. This would make Y die earlier.
3110bool AddressingModeMatcher::
3111IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
3112 ExtAddrMode &AMAfter) {
3113 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003114
Chandler Carruthc8925912013-01-05 02:09:22 +00003115 // AMBefore is the addressing mode before this instruction was folded into it,
3116 // and AMAfter is the addressing mode after the instruction was folded. Get
3117 // the set of registers referenced by AMAfter and subtract out those
3118 // referenced by AMBefore: this is the set of values which folding in this
3119 // address extends the lifetime of.
3120 //
3121 // Note that there are only two potential values being referenced here,
3122 // BaseReg and ScaleReg (global addresses are always available, as are any
3123 // folded immediates).
3124 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003125
Chandler Carruthc8925912013-01-05 02:09:22 +00003126 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3127 // lifetime wasn't extended by adding this instruction.
3128 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003129 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003130 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003131 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003132
3133 // If folding this instruction (and it's subexprs) didn't extend any live
3134 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003135 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003136 return true;
3137
3138 // If all uses of this instruction are ultimately load/store/inlineasm's,
3139 // check to see if their addressing modes will include this instruction. If
3140 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3141 // uses.
3142 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3143 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003144 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003145 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003146
Chandler Carruthc8925912013-01-05 02:09:22 +00003147 // Now that we know that all uses of this instruction are part of a chain of
3148 // computation involving only operations that could theoretically be folded
3149 // into a memory use, loop over each of these uses and see if they could
3150 // *actually* fold the instruction.
3151 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3152 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3153 Instruction *User = MemoryUses[i].first;
3154 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003155
Chandler Carruthc8925912013-01-05 02:09:22 +00003156 // Get the access type of this use. If the use isn't a pointer, we don't
3157 // know what it accesses.
3158 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003159 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3160 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003161 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003162 Type *AddressAccessTy = AddrTy->getElementType();
3163 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003164
Chandler Carruthc8925912013-01-05 02:09:22 +00003165 // Do a match against the root of this address, ignoring profitability. This
3166 // will tell us if the addressing mode for the memory operation will
3167 // *actually* cover the shared instruction.
3168 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003169 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3170 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003171 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003172 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003173 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003174 Matcher.IgnoreProfitability = true;
3175 bool Success = Matcher.MatchAddr(Address, 0);
3176 (void)Success; assert(Success && "Couldn't select *anything*?");
3177
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003178 // The match was to check the profitability, the changes made are not
3179 // part of the original matcher. Therefore, they should be dropped
3180 // otherwise the original matcher will not present the right state.
3181 TPT.rollback(LastKnownGood);
3182
Chandler Carruthc8925912013-01-05 02:09:22 +00003183 // If the match didn't cover I, then it won't be shared by it.
3184 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3185 I) == MatchedAddrModeInsts.end())
3186 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003187
Chandler Carruthc8925912013-01-05 02:09:22 +00003188 MatchedAddrModeInsts.clear();
3189 }
Stephen Lin837bba12013-07-15 17:55:02 +00003190
Chandler Carruthc8925912013-01-05 02:09:22 +00003191 return true;
3192}
3193
3194} // end anonymous namespace
3195
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003196/// IsNonLocalValue - Return true if the specified values are defined in a
3197/// different basic block than BB.
3198static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3199 if (Instruction *I = dyn_cast<Instruction>(V))
3200 return I->getParent() != BB;
3201 return false;
3202}
3203
Bob Wilson53bdae32009-12-03 21:47:07 +00003204/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003205/// addressing modes that can do significant amounts of computation. As such,
3206/// instruction selection will try to get the load or store to do as much
3207/// computation as possible for the program. The problem is that isel can only
3208/// see within a single block. As such, we sink as much legal addressing mode
3209/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003210///
3211/// This method is used to optimize both load/store and inline asms with memory
3212/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003213bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003214 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003215 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003216
3217 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003218 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003219 SmallVector<Value*, 8> worklist;
3220 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003221 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003222
Owen Anderson8ba5f392010-11-27 08:15:55 +00003223 // Use a worklist to iteratively look through PHI nodes, and ensure that
3224 // the addressing mode obtained from the non-PHI roots of the graph
3225 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003226 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003227 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003228 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003229 SmallVector<Instruction*, 16> AddrModeInsts;
3230 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003231 TypePromotionTransaction TPT;
3232 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3233 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003234 while (!worklist.empty()) {
3235 Value *V = worklist.back();
3236 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003237
Owen Anderson8ba5f392010-11-27 08:15:55 +00003238 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003239 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003240 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003241 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003242 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003243
Owen Anderson8ba5f392010-11-27 08:15:55 +00003244 // For a PHI node, push all of its incoming values.
3245 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003246 for (Value *IncValue : P->incoming_values())
3247 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003248 continue;
3249 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003250
Owen Anderson8ba5f392010-11-27 08:15:55 +00003251 // For non-PHIs, determine the addressing mode being computed.
3252 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003253 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003254 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003255 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003256
3257 // This check is broken into two cases with very similar code to avoid using
3258 // getNumUses() as much as possible. Some values have a lot of uses, so
3259 // calling getNumUses() unconditionally caused a significant compile-time
3260 // regression.
3261 if (!Consensus) {
3262 Consensus = V;
3263 AddrMode = NewAddrMode;
3264 AddrModeInsts = NewAddrModeInsts;
3265 continue;
3266 } else if (NewAddrMode == AddrMode) {
3267 if (!IsNumUsesConsensusValid) {
3268 NumUsesConsensus = Consensus->getNumUses();
3269 IsNumUsesConsensusValid = true;
3270 }
3271
3272 // Ensure that the obtained addressing mode is equivalent to that obtained
3273 // for all other roots of the PHI traversal. Also, when choosing one
3274 // such root as representative, select the one with the most uses in order
3275 // to keep the cost modeling heuristics in AddressingModeMatcher
3276 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003277 unsigned NumUses = V->getNumUses();
3278 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003279 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003280 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003281 AddrModeInsts = NewAddrModeInsts;
3282 }
3283 continue;
3284 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003285
Craig Topperc0196b12014-04-14 00:51:57 +00003286 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003287 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003288 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003289
Owen Anderson8ba5f392010-11-27 08:15:55 +00003290 // If the addressing mode couldn't be determined, or if multiple different
3291 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003292 if (!Consensus) {
3293 TPT.rollback(LastKnownGood);
3294 return false;
3295 }
3296 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003297
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003298 // Check to see if any of the instructions supersumed by this addr mode are
3299 // non-local to I's BB.
3300 bool AnyNonLocal = false;
3301 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003302 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003303 AnyNonLocal = true;
3304 break;
3305 }
3306 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003307
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003308 // If all the instructions matched are already in this BB, don't do anything.
3309 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003310 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003311 return false;
3312 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003313
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003314 // Insert this computation right after this user. Since our caller is
3315 // scanning from the top of the BB to the bottom, reuse of the expr are
3316 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003317 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003318
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003319 // Now that we determined the addressing expression we want to use and know
3320 // that we have to sink it into this block. Check to see if we have already
3321 // done this for some other load/store instr in this block. If so, reuse the
3322 // computation.
3323 Value *&SunkAddr = SunkAddrs[Addr];
3324 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003325 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003326 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003327 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003328 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003329 } else if (AddrSinkUsingGEPs ||
3330 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003331 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3332 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003333 // By default, we use the GEP-based method when AA is used later. This
3334 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3335 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003336 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003337 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003338 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003339
3340 // First, find the pointer.
3341 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3342 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003343 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003344 }
3345
3346 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3347 // We can't add more than one pointer together, nor can we scale a
3348 // pointer (both of which seem meaningless).
3349 if (ResultPtr || AddrMode.Scale != 1)
3350 return false;
3351
3352 ResultPtr = AddrMode.ScaledReg;
3353 AddrMode.Scale = 0;
3354 }
3355
3356 if (AddrMode.BaseGV) {
3357 if (ResultPtr)
3358 return false;
3359
3360 ResultPtr = AddrMode.BaseGV;
3361 }
3362
3363 // If the real base value actually came from an inttoptr, then the matcher
3364 // will look through it and provide only the integer value. In that case,
3365 // use it here.
3366 if (!ResultPtr && AddrMode.BaseReg) {
3367 ResultPtr =
3368 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003369 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003370 } else if (!ResultPtr && AddrMode.Scale == 1) {
3371 ResultPtr =
3372 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3373 AddrMode.Scale = 0;
3374 }
3375
3376 if (!ResultPtr &&
3377 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3378 SunkAddr = Constant::getNullValue(Addr->getType());
3379 } else if (!ResultPtr) {
3380 return false;
3381 } else {
3382 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003383 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3384 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003385
3386 // Start with the base register. Do this first so that subsequent address
3387 // matching finds it last, which will prevent it from trying to match it
3388 // as the scaled value in case it happens to be a mul. That would be
3389 // problematic if we've sunk a different mul for the scale, because then
3390 // we'd end up sinking both muls.
3391 if (AddrMode.BaseReg) {
3392 Value *V = AddrMode.BaseReg;
3393 if (V->getType() != IntPtrTy)
3394 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3395
3396 ResultIndex = V;
3397 }
3398
3399 // Add the scale value.
3400 if (AddrMode.Scale) {
3401 Value *V = AddrMode.ScaledReg;
3402 if (V->getType() == IntPtrTy) {
3403 // done.
3404 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3405 cast<IntegerType>(V->getType())->getBitWidth()) {
3406 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3407 } else {
3408 // It is only safe to sign extend the BaseReg if we know that the math
3409 // required to create it did not overflow before we extend it. Since
3410 // the original IR value was tossed in favor of a constant back when
3411 // the AddrMode was created we need to bail out gracefully if widths
3412 // do not match instead of extending it.
3413 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3414 if (I && (ResultIndex != AddrMode.BaseReg))
3415 I->eraseFromParent();
3416 return false;
3417 }
3418
3419 if (AddrMode.Scale != 1)
3420 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3421 "sunkaddr");
3422 if (ResultIndex)
3423 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3424 else
3425 ResultIndex = V;
3426 }
3427
3428 // Add in the Base Offset if present.
3429 if (AddrMode.BaseOffs) {
3430 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3431 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003432 // We need to add this separately from the scale above to help with
3433 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003434 if (ResultPtr->getType() != I8PtrTy)
3435 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003436 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003437 }
3438
3439 ResultIndex = V;
3440 }
3441
3442 if (!ResultIndex) {
3443 SunkAddr = ResultPtr;
3444 } else {
3445 if (ResultPtr->getType() != I8PtrTy)
3446 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003447 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003448 }
3449
3450 if (SunkAddr->getType() != Addr->getType())
3451 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3452 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003453 } else {
David Greene74e2d492010-01-05 01:27:11 +00003454 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003455 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003456 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003457 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003458
3459 // Start with the base register. Do this first so that subsequent address
3460 // matching finds it last, which will prevent it from trying to match it
3461 // as the scaled value in case it happens to be a mul. That would be
3462 // problematic if we've sunk a different mul for the scale, because then
3463 // we'd end up sinking both muls.
3464 if (AddrMode.BaseReg) {
3465 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003466 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003467 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003468 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003469 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003470 Result = V;
3471 }
3472
3473 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003474 if (AddrMode.Scale) {
3475 Value *V = AddrMode.ScaledReg;
3476 if (V->getType() == IntPtrTy) {
3477 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003478 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003479 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003480 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3481 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003482 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003483 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003484 // It is only safe to sign extend the BaseReg if we know that the math
3485 // required to create it did not overflow before we extend it. Since
3486 // the original IR value was tossed in favor of a constant back when
3487 // the AddrMode was created we need to bail out gracefully if widths
3488 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003489 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003490 if (I && (Result != AddrMode.BaseReg))
3491 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003492 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003493 }
3494 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003495 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3496 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003497 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003498 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003499 else
3500 Result = V;
3501 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003502
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003503 // Add in the BaseGV if present.
3504 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003505 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003506 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003507 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003508 else
3509 Result = V;
3510 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003511
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003512 // Add in the Base Offset if present.
3513 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003514 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003515 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003516 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003517 else
3518 Result = V;
3519 }
3520
Craig Topperc0196b12014-04-14 00:51:57 +00003521 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003522 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003523 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003524 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003525 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003526
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003527 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003528
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003529 // If we have no uses, recursively delete the value and all dead instructions
3530 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003531 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003532 // This can cause recursive deletion, which can invalidate our iterator.
3533 // Use a WeakVH to hold onto it in case this happens.
3534 WeakVH IterHandle(CurInstIterator);
3535 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003536
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003537 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003538
3539 if (IterHandle != CurInstIterator) {
3540 // If the iterator instruction was recursively deleted, start over at the
3541 // start of the block.
3542 CurInstIterator = BB->begin();
3543 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003544 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003545 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003546 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003547 return true;
3548}
3549
Evan Cheng1da25002008-02-26 02:42:37 +00003550/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00003551/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00003552/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00003553bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003554 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003555
Eric Christopher11e4df72015-02-26 22:38:43 +00003556 const TargetRegisterInfo *TRI =
3557 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003558 TargetLowering::AsmOperandInfoVector TargetConstraints =
3559 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003560 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003561 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3562 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003563
Evan Cheng1da25002008-02-26 02:42:37 +00003564 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003565 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003566
Eli Friedman666bbe32008-02-26 18:37:49 +00003567 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3568 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003569 Value *OpVal = CS->getArgOperand(ArgNo++);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003570 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003571 } else if (OpInfo.Type == InlineAsm::isInput)
3572 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003573 }
3574
3575 return MadeChange;
3576}
3577
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003578/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3579/// sign extensions.
3580static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3581 assert(!Inst->use_empty() && "Input must have at least one use");
3582 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3583 bool IsSExt = isa<SExtInst>(FirstUser);
3584 Type *ExtTy = FirstUser->getType();
3585 for (const User *U : Inst->users()) {
3586 const Instruction *UI = cast<Instruction>(U);
3587 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3588 return false;
3589 Type *CurTy = UI->getType();
3590 // Same input and output types: Same instruction after CSE.
3591 if (CurTy == ExtTy)
3592 continue;
3593
3594 // If IsSExt is true, we are in this situation:
3595 // a = Inst
3596 // b = sext ty1 a to ty2
3597 // c = sext ty1 a to ty3
3598 // Assuming ty2 is shorter than ty3, this could be turned into:
3599 // a = Inst
3600 // b = sext ty1 a to ty2
3601 // c = sext ty2 b to ty3
3602 // However, the last sext is not free.
3603 if (IsSExt)
3604 return false;
3605
3606 // This is a ZExt, maybe this is free to extend from one type to another.
3607 // In that case, we would not account for a different use.
3608 Type *NarrowTy;
3609 Type *LargeTy;
3610 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3611 CurTy->getScalarType()->getIntegerBitWidth()) {
3612 NarrowTy = CurTy;
3613 LargeTy = ExtTy;
3614 } else {
3615 NarrowTy = ExtTy;
3616 LargeTy = CurTy;
3617 }
3618
3619 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3620 return false;
3621 }
3622 // All uses are the same or can be derived from one another for free.
3623 return true;
3624}
3625
3626/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3627/// load instruction.
3628/// If an ext(load) can be formed, it is returned via \p LI for the load
3629/// and \p Inst for the extension.
3630/// Otherwise LI == nullptr and Inst == nullptr.
3631/// When some promotion happened, \p TPT contains the proper state to
3632/// revert them.
3633///
3634/// \return true when promoting was necessary to expose the ext(load)
3635/// opportunity, false otherwise.
3636///
3637/// Example:
3638/// \code
3639/// %ld = load i32* %addr
3640/// %add = add nuw i32 %ld, 4
3641/// %zext = zext i32 %add to i64
3642/// \endcode
3643/// =>
3644/// \code
3645/// %ld = load i32* %addr
3646/// %zext = zext i32 %ld to i64
3647/// %add = add nuw i64 %zext, 4
3648/// \encode
3649/// Thanks to the promotion, we can match zext(load i32*) to i64.
3650bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3651 LoadInst *&LI, Instruction *&Inst,
3652 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003653 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003654 // Iterate over all the extensions to see if one form an ext(load).
3655 for (auto I : Exts) {
3656 // Check if we directly have ext(load).
3657 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3658 Inst = I;
3659 // No promotion happened here.
3660 return false;
3661 }
3662 // Check whether or not we want to do any promotion.
3663 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3664 continue;
3665 // Get the action to perform the promotion.
3666 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003667 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003668 // Check if we can promote.
3669 if (!TPH)
3670 continue;
3671 // Save the current state.
3672 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3673 TPT.getRestorationPoint();
3674 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003675 unsigned NewCreatedInstsCost = 0;
3676 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003677 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003678 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3679 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003680 assert(PromotedVal &&
3681 "TypePromotionHelper should have filtered out those cases");
3682
3683 // We would be able to merge only one extension in a load.
3684 // Therefore, if we have more than 1 new extension we heuristically
3685 // cut this search path, because it means we degrade the code quality.
3686 // With exactly 2, the transformation is neutral, because we will merge
3687 // one extension but leave one. However, we optimistically keep going,
3688 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003689 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3690 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003691 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00003692 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00003693 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003694 // The promotion is not profitable, rollback to the previous state.
3695 TPT.rollback(LastKnownGood);
3696 continue;
3697 }
3698 // The promotion is profitable.
3699 // Check if it exposes an ext(load).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003700 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
3701 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003702 // If we have created a new extension, i.e., now we have two
3703 // extensions. We must make sure one of them is merged with
3704 // the load, otherwise we may degrade the code quality.
3705 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3706 // Promotion happened.
3707 return true;
3708 // If this does not help to expose an ext(load) then, rollback.
3709 TPT.rollback(LastKnownGood);
3710 }
3711 // None of the extension can form an ext(load).
3712 LI = nullptr;
3713 Inst = nullptr;
3714 return false;
3715}
3716
Dan Gohman99429a02009-10-16 20:59:35 +00003717/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3718/// basic block as the load, unless conditions are unfavorable. This allows
3719/// SelectionDAG to fold the extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003720/// \p I[in/out] the extension may be modified during the process if some
3721/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003722///
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003723bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3724 // Try to promote a chain of computation if it allows to form
3725 // an extended load.
3726 TypePromotionTransaction TPT;
3727 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3728 TPT.getRestorationPoint();
3729 SmallVector<Instruction *, 1> Exts;
3730 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003731 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003732 LoadInst *LI = nullptr;
3733 Instruction *OldExt = I;
3734 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3735 if (!LI || !I) {
3736 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3737 "the code must remain the same");
3738 I = OldExt;
3739 return false;
3740 }
Dan Gohman99429a02009-10-16 20:59:35 +00003741
3742 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003743 // Make the cheap checks first if we did not promote.
3744 // If we promoted, we need to check if it is indeed profitable.
3745 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003746 return false;
3747
Mehdi Amini44ede332015-07-09 02:09:04 +00003748 EVT VT = TLI->getValueType(*DL, I->getType());
3749 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003750
Dan Gohman99429a02009-10-16 20:59:35 +00003751 // If the load has other users and the truncate is not free, this probably
3752 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003753 if (!LI->hasOneUse() && TLI &&
3754 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003755 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3756 I = OldExt;
3757 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003758 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003759 }
Dan Gohman99429a02009-10-16 20:59:35 +00003760
3761 // Check whether the target supports casts folded into loads.
3762 unsigned LType;
3763 if (isa<ZExtInst>(I))
3764 LType = ISD::ZEXTLOAD;
3765 else {
3766 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3767 LType = ISD::SEXTLOAD;
3768 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003769 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003770 I = OldExt;
3771 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003772 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003773 }
Dan Gohman99429a02009-10-16 20:59:35 +00003774
3775 // Move the extend into the same block as the load, so that SelectionDAG
3776 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003777 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003778 I->removeFromParent();
3779 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003780 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003781 return true;
3782}
3783
Evan Chengd3d80172007-12-05 23:58:20 +00003784bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3785 BasicBlock *DefBB = I->getParent();
3786
Bob Wilsonff714f92010-09-21 21:44:14 +00003787 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003788 // other uses of the source with result of extension.
3789 Value *Src = I->getOperand(0);
3790 if (Src->hasOneUse())
3791 return false;
3792
Evan Cheng2011df42007-12-13 07:50:36 +00003793 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003794 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003795 return false;
3796
Evan Cheng7bc89422007-12-12 00:51:06 +00003797 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003798 // this block.
3799 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003800 return false;
3801
Evan Chengd3d80172007-12-05 23:58:20 +00003802 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003803 for (User *U : I->users()) {
3804 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003805
3806 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003807 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003808 if (UserBB == DefBB) continue;
3809 DefIsLiveOut = true;
3810 break;
3811 }
3812 if (!DefIsLiveOut)
3813 return false;
3814
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003815 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003816 for (User *U : Src->users()) {
3817 Instruction *UI = cast<Instruction>(U);
3818 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003819 if (UserBB == DefBB) continue;
3820 // Be conservative. We don't want this xform to end up introducing
3821 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003822 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003823 return false;
3824 }
3825
Evan Chengd3d80172007-12-05 23:58:20 +00003826 // InsertedTruncs - Only insert one trunc in each block once.
3827 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3828
3829 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003830 for (Use &U : Src->uses()) {
3831 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003832
3833 // Figure out which BB this ext is used in.
3834 BasicBlock *UserBB = User->getParent();
3835 if (UserBB == DefBB) continue;
3836
3837 // Both src and def are live in this block. Rewrite the use.
3838 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3839
3840 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003841 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003842 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003843 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003844 }
3845
3846 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003847 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003848 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003849 MadeChange = true;
3850 }
3851
3852 return MadeChange;
3853}
3854
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003855/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3856/// turned into an explicit branch.
3857static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3858 // FIXME: This should use the same heuristics as IfConversion to determine
3859 // whether a select is better represented as a branch. This requires that
3860 // branch probability metadata is preserved for the select, which is not the
3861 // case currently.
3862
3863 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3864
3865 // If the branch is predicted right, an out of order CPU can avoid blocking on
3866 // the compare. Emit cmovs on compares with a memory operand as branches to
3867 // avoid stalls on the load from memory. If the compare has more than one use
3868 // there's probably another cmov or setcc around so it's not worth emitting a
3869 // branch.
3870 if (!Cmp)
3871 return false;
3872
3873 Value *CmpOp0 = Cmp->getOperand(0);
3874 Value *CmpOp1 = Cmp->getOperand(1);
3875
3876 // We check that the memory operand has one use to avoid uses of the loaded
3877 // value directly after the compare, making branches unprofitable.
3878 return Cmp->hasOneUse() &&
3879 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3880 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3881}
3882
3883
Nadav Rotem9d832022012-09-02 12:10:19 +00003884/// If we have a SelectInst that will likely profit from branch prediction,
3885/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003886bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003887 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3888
3889 // Can we convert the 'select' to CF ?
3890 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003891 return false;
3892
Nadav Rotem9d832022012-09-02 12:10:19 +00003893 TargetLowering::SelectSupportKind SelectKind;
3894 if (VectorCond)
3895 SelectKind = TargetLowering::VectorMaskSelect;
3896 else if (SI->getType()->isVectorTy())
3897 SelectKind = TargetLowering::ScalarCondVectorVal;
3898 else
3899 SelectKind = TargetLowering::ScalarValSelect;
3900
3901 // Do we have efficient codegen support for this kind of 'selects' ?
3902 if (TLI->isSelectSupported(SelectKind)) {
3903 // We have efficient codegen support for the select instruction.
3904 // Check if it is profitable to keep this 'select'.
3905 if (!TLI->isPredictableSelectExpensive() ||
3906 !isFormingBranchFromSelectProfitable(SI))
3907 return false;
3908 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003909
3910 ModifiedDT = true;
3911
3912 // First, we split the block containing the select into 2 blocks.
3913 BasicBlock *StartBlock = SI->getParent();
3914 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3915 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3916
3917 // Create a new block serving as the landing pad for the branch.
3918 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3919 NextBlock->getParent(), NextBlock);
3920
3921 // Move the unconditional branch from the block with the select in it into our
3922 // landing pad block.
3923 StartBlock->getTerminator()->eraseFromParent();
3924 BranchInst::Create(NextBlock, SmallBlock);
3925
3926 // Insert the real conditional branch based on the original condition.
3927 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3928
3929 // The select itself is replaced with a PHI Node.
3930 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3931 PN->takeName(SI);
3932 PN->addIncoming(SI->getTrueValue(), StartBlock);
3933 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3934 SI->replaceAllUsesWith(PN);
3935 SI->eraseFromParent();
3936
3937 // Instruct OptimizeBlock to skip to the next block.
3938 CurInstIterator = StartBlock->end();
3939 ++NumSelectsExpanded;
3940 return true;
3941}
3942
Benjamin Kramer573ff362014-03-01 17:24:40 +00003943static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003944 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3945 int SplatElem = -1;
3946 for (unsigned i = 0; i < Mask.size(); ++i) {
3947 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3948 return false;
3949 SplatElem = Mask[i];
3950 }
3951
3952 return true;
3953}
3954
3955/// Some targets have expensive vector shifts if the lanes aren't all the same
3956/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3957/// it's often worth sinking a shufflevector splat down to its use so that
3958/// codegen can spot all lanes are identical.
3959bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3960 BasicBlock *DefBB = SVI->getParent();
3961
3962 // Only do this xform if variable vector shifts are particularly expensive.
3963 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3964 return false;
3965
3966 // We only expect better codegen by sinking a shuffle if we can recognise a
3967 // constant splat.
3968 if (!isBroadcastShuffle(SVI))
3969 return false;
3970
3971 // InsertedShuffles - Only insert a shuffle in each block once.
3972 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3973
3974 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003975 for (User *U : SVI->users()) {
3976 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003977
3978 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003979 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003980 if (UserBB == DefBB) continue;
3981
3982 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003983 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003984
3985 // Everything checks out, sink the shuffle if the user's block doesn't
3986 // already have a copy.
3987 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3988
3989 if (!InsertedShuffle) {
3990 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3991 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3992 SVI->getOperand(1),
3993 SVI->getOperand(2), "", InsertPt);
3994 }
3995
Chandler Carruthcdf47882014-03-09 03:16:01 +00003996 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003997 MadeChange = true;
3998 }
3999
4000 // If we removed all uses, nuke the shuffle.
4001 if (SVI->use_empty()) {
4002 SVI->eraseFromParent();
4003 MadeChange = true;
4004 }
4005
4006 return MadeChange;
4007}
4008
Quentin Colombetc32615d2014-10-31 17:52:53 +00004009namespace {
4010/// \brief Helper class to promote a scalar operation to a vector one.
4011/// This class is used to move downward extractelement transition.
4012/// E.g.,
4013/// a = vector_op <2 x i32>
4014/// b = extractelement <2 x i32> a, i32 0
4015/// c = scalar_op b
4016/// store c
4017///
4018/// =>
4019/// a = vector_op <2 x i32>
4020/// c = vector_op a (equivalent to scalar_op on the related lane)
4021/// * d = extractelement <2 x i32> c, i32 0
4022/// * store d
4023/// Assuming both extractelement and store can be combine, we get rid of the
4024/// transition.
4025class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004026 /// DataLayout associated with the current module.
4027 const DataLayout &DL;
4028
Quentin Colombetc32615d2014-10-31 17:52:53 +00004029 /// Used to perform some checks on the legality of vector operations.
4030 const TargetLowering &TLI;
4031
4032 /// Used to estimated the cost of the promoted chain.
4033 const TargetTransformInfo &TTI;
4034
4035 /// The transition being moved downwards.
4036 Instruction *Transition;
4037 /// The sequence of instructions to be promoted.
4038 SmallVector<Instruction *, 4> InstsToBePromoted;
4039 /// Cost of combining a store and an extract.
4040 unsigned StoreExtractCombineCost;
4041 /// Instruction that will be combined with the transition.
4042 Instruction *CombineInst;
4043
4044 /// \brief The instruction that represents the current end of the transition.
4045 /// Since we are faking the promotion until we reach the end of the chain
4046 /// of computation, we need a way to get the current end of the transition.
4047 Instruction *getEndOfTransition() const {
4048 if (InstsToBePromoted.empty())
4049 return Transition;
4050 return InstsToBePromoted.back();
4051 }
4052
4053 /// \brief Return the index of the original value in the transition.
4054 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4055 /// c, is at index 0.
4056 unsigned getTransitionOriginalValueIdx() const {
4057 assert(isa<ExtractElementInst>(Transition) &&
4058 "Other kind of transitions are not supported yet");
4059 return 0;
4060 }
4061
4062 /// \brief Return the index of the index in the transition.
4063 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4064 /// is at index 1.
4065 unsigned getTransitionIdx() const {
4066 assert(isa<ExtractElementInst>(Transition) &&
4067 "Other kind of transitions are not supported yet");
4068 return 1;
4069 }
4070
4071 /// \brief Get the type of the transition.
4072 /// This is the type of the original value.
4073 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4074 /// transition is <2 x i32>.
4075 Type *getTransitionType() const {
4076 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4077 }
4078
4079 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4080 /// I.e., we have the following sequence:
4081 /// Def = Transition <ty1> a to <ty2>
4082 /// b = ToBePromoted <ty2> Def, ...
4083 /// =>
4084 /// b = ToBePromoted <ty1> a, ...
4085 /// Def = Transition <ty1> ToBePromoted to <ty2>
4086 void promoteImpl(Instruction *ToBePromoted);
4087
4088 /// \brief Check whether or not it is profitable to promote all the
4089 /// instructions enqueued to be promoted.
4090 bool isProfitableToPromote() {
4091 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4092 unsigned Index = isa<ConstantInt>(ValIdx)
4093 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4094 : -1;
4095 Type *PromotedType = getTransitionType();
4096
4097 StoreInst *ST = cast<StoreInst>(CombineInst);
4098 unsigned AS = ST->getPointerAddressSpace();
4099 unsigned Align = ST->getAlignment();
4100 // Check if this store is supported.
4101 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004102 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4103 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004104 // If this is not supported, there is no way we can combine
4105 // the extract with the store.
4106 return false;
4107 }
4108
4109 // The scalar chain of computation has to pay for the transition
4110 // scalar to vector.
4111 // The vector chain has to account for the combining cost.
4112 uint64_t ScalarCost =
4113 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4114 uint64_t VectorCost = StoreExtractCombineCost;
4115 for (const auto &Inst : InstsToBePromoted) {
4116 // Compute the cost.
4117 // By construction, all instructions being promoted are arithmetic ones.
4118 // Moreover, one argument is a constant that can be viewed as a splat
4119 // constant.
4120 Value *Arg0 = Inst->getOperand(0);
4121 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4122 isa<ConstantFP>(Arg0);
4123 TargetTransformInfo::OperandValueKind Arg0OVK =
4124 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4125 : TargetTransformInfo::OK_AnyValue;
4126 TargetTransformInfo::OperandValueKind Arg1OVK =
4127 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4128 : TargetTransformInfo::OK_AnyValue;
4129 ScalarCost += TTI.getArithmeticInstrCost(
4130 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4131 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4132 Arg0OVK, Arg1OVK);
4133 }
4134 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4135 << ScalarCost << "\nVector: " << VectorCost << '\n');
4136 return ScalarCost > VectorCost;
4137 }
4138
4139 /// \brief Generate a constant vector with \p Val with the same
4140 /// number of elements as the transition.
4141 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004142 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004143 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4144 /// otherwise we generate a vector with as many undef as possible:
4145 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4146 /// used at the index of the extract.
4147 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4148 unsigned ExtractIdx = UINT_MAX;
4149 if (!UseSplat) {
4150 // If we cannot determine where the constant must be, we have to
4151 // use a splat constant.
4152 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4153 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4154 ExtractIdx = CstVal->getSExtValue();
4155 else
4156 UseSplat = true;
4157 }
4158
4159 unsigned End = getTransitionType()->getVectorNumElements();
4160 if (UseSplat)
4161 return ConstantVector::getSplat(End, Val);
4162
4163 SmallVector<Constant *, 4> ConstVec;
4164 UndefValue *UndefVal = UndefValue::get(Val->getType());
4165 for (unsigned Idx = 0; Idx != End; ++Idx) {
4166 if (Idx == ExtractIdx)
4167 ConstVec.push_back(Val);
4168 else
4169 ConstVec.push_back(UndefVal);
4170 }
4171 return ConstantVector::get(ConstVec);
4172 }
4173
4174 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4175 /// in \p Use can trigger undefined behavior.
4176 static bool canCauseUndefinedBehavior(const Instruction *Use,
4177 unsigned OperandIdx) {
4178 // This is not safe to introduce undef when the operand is on
4179 // the right hand side of a division-like instruction.
4180 if (OperandIdx != 1)
4181 return false;
4182 switch (Use->getOpcode()) {
4183 default:
4184 return false;
4185 case Instruction::SDiv:
4186 case Instruction::UDiv:
4187 case Instruction::SRem:
4188 case Instruction::URem:
4189 return true;
4190 case Instruction::FDiv:
4191 case Instruction::FRem:
4192 return !Use->hasNoNaNs();
4193 }
4194 llvm_unreachable(nullptr);
4195 }
4196
4197public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004198 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4199 const TargetTransformInfo &TTI, Instruction *Transition,
4200 unsigned CombineCost)
4201 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004202 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4203 assert(Transition && "Do not know how to promote null");
4204 }
4205
4206 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4207 bool canPromote(const Instruction *ToBePromoted) const {
4208 // We could support CastInst too.
4209 return isa<BinaryOperator>(ToBePromoted);
4210 }
4211
4212 /// \brief Check if it is profitable to promote \p ToBePromoted
4213 /// by moving downward the transition through.
4214 bool shouldPromote(const Instruction *ToBePromoted) const {
4215 // Promote only if all the operands can be statically expanded.
4216 // Indeed, we do not want to introduce any new kind of transitions.
4217 for (const Use &U : ToBePromoted->operands()) {
4218 const Value *Val = U.get();
4219 if (Val == getEndOfTransition()) {
4220 // If the use is a division and the transition is on the rhs,
4221 // we cannot promote the operation, otherwise we may create a
4222 // division by zero.
4223 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4224 return false;
4225 continue;
4226 }
4227 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4228 !isa<ConstantFP>(Val))
4229 return false;
4230 }
4231 // Check that the resulting operation is legal.
4232 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4233 if (!ISDOpcode)
4234 return false;
4235 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004236 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004237 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004238 }
4239
4240 /// \brief Check whether or not \p Use can be combined
4241 /// with the transition.
4242 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4243 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4244
4245 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4246 void enqueueForPromotion(Instruction *ToBePromoted) {
4247 InstsToBePromoted.push_back(ToBePromoted);
4248 }
4249
4250 /// \brief Set the instruction that will be combined with the transition.
4251 void recordCombineInstruction(Instruction *ToBeCombined) {
4252 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4253 CombineInst = ToBeCombined;
4254 }
4255
4256 /// \brief Promote all the instructions enqueued for promotion if it is
4257 /// is profitable.
4258 /// \return True if the promotion happened, false otherwise.
4259 bool promote() {
4260 // Check if there is something to promote.
4261 // Right now, if we do not have anything to combine with,
4262 // we assume the promotion is not profitable.
4263 if (InstsToBePromoted.empty() || !CombineInst)
4264 return false;
4265
4266 // Check cost.
4267 if (!StressStoreExtract && !isProfitableToPromote())
4268 return false;
4269
4270 // Promote.
4271 for (auto &ToBePromoted : InstsToBePromoted)
4272 promoteImpl(ToBePromoted);
4273 InstsToBePromoted.clear();
4274 return true;
4275 }
4276};
4277} // End of anonymous namespace.
4278
4279void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4280 // At this point, we know that all the operands of ToBePromoted but Def
4281 // can be statically promoted.
4282 // For Def, we need to use its parameter in ToBePromoted:
4283 // b = ToBePromoted ty1 a
4284 // Def = Transition ty1 b to ty2
4285 // Move the transition down.
4286 // 1. Replace all uses of the promoted operation by the transition.
4287 // = ... b => = ... Def.
4288 assert(ToBePromoted->getType() == Transition->getType() &&
4289 "The type of the result of the transition does not match "
4290 "the final type");
4291 ToBePromoted->replaceAllUsesWith(Transition);
4292 // 2. Update the type of the uses.
4293 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4294 Type *TransitionTy = getTransitionType();
4295 ToBePromoted->mutateType(TransitionTy);
4296 // 3. Update all the operands of the promoted operation with promoted
4297 // operands.
4298 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4299 for (Use &U : ToBePromoted->operands()) {
4300 Value *Val = U.get();
4301 Value *NewVal = nullptr;
4302 if (Val == Transition)
4303 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4304 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4305 isa<ConstantFP>(Val)) {
4306 // Use a splat constant if it is not safe to use undef.
4307 NewVal = getConstantVector(
4308 cast<Constant>(Val),
4309 isa<UndefValue>(Val) ||
4310 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4311 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004312 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4313 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004314 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4315 }
4316 Transition->removeFromParent();
4317 Transition->insertAfter(ToBePromoted);
4318 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4319}
4320
4321/// Some targets can do store(extractelement) with one instruction.
4322/// Try to push the extractelement towards the stores when the target
4323/// has this feature and this is profitable.
4324bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4325 unsigned CombineCost = UINT_MAX;
4326 if (DisableStoreExtract || !TLI ||
4327 (!StressStoreExtract &&
4328 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4329 Inst->getOperand(1), CombineCost)))
4330 return false;
4331
4332 // At this point we know that Inst is a vector to scalar transition.
4333 // Try to move it down the def-use chain, until:
4334 // - We can combine the transition with its single use
4335 // => we got rid of the transition.
4336 // - We escape the current basic block
4337 // => we would need to check that we are moving it at a cheaper place and
4338 // we do not do that for now.
4339 BasicBlock *Parent = Inst->getParent();
4340 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00004341 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00004342 // If the transition has more than one use, assume this is not going to be
4343 // beneficial.
4344 while (Inst->hasOneUse()) {
4345 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4346 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4347
4348 if (ToBePromoted->getParent() != Parent) {
4349 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4350 << ToBePromoted->getParent()->getName()
4351 << ") than the transition (" << Parent->getName() << ").\n");
4352 return false;
4353 }
4354
4355 if (VPH.canCombine(ToBePromoted)) {
4356 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4357 << "will be combined with: " << *ToBePromoted << '\n');
4358 VPH.recordCombineInstruction(ToBePromoted);
4359 bool Changed = VPH.promote();
4360 NumStoreExtractExposed += Changed;
4361 return Changed;
4362 }
4363
4364 DEBUG(dbgs() << "Try promoting.\n");
4365 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4366 return false;
4367
4368 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4369
4370 VPH.enqueueForPromotion(ToBePromoted);
4371 Inst = ToBePromoted;
4372 }
4373 return false;
4374}
4375
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004376bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004377 // Bail out if we inserted the instruction to prevent optimizations from
4378 // stepping on each other's toes.
4379 if (InsertedInsts.count(I))
4380 return false;
4381
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004382 if (PHINode *P = dyn_cast<PHINode>(I)) {
4383 // It is possible for very late stage optimizations (such as SimplifyCFG)
4384 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4385 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00004386 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004387 P->replaceAllUsesWith(V);
4388 P->eraseFromParent();
4389 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004390 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004391 }
Chris Lattneree588de2011-01-15 07:29:01 +00004392 return false;
4393 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004394
Chris Lattneree588de2011-01-15 07:29:01 +00004395 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004396 // If the source of the cast is a constant, then this should have
4397 // already been constant folded. The only reason NOT to constant fold
4398 // it is if something (e.g. LSR) was careful to place the constant
4399 // evaluation in a block other than then one that uses it (e.g. to hoist
4400 // the address of globals out of a loop). If this is the case, we don't
4401 // want to forward-subst the cast.
4402 if (isa<Constant>(CI->getOperand(0)))
4403 return false;
4404
Mehdi Amini44ede332015-07-09 02:09:04 +00004405 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00004406 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004407
Chris Lattneree588de2011-01-15 07:29:01 +00004408 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004409 /// Sink a zext or sext into its user blocks if the target type doesn't
4410 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00004411 if (TLI &&
4412 TLI->getTypeAction(CI->getContext(),
4413 TLI->getValueType(*DL, CI->getType())) ==
4414 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004415 return SinkCast(CI);
4416 } else {
4417 bool MadeChange = MoveExtToFormExtLoad(I);
4418 return MadeChange | OptimizeExtUses(I);
4419 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004420 }
Chris Lattneree588de2011-01-15 07:29:01 +00004421 return false;
4422 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004423
Chris Lattneree588de2011-01-15 07:29:01 +00004424 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004425 if (!TLI || !TLI->hasMultipleConditionRegisters())
4426 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004427
Chris Lattneree588de2011-01-15 07:29:01 +00004428 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004429 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004430 if (TLI) {
4431 unsigned AS = LI->getPointerAddressSpace();
4432 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
4433 }
Hans Wennborgf3254832012-10-30 11:23:25 +00004434 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004435 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004436
Chris Lattneree588de2011-01-15 07:29:01 +00004437 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004438 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004439 if (TLI) {
4440 unsigned AS = SI->getPointerAddressSpace();
Chris Lattneree588de2011-01-15 07:29:01 +00004441 return OptimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004442 SI->getOperand(0)->getType(), AS);
4443 }
Chris Lattneree588de2011-01-15 07:29:01 +00004444 return false;
4445 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004446
Yi Jiangd069f632014-04-21 19:34:27 +00004447 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4448
4449 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4450 BinOp->getOpcode() == Instruction::LShr)) {
4451 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4452 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00004453 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00004454
4455 return false;
4456 }
4457
Chris Lattneree588de2011-01-15 07:29:01 +00004458 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004459 if (GEPI->hasAllZeroIndices()) {
4460 /// The GEP operand must be a pointer, so must its result -> BitCast
4461 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4462 GEPI->getName(), GEPI);
4463 GEPI->replaceAllUsesWith(NC);
4464 GEPI->eraseFromParent();
4465 ++NumGEPsElim;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004466 OptimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004467 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004468 }
Chris Lattneree588de2011-01-15 07:29:01 +00004469 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004470 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004471
Chris Lattneree588de2011-01-15 07:29:01 +00004472 if (CallInst *CI = dyn_cast<CallInst>(I))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004473 return OptimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004474
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004475 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4476 return OptimizeSelectInst(SI);
4477
Tim Northoveraeb8e062014-02-19 10:02:43 +00004478 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4479 return OptimizeShuffleVectorInst(SVI);
4480
Quentin Colombetc32615d2014-10-31 17:52:53 +00004481 if (isa<ExtractElementInst>(I))
4482 return OptimizeExtractElementInst(I);
4483
Chris Lattneree588de2011-01-15 07:29:01 +00004484 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004485}
4486
Chris Lattnerf2836d12007-03-31 04:06:36 +00004487// In this pass we look for GEP and cast instructions that are used
4488// across basic blocks and rewrite them to improve basic-block-at-a-time
4489// selection.
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004490bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004491 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004492 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004493
Chris Lattner7a277142011-01-15 07:14:54 +00004494 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004495 while (CurInstIterator != BB.end()) {
4496 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4497 if (ModifiedDT)
4498 return true;
4499 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00004500 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4501
Chris Lattnerf2836d12007-03-31 04:06:36 +00004502 return MadeChange;
4503}
Devang Patel53771ba2011-08-18 00:50:51 +00004504
4505// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004506// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004507// find a node corresponding to the value.
4508bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4509 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004510 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004511 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004512 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithe90f1162015-01-08 21:07:55 +00004513 Instruction *Insn = BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00004514 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004515 // Leave dbg.values that refer to an alloca alone. These
4516 // instrinsics describe the address of a variable (= the alloca)
4517 // being taken. They should not be moved next to the alloca
4518 // (and to the beginning of the scope), but rather stay close to
4519 // where said address is used.
4520 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004521 PrevNonDbgInst = Insn;
4522 continue;
4523 }
4524
4525 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4526 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4527 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4528 DVI->removeFromParent();
4529 if (isa<PHINode>(VI))
4530 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4531 else
4532 DVI->insertAfter(VI);
4533 MadeChange = true;
4534 ++NumDbgValueMoved;
4535 }
4536 }
4537 }
4538 return MadeChange;
4539}
Tim Northovercea0abb2014-03-29 08:22:29 +00004540
4541// If there is a sequence that branches based on comparing a single bit
4542// against zero that can be combined into a single instruction, and the
4543// target supports folding these into a single instruction, sink the
4544// mask and compare into the branch uses. Do this before OptimizeBlock ->
4545// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4546// searched for.
4547bool CodeGenPrepare::sinkAndCmp(Function &F) {
4548 if (!EnableAndCmpSinking)
4549 return false;
4550 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4551 return false;
4552 bool MadeChange = false;
4553 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4554 BasicBlock *BB = I++;
4555
4556 // Does this BB end with the following?
4557 // %andVal = and %val, #single-bit-set
4558 // %icmpVal = icmp %andResult, 0
4559 // br i1 %cmpVal label %dest1, label %dest2"
4560 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4561 if (!Brcc || !Brcc->isConditional())
4562 continue;
4563 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4564 if (!Cmp || Cmp->getParent() != BB)
4565 continue;
4566 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4567 if (!Zero || !Zero->isZero())
4568 continue;
4569 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4570 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4571 continue;
4572 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4573 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4574 continue;
4575 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4576
4577 // Push the "and; icmp" for any users that are conditional branches.
4578 // Since there can only be one branch use per BB, we don't need to keep
4579 // track of which BBs we insert into.
4580 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4581 UI != E; ) {
4582 Use &TheUse = *UI;
4583 // Find brcc use.
4584 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4585 ++UI;
4586 if (!BrccUser || !BrccUser->isConditional())
4587 continue;
4588 BasicBlock *UserBB = BrccUser->getParent();
4589 if (UserBB == BB) continue;
4590 DEBUG(dbgs() << "found Brcc use\n");
4591
4592 // Sink the "and; icmp" to use.
4593 MadeChange = true;
4594 BinaryOperator *NewAnd =
4595 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4596 BrccUser);
4597 CmpInst *NewCmp =
4598 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4599 "", BrccUser);
4600 TheUse = NewCmp;
4601 ++NumAndCmpsMoved;
4602 DEBUG(BrccUser->getParent()->dump());
4603 }
4604 }
4605 return MadeChange;
4606}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004607
Juergen Ributzka194350a2014-12-09 17:32:12 +00004608/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4609/// success, or returns false if no or invalid metadata was found.
4610static bool extractBranchMetadata(BranchInst *BI,
4611 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4612 assert(BI->isConditional() &&
4613 "Looking for probabilities on unconditional branch?");
4614 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4615 if (!ProfileData || ProfileData->getNumOperands() != 3)
4616 return false;
4617
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004618 const auto *CITrue =
4619 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4620 const auto *CIFalse =
4621 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004622 if (!CITrue || !CIFalse)
4623 return false;
4624
4625 ProbTrue = CITrue->getValue().getZExtValue();
4626 ProbFalse = CIFalse->getValue().getZExtValue();
4627
4628 return true;
4629}
4630
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004631/// \brief Scale down both weights to fit into uint32_t.
4632static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4633 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4634 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4635 NewTrue = NewTrue / Scale;
4636 NewFalse = NewFalse / Scale;
4637}
4638
4639/// \brief Some targets prefer to split a conditional branch like:
4640/// \code
4641/// %0 = icmp ne i32 %a, 0
4642/// %1 = icmp ne i32 %b, 0
4643/// %or.cond = or i1 %0, %1
4644/// br i1 %or.cond, label %TrueBB, label %FalseBB
4645/// \endcode
4646/// into multiple branch instructions like:
4647/// \code
4648/// bb1:
4649/// %0 = icmp ne i32 %a, 0
4650/// br i1 %0, label %TrueBB, label %bb2
4651/// bb2:
4652/// %1 = icmp ne i32 %b, 0
4653/// br i1 %1, label %TrueBB, label %FalseBB
4654/// \endcode
4655/// This usually allows instruction selection to do even further optimizations
4656/// and combine the compare with the branch instruction. Currently this is
4657/// applied for targets which have "cheap" jump instructions.
4658///
4659/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4660///
4661bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00004662 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004663 return false;
4664
4665 bool MadeChange = false;
4666 for (auto &BB : F) {
4667 // Does this BB end with the following?
4668 // %cond1 = icmp|fcmp|binary instruction ...
4669 // %cond2 = icmp|fcmp|binary instruction ...
4670 // %cond.or = or|and i1 %cond1, cond2
4671 // br i1 %cond.or label %dest1, label %dest2"
4672 BinaryOperator *LogicOp;
4673 BasicBlock *TBB, *FBB;
4674 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4675 continue;
4676
Sanjay Patel42574202015-09-02 19:23:23 +00004677 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4678 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
4679 continue;
4680
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004681 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004682 Value *Cond1, *Cond2;
4683 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4684 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004685 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004686 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4687 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004688 Opc = Instruction::Or;
4689 else
4690 continue;
4691
4692 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4693 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4694 continue;
4695
4696 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4697
4698 // Create a new BB.
4699 auto *InsertBefore = std::next(Function::iterator(BB))
4700 .getNodePtrUnchecked();
4701 auto TmpBB = BasicBlock::Create(BB.getContext(),
4702 BB.getName() + ".cond.split",
4703 BB.getParent(), InsertBefore);
4704
4705 // Update original basic block by using the first condition directly by the
4706 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004707 Br1->setCondition(Cond1);
4708 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004709
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004710 // Depending on the conditon we have to either replace the true or the false
4711 // successor of the original branch instruction.
4712 if (Opc == Instruction::And)
4713 Br1->setSuccessor(0, TmpBB);
4714 else
4715 Br1->setSuccessor(1, TmpBB);
4716
4717 // Fill in the new basic block.
4718 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004719 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4720 I->removeFromParent();
4721 I->insertBefore(Br2);
4722 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004723
4724 // Update PHI nodes in both successors. The original BB needs to be
4725 // replaced in one succesor's PHI nodes, because the branch comes now from
4726 // the newly generated BB (NewBB). In the other successor we need to add one
4727 // incoming edge to the PHI nodes, because both branch instructions target
4728 // now the same successor. Depending on the original branch condition
4729 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4730 // we perfrom the correct update for the PHI nodes.
4731 // This doesn't change the successor order of the just created branch
4732 // instruction (or any other instruction).
4733 if (Opc == Instruction::Or)
4734 std::swap(TBB, FBB);
4735
4736 // Replace the old BB with the new BB.
4737 for (auto &I : *TBB) {
4738 PHINode *PN = dyn_cast<PHINode>(&I);
4739 if (!PN)
4740 break;
4741 int i;
4742 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4743 PN->setIncomingBlock(i, TmpBB);
4744 }
4745
4746 // Add another incoming edge form the new BB.
4747 for (auto &I : *FBB) {
4748 PHINode *PN = dyn_cast<PHINode>(&I);
4749 if (!PN)
4750 break;
4751 auto *Val = PN->getIncomingValueForBlock(&BB);
4752 PN->addIncoming(Val, TmpBB);
4753 }
4754
4755 // Update the branch weights (from SelectionDAGBuilder::
4756 // FindMergedConditions).
4757 if (Opc == Instruction::Or) {
4758 // Codegen X | Y as:
4759 // BB1:
4760 // jmp_if_X TBB
4761 // jmp TmpBB
4762 // TmpBB:
4763 // jmp_if_Y TBB
4764 // jmp FBB
4765 //
4766
4767 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4768 // The requirement is that
4769 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4770 // = TrueProb for orignal BB.
4771 // Assuming the orignal weights are A and B, one choice is to set BB1's
4772 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4773 // assumes that
4774 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4775 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4776 // TmpBB, but the math is more complicated.
4777 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004778 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004779 uint64_t NewTrueWeight = TrueWeight;
4780 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4781 scaleWeights(NewTrueWeight, NewFalseWeight);
4782 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4783 .createBranchWeights(TrueWeight, FalseWeight));
4784
4785 NewTrueWeight = TrueWeight;
4786 NewFalseWeight = 2 * FalseWeight;
4787 scaleWeights(NewTrueWeight, NewFalseWeight);
4788 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4789 .createBranchWeights(TrueWeight, FalseWeight));
4790 }
4791 } else {
4792 // Codegen X & Y as:
4793 // BB1:
4794 // jmp_if_X TmpBB
4795 // jmp FBB
4796 // TmpBB:
4797 // jmp_if_Y TBB
4798 // jmp FBB
4799 //
4800 // This requires creation of TmpBB after CurBB.
4801
4802 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4803 // The requirement is that
4804 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4805 // = FalseProb for orignal BB.
4806 // Assuming the orignal weights are A and B, one choice is to set BB1's
4807 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4808 // assumes that
4809 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4810 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004811 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004812 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4813 uint64_t NewFalseWeight = FalseWeight;
4814 scaleWeights(NewTrueWeight, NewFalseWeight);
4815 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4816 .createBranchWeights(TrueWeight, FalseWeight));
4817
4818 NewTrueWeight = 2 * TrueWeight;
4819 NewFalseWeight = FalseWeight;
4820 scaleWeights(NewTrueWeight, NewFalseWeight);
4821 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4822 .createBranchWeights(TrueWeight, FalseWeight));
4823 }
4824 }
4825
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004826 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00004827 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004828 ModifiedDT = true;
4829
4830 MadeChange = true;
4831
4832 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4833 TmpBB->dump());
4834 }
4835 return MadeChange;
4836}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004837
4838void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
4839 if (auto *InvariantMD = I.getMetadata("invariant.group"))
4840 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
4841}