blob: a4e382d9c85884c86f886758128ba695af4a647e [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000024#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000030#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000035#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000036#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000037#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000038#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000039#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000040#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000041#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000042#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000044#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000045#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000048#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000050#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000051using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000052using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000053
Chandler Carruth1b9dde02014-04-22 02:02:50 +000054#define DEBUG_TYPE "codegenprepare"
55
Cameron Zwarichced753f2011-01-05 17:27:27 +000056STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000057STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
58STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000059STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
60 "sunken Cmps");
61STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
62 "of sunken Casts");
63STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
64 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000065STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
66STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000067STATISTIC(NumAndsAdded,
68 "Number of and mask instructions added to form ext loads");
69STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000070STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000071STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000072STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000073STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000074STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000075
Cameron Zwarich338d3622011-03-11 21:52:04 +000076static cl::opt<bool> DisableBranchOpts(
77 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
78 cl::desc("Disable branch optimizations in CodeGenPrepare"));
79
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000080static cl::opt<bool>
81 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
82 cl::desc("Disable GC optimizations in CodeGenPrepare"));
83
Benjamin Kramer3d38c172012-05-06 14:25:16 +000084static cl::opt<bool> DisableSelectToBranch(
85 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
86 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000087
Hal Finkelc3998302014-04-12 00:59:48 +000088static cl::opt<bool> AddrSinkUsingGEPs(
89 "addr-sink-using-gep", cl::Hidden, cl::init(false),
90 cl::desc("Address sinking in CGP using GEPs."));
91
Tim Northovercea0abb2014-03-29 08:22:29 +000092static cl::opt<bool> EnableAndCmpSinking(
93 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
94 cl::desc("Enable sinkinig and/cmp into branches."));
95
Quentin Colombetc32615d2014-10-31 17:52:53 +000096static cl::opt<bool> DisableStoreExtract(
97 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
98 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
99
100static cl::opt<bool> StressStoreExtract(
101 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
102 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
103
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000104static cl::opt<bool> DisableExtLdPromotion(
105 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
106 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
107 "CodeGenPrepare"));
108
109static cl::opt<bool> StressExtLdPromotion(
110 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
111 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
112 "optimization in CodeGenPrepare"));
113
Eric Christopherc1ea1492008-09-24 05:32:41 +0000114namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000115typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000116typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000117typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000118class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000119
Chris Lattner2dd09db2009-09-02 06:11:42 +0000120 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000121 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000122 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000123 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000124 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000125
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000126 /// As we scan instructions optimizing them, this is the next instruction
127 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000128 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000129
Evan Cheng0663f232011-03-21 01:19:09 +0000130 /// Keeps track of non-local addresses that have been sunk into a block.
131 /// This allows us to avoid inserting duplicate code for blocks with
132 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000133 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000134
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000135 /// Keeps track of all instructions inserted for the current function.
136 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000137 /// Keeps track of the type of the related instruction before their
138 /// promotion for the current function.
139 InstrToOrigTy PromotedInsts;
140
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000141 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000142 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000143
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000144 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000145 bool OptSize;
146
Mehdi Amini4fe37982015-07-07 18:45:17 +0000147 /// DataLayout for the Function being processed.
148 const DataLayout *DL;
149
Chris Lattnerf2836d12007-03-31 04:06:36 +0000150 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000151 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000152 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000153 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000154 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
155 }
Craig Topper4584cd52014-03-07 09:26:03 +0000156 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000157
Craig Topper4584cd52014-03-07 09:26:03 +0000158 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000159
Craig Topper4584cd52014-03-07 09:26:03 +0000160 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000161 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000162 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000163 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000164 }
165
Chris Lattnerf2836d12007-03-31 04:06:36 +0000166 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000167 bool eliminateFallThrough(Function &F);
168 bool eliminateMostlyEmptyBlocks(Function &F);
169 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
170 void eliminateMostlyEmptyBlock(BasicBlock *BB);
171 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
172 bool optimizeInst(Instruction *I, bool& ModifiedDT);
173 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000174 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000175 bool optimizeInlineAsmInst(CallInst *CS);
176 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
177 bool moveExtToFormExtLoad(Instruction *&I);
178 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000179 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000180 bool optimizeSelectInst(SelectInst *SI);
181 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000182 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000183 bool optimizeExtractElementInst(Instruction *Inst);
184 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
185 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000186 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000187 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000188 Instruction *&Inst,
189 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000190 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000191 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000192 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000193 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000194 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000195}
Devang Patel09f162c2007-05-01 21:15:47 +0000196
Devang Patel8c78a0b2007-05-03 01:11:54 +0000197char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000198INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
199 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000200
Bill Wendling7a639ea2013-06-19 21:07:11 +0000201FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
202 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000203}
204
Chris Lattnerf2836d12007-03-31 04:06:36 +0000205bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000206 if (skipOptnoneFunction(F))
207 return false;
208
Mehdi Amini4fe37982015-07-07 18:45:17 +0000209 DL = &F.getParent()->getDataLayout();
210
Chris Lattnerf2836d12007-03-31 04:06:36 +0000211 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000212 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000213 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000214 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000215
Devang Patel8f606d72011-03-24 15:35:25 +0000216 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000217 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000218 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000219 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000220 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000221 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000222
Preston Gurdcdf540d2012-09-04 18:22:17 +0000223 /// This optimization identifies DIV instructions that can be
224 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000225 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000226 const DenseMap<unsigned int, unsigned int> &BypassWidths =
227 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000228 BasicBlock* BB = &*F.begin();
229 while (BB != nullptr) {
230 // bypassSlowDivision may create new BBs, but we don't want to reapply the
231 // optimization to those blocks.
232 BasicBlock* Next = BB->getNextNode();
233 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
234 BB = Next;
235 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000236 }
237
238 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000239 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000240 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000241
Devang Patel53771ba2011-08-18 00:50:51 +0000242 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000243 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000244 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000245 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000246
Tim Northovercea0abb2014-03-29 08:22:29 +0000247 // If there is a mask, compare against zero, and branch that can be combined
248 // into a single target instruction, push the mask and compare into branch
249 // users. Do this before OptimizeBlock -> OptimizeInst ->
250 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000251 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000252 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000253 EverMadeChange |= splitBranchCondition(F);
254 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000255
Chris Lattnerc3748562007-04-02 01:35:34 +0000256 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000257 while (MadeChange) {
258 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000259 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000260 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000261 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000262 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000263
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000264 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000265 if (ModifiedDTOnIteration)
266 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000267 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000268 EverMadeChange |= MadeChange;
269 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000270
271 SunkAddrs.clear();
272
Cameron Zwarich338d3622011-03-11 21:52:04 +0000273 if (!DisableBranchOpts) {
274 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000275 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000276 for (BasicBlock &BB : F) {
277 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
278 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000279 if (!MadeChange) continue;
280
281 for (SmallVectorImpl<BasicBlock*>::iterator
282 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
283 if (pred_begin(*II) == pred_end(*II))
284 WorkList.insert(*II);
285 }
286
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000287 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000288 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000289 while (!WorkList.empty()) {
290 BasicBlock *BB = *WorkList.begin();
291 WorkList.erase(BB);
292 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
293
294 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000295
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000296 for (SmallVectorImpl<BasicBlock*>::iterator
297 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
298 if (pred_begin(*II) == pred_end(*II))
299 WorkList.insert(*II);
300 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000301
Nadav Rotem70409992012-08-14 05:19:07 +0000302 // Merge pairs of basic blocks with unconditional branches, connected by
303 // a single edge.
304 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000305 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000306
Cameron Zwarich338d3622011-03-11 21:52:04 +0000307 EverMadeChange |= MadeChange;
308 }
309
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000310 if (!DisableGCOpts) {
311 SmallVector<Instruction *, 2> Statepoints;
312 for (BasicBlock &BB : F)
313 for (Instruction &I : BB)
314 if (isStatepoint(I))
315 Statepoints.push_back(&I);
316 for (auto &I : Statepoints)
317 EverMadeChange |= simplifyOffsetableRelocate(*I);
318 }
319
Chris Lattnerf2836d12007-03-31 04:06:36 +0000320 return EverMadeChange;
321}
322
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000323/// Merge basic blocks which are connected by a single edge, where one of the
324/// basic blocks has a single successor pointing to the other basic block,
325/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000326bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000327 bool Changed = false;
328 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000329 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000330 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000331 // If the destination block has a single pred, then this is a trivial
332 // edge, just collapse it.
333 BasicBlock *SinglePred = BB->getSinglePredecessor();
334
Evan Cheng64a223a2012-09-28 23:58:57 +0000335 // Don't merge if BB's address is taken.
336 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000337
338 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
339 if (Term && !Term->isConditional()) {
340 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000341 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000342 // Remember if SinglePred was the entry block of the function.
343 // If so, we will need to move BB back to the entry position.
344 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000345 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000346
347 if (isEntry && BB != &BB->getParent()->getEntryBlock())
348 BB->moveBefore(&BB->getParent()->getEntryBlock());
349
350 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000351 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000352 }
353 }
354 return Changed;
355}
356
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000357/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
358/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
359/// edges in ways that are non-optimal for isel. Start by eliminating these
360/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000361bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000362 bool MadeChange = false;
363 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000364 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000365 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000366
367 // If this block doesn't end with an uncond branch, ignore it.
368 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
369 if (!BI || !BI->isUnconditional())
370 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000371
Dale Johannesen4026b042009-03-27 01:13:37 +0000372 // If the instruction before the branch (skipping debug info) isn't a phi
373 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000374 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 if (BBI != BB->begin()) {
376 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000377 while (isa<DbgInfoIntrinsic>(BBI)) {
378 if (BBI == BB->begin())
379 break;
380 --BBI;
381 }
382 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
383 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000385
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 // Do not break infinite loops.
387 BasicBlock *DestBB = BI->getSuccessor(0);
388 if (DestBB == BB)
389 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000390
Sanjay Patelfc580a62015-09-21 23:03:16 +0000391 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000392 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000393
Sanjay Patelfc580a62015-09-21 23:03:16 +0000394 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000395 MadeChange = true;
396 }
397 return MadeChange;
398}
399
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000400/// Return true if we can merge BB into DestBB if there is a single
401/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000402/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000403bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000404 const BasicBlock *DestBB) const {
405 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
406 // the successor. If there are more complex condition (e.g. preheaders),
407 // don't mess around with them.
408 BasicBlock::const_iterator BBI = BB->begin();
409 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000410 for (const User *U : PN->users()) {
411 const Instruction *UI = cast<Instruction>(U);
412 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000413 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000414 // If User is inside DestBB block and it is a PHINode then check
415 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000416 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000417 if (UI->getParent() == DestBB) {
418 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000419 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
420 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
421 if (Insn && Insn->getParent() == BB &&
422 Insn->getParent() != UPN->getIncomingBlock(I))
423 return false;
424 }
425 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 }
427 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000428
Chris Lattnerc3748562007-04-02 01:35:34 +0000429 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
430 // and DestBB may have conflicting incoming values for the block. If so, we
431 // can't merge the block.
432 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
433 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000434
Chris Lattnerc3748562007-04-02 01:35:34 +0000435 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000436 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000437 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
438 // It is faster to get preds from a PHI than with pred_iterator.
439 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
440 BBPreds.insert(BBPN->getIncomingBlock(i));
441 } else {
442 BBPreds.insert(pred_begin(BB), pred_end(BB));
443 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000444
Chris Lattnerc3748562007-04-02 01:35:34 +0000445 // Walk the preds of DestBB.
446 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
447 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
448 if (BBPreds.count(Pred)) { // Common predecessor?
449 BBI = DestBB->begin();
450 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
451 const Value *V1 = PN->getIncomingValueForBlock(Pred);
452 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000453
Chris Lattnerc3748562007-04-02 01:35:34 +0000454 // If V2 is a phi node in BB, look up what the mapped value will be.
455 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
456 if (V2PN->getParent() == BB)
457 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000458
Chris Lattnerc3748562007-04-02 01:35:34 +0000459 // If there is a conflict, bail out.
460 if (V1 != V2) return false;
461 }
462 }
463 }
464
465 return true;
466}
467
468
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000469/// Eliminate a basic block that has only phi's and an unconditional branch in
470/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000471void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000472 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
473 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000474
David Greene74e2d492010-01-05 01:27:11 +0000475 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000476
Chris Lattnerc3748562007-04-02 01:35:34 +0000477 // If the destination block has a single pred, then this is a trivial edge,
478 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000479 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000480 if (SinglePred != DestBB) {
481 // Remember if SinglePred was the entry block of the function. If so, we
482 // will need to move BB back to the entry position.
483 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000484 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000485
Chris Lattner8a172da2008-11-28 19:54:49 +0000486 if (isEntry && BB != &BB->getParent()->getEntryBlock())
487 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000488
David Greene74e2d492010-01-05 01:27:11 +0000489 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000490 return;
491 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000492 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000493
Chris Lattnerc3748562007-04-02 01:35:34 +0000494 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
495 // to handle the new incoming edges it is about to have.
496 PHINode *PN;
497 for (BasicBlock::iterator BBI = DestBB->begin();
498 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
499 // Remove the incoming value for BB, and remember it.
500 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000501
Chris Lattnerc3748562007-04-02 01:35:34 +0000502 // Two options: either the InVal is a phi node defined in BB or it is some
503 // value that dominates BB.
504 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
505 if (InValPhi && InValPhi->getParent() == BB) {
506 // Add all of the input values of the input PHI as inputs of this phi.
507 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
508 PN->addIncoming(InValPhi->getIncomingValue(i),
509 InValPhi->getIncomingBlock(i));
510 } else {
511 // Otherwise, add one instance of the dominating value for each edge that
512 // we will be adding.
513 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
514 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
515 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
516 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000517 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
518 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000519 }
520 }
521 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000522
Chris Lattnerc3748562007-04-02 01:35:34 +0000523 // The PHIs are now updated, change everything that refers to BB to use
524 // DestBB and remove BB.
525 BB->replaceAllUsesWith(DestBB);
526 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000527 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000528
David Greene74e2d492010-01-05 01:27:11 +0000529 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000530}
531
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000532// Computes a map of base pointer relocation instructions to corresponding
533// derived pointer relocation instructions given a vector of all relocate calls
534static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000535 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
536 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
537 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000538 // Collect information in two maps: one primarily for locating the base object
539 // while filling the second map; the second map is the final structure holding
540 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000541 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
542 for (auto *ThisRelocate : AllRelocateCalls) {
543 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
544 ThisRelocate->getDerivedPtrIndex());
545 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000546 }
547 for (auto &Item : RelocateIdxMap) {
548 std::pair<unsigned, unsigned> Key = Item.first;
549 if (Key.first == Key.second)
550 // Base relocation: nothing to insert
551 continue;
552
Manuel Jacob83eefa62016-01-05 04:03:00 +0000553 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000554 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000555
556 // We're iterating over RelocateIdxMap so we cannot modify it.
557 auto MaybeBase = RelocateIdxMap.find(BaseKey);
558 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000559 // TODO: We might want to insert a new base object relocate and gep off
560 // that, if there are enough derived object relocates.
561 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000562
563 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000564 }
565}
566
567// Accepts a GEP and extracts the operands into a vector provided they're all
568// small integer constants
569static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
570 SmallVectorImpl<Value *> &OffsetV) {
571 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
572 // Only accept small constant integer operands
573 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
574 if (!Op || Op->getZExtValue() > 20)
575 return false;
576 }
577
578 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
579 OffsetV.push_back(GEP->getOperand(i));
580 return true;
581}
582
583// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
584// replace, computes a replacement, and affects it.
585static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000586simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
587 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000588 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000589 for (GCRelocateInst *ToReplace : Targets) {
590 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000591 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000592 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000593 // A duplicate relocate call. TODO: coalesce duplicates.
594 continue;
595 }
596
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000597 if (RelocatedBase->getParent() != ToReplace->getParent()) {
598 // Base and derived relocates are in different basic blocks.
599 // In this case transform is only valid when base dominates derived
600 // relocate. However it would be too expensive to check dominance
601 // for each such relocate, so we skip the whole transformation.
602 continue;
603 }
604
Manuel Jacob83eefa62016-01-05 04:03:00 +0000605 Value *Base = ToReplace->getBasePtr();
606 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000607 if (!Derived || Derived->getPointerOperand() != Base)
608 continue;
609
610 SmallVector<Value *, 2> OffsetV;
611 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
612 continue;
613
614 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000615 assert(RelocatedBase->getNextNode() &&
616 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000617
618 // Insert after RelocatedBase
619 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000620 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000621
622 // If gc_relocate does not match the actual type, cast it to the right type.
623 // In theory, there must be a bitcast after gc_relocate if the type does not
624 // match, and we should reuse it to get the derived pointer. But it could be
625 // cases like this:
626 // bb1:
627 // ...
628 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
629 // br label %merge
630 //
631 // bb2:
632 // ...
633 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
634 // br label %merge
635 //
636 // merge:
637 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
638 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
639 //
640 // In this case, we can not find the bitcast any more. So we insert a new bitcast
641 // no matter there is already one or not. In this way, we can handle all cases, and
642 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000643 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000644 if (RelocatedBase->getType() != Base->getType()) {
645 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000646 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000647 }
David Blaikie68d535c2015-03-24 22:38:16 +0000648 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000649 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000650 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000651 // If the newly generated derived pointer's type does not match the original derived
652 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000653 Value *ActualReplacement = Replacement;
654 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000655 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000656 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000657 }
658 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000659 ToReplace->eraseFromParent();
660
661 MadeChange = true;
662 }
663 return MadeChange;
664}
665
666// Turns this:
667//
668// %base = ...
669// %ptr = gep %base + 15
670// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
671// %base' = relocate(%tok, i32 4, i32 4)
672// %ptr' = relocate(%tok, i32 4, i32 5)
673// %val = load %ptr'
674//
675// into this:
676//
677// %base = ...
678// %ptr = gep %base + 15
679// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
680// %base' = gc.relocate(%tok, i32 4, i32 4)
681// %ptr' = gep %base' + 15
682// %val = load %ptr'
683bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
684 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000685 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000686
687 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000688 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000689 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000690 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000691
692 // We need atleast one base pointer relocation + one derived pointer
693 // relocation to mangle
694 if (AllRelocateCalls.size() < 2)
695 return false;
696
697 // RelocateInstMap is a mapping from the base relocate instruction to the
698 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000699 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000700 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
701 if (RelocateInstMap.empty())
702 return false;
703
704 for (auto &Item : RelocateInstMap)
705 // Item.first is the RelocatedBase to offset against
706 // Item.second is the vector of Targets to replace
707 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
708 return MadeChange;
709}
710
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000711/// SinkCast - Sink the specified cast instruction into its user blocks
712static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000713 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000714
Chris Lattnerf2836d12007-03-31 04:06:36 +0000715 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000716 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000717
Chris Lattnerf2836d12007-03-31 04:06:36 +0000718 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000719 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000720 UI != E; ) {
721 Use &TheUse = UI.getUse();
722 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000723
Chris Lattnerf2836d12007-03-31 04:06:36 +0000724 // Figure out which BB this cast is used in. For PHI's this is the
725 // appropriate predecessor block.
726 BasicBlock *UserBB = User->getParent();
727 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000728 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000729 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000730
Chris Lattnerf2836d12007-03-31 04:06:36 +0000731 // Preincrement use iterator so we don't invalidate it.
732 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000733
Andrew Kaylord0430e82015-11-23 19:16:15 +0000734 // If the block selected to receive the cast is an EH pad that does not
735 // allow non-PHI instructions before the terminator, we can't sink the
736 // cast.
737 if (UserBB->getTerminator()->isEHPad())
738 continue;
739
Chris Lattnerf2836d12007-03-31 04:06:36 +0000740 // If this user is in the same block as the cast, don't change the cast.
741 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000742
Chris Lattnerf2836d12007-03-31 04:06:36 +0000743 // If we have already inserted a cast into this block, use it.
744 CastInst *&InsertedCast = InsertedCasts[UserBB];
745
746 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000747 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000748 assert(InsertPt != UserBB->end());
749 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
750 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000751 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000752
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000753 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000754 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000755 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000756 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000757 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000758
Chris Lattnerf2836d12007-03-31 04:06:36 +0000759 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000760 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000761 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000762 MadeChange = true;
763 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000764
Chris Lattnerf2836d12007-03-31 04:06:36 +0000765 return MadeChange;
766}
767
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000768/// If the specified cast instruction is a noop copy (e.g. it's casting from
769/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
770/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000771///
772/// Return true if any changes are made.
773///
Mehdi Amini44ede332015-07-09 02:09:04 +0000774static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
775 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000776 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000777 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
778 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000779
780 // This is an fp<->int conversion?
781 if (SrcVT.isInteger() != DstVT.isInteger())
782 return false;
783
784 // If this is an extension, it will be a zero or sign extension, which
785 // isn't a noop.
786 if (SrcVT.bitsLT(DstVT)) return false;
787
788 // If these values will be promoted, find out what they will be promoted
789 // to. This helps us consider truncates on PPC as noop copies when they
790 // are.
791 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
792 TargetLowering::TypePromoteInteger)
793 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
794 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
795 TargetLowering::TypePromoteInteger)
796 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
797
798 // If, after promotion, these are the same types, this is a noop copy.
799 if (SrcVT != DstVT)
800 return false;
801
802 return SinkCast(CI);
803}
804
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000805/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
806/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000807///
808/// Return true if any changes were made.
809static bool CombineUAddWithOverflow(CmpInst *CI) {
810 Value *A, *B;
811 Instruction *AddI;
812 if (!match(CI,
813 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
814 return false;
815
816 Type *Ty = AddI->getType();
817 if (!isa<IntegerType>(Ty))
818 return false;
819
820 // We don't want to move around uses of condition values this late, so we we
821 // check if it is legal to create the call to the intrinsic in the basic
822 // block containing the icmp:
823
824 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
825 return false;
826
827#ifndef NDEBUG
828 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
829 // for now:
830 if (AddI->hasOneUse())
831 assert(*AddI->user_begin() == CI && "expected!");
832#endif
833
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000834 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000835 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
836
837 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
838
839 auto *UAddWithOverflow =
840 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
841 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
842 auto *Overflow =
843 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
844
845 CI->replaceAllUsesWith(Overflow);
846 AddI->replaceAllUsesWith(UAdd);
847 CI->eraseFromParent();
848 AddI->eraseFromParent();
849 return true;
850}
851
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000852/// Sink the given CmpInst into user blocks to reduce the number of virtual
853/// registers that must be created and coalesced. This is a clear win except on
854/// targets with multiple condition code registers (PowerPC), where it might
855/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000856///
857/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000858static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000859 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000860
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000861 /// Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000862 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000863
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000864 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000865 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000866 UI != E; ) {
867 Use &TheUse = UI.getUse();
868 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000869
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000870 // Preincrement use iterator so we don't invalidate it.
871 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000872
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000873 // Don't bother for PHI nodes.
874 if (isa<PHINode>(User))
875 continue;
876
877 // Figure out which BB this cmp is used in.
878 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000879
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000880 // If this user is in the same block as the cmp, don't change the cmp.
881 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000882
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000883 // If we have already inserted a cmp into this block, use it.
884 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
885
886 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000887 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000888 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000889 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000890 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
891 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000892 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000893
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000894 // Replace a use of the cmp with a use of the new cmp.
895 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000896 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000897 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000898 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000899
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000900 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000901 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000902 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000903 MadeChange = true;
904 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000905
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000906 return MadeChange;
907}
908
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000909static bool OptimizeCmpExpression(CmpInst *CI) {
910 if (SinkCmpExpression(CI))
911 return true;
912
913 if (CombineUAddWithOverflow(CI))
914 return true;
915
916 return false;
917}
918
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000919/// Check if the candidates could be combined with a shift instruction, which
920/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000921/// 1. Truncate instruction
922/// 2. And instruction and the imm is a mask of the low bits:
923/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000924static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000925 if (!isa<TruncInst>(User)) {
926 if (User->getOpcode() != Instruction::And ||
927 !isa<ConstantInt>(User->getOperand(1)))
928 return false;
929
Quentin Colombetd4f44692014-04-22 01:20:34 +0000930 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000931
Quentin Colombetd4f44692014-04-22 01:20:34 +0000932 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000933 return false;
934 }
935 return true;
936}
937
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000938/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000939static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000940SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
941 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000942 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000943 BasicBlock *UserBB = User->getParent();
944 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
945 TruncInst *TruncI = dyn_cast<TruncInst>(User);
946 bool MadeChange = false;
947
948 for (Value::user_iterator TruncUI = TruncI->user_begin(),
949 TruncE = TruncI->user_end();
950 TruncUI != TruncE;) {
951
952 Use &TruncTheUse = TruncUI.getUse();
953 Instruction *TruncUser = cast<Instruction>(*TruncUI);
954 // Preincrement use iterator so we don't invalidate it.
955
956 ++TruncUI;
957
958 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
959 if (!ISDOpcode)
960 continue;
961
Tim Northovere2239ff2014-07-29 10:20:22 +0000962 // If the use is actually a legal node, there will not be an
963 // implicit truncate.
964 // FIXME: always querying the result type is just an
965 // approximation; some nodes' legality is determined by the
966 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000967 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000968 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000969 continue;
970
971 // Don't bother for PHI nodes.
972 if (isa<PHINode>(TruncUser))
973 continue;
974
975 BasicBlock *TruncUserBB = TruncUser->getParent();
976
977 if (UserBB == TruncUserBB)
978 continue;
979
980 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
981 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
982
983 if (!InsertedShift && !InsertedTrunc) {
984 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000985 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000986 // Sink the shift
987 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000988 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
989 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000990 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000991 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
992 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000993
994 // Sink the trunc
995 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
996 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000997 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000998
999 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001000 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001001
1002 MadeChange = true;
1003
1004 TruncTheUse = InsertedTrunc;
1005 }
1006 }
1007 return MadeChange;
1008}
1009
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001010/// Sink the shift *right* instruction into user blocks if the uses could
1011/// potentially be combined with this shift instruction and generate BitExtract
1012/// instruction. It will only be applied if the architecture supports BitExtract
1013/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001014/// BB1:
1015/// %x.extract.shift = lshr i64 %arg1, 32
1016/// BB2:
1017/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1018/// ==>
1019///
1020/// BB2:
1021/// %x.extract.shift.1 = lshr i64 %arg1, 32
1022/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1023///
1024/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1025/// instruction.
1026/// Return true if any changes are made.
1027static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001028 const TargetLowering &TLI,
1029 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001030 BasicBlock *DefBB = ShiftI->getParent();
1031
1032 /// Only insert instructions in each block once.
1033 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1034
Mehdi Amini44ede332015-07-09 02:09:04 +00001035 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001036
1037 bool MadeChange = false;
1038 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1039 UI != E;) {
1040 Use &TheUse = UI.getUse();
1041 Instruction *User = cast<Instruction>(*UI);
1042 // Preincrement use iterator so we don't invalidate it.
1043 ++UI;
1044
1045 // Don't bother for PHI nodes.
1046 if (isa<PHINode>(User))
1047 continue;
1048
1049 if (!isExtractBitsCandidateUse(User))
1050 continue;
1051
1052 BasicBlock *UserBB = User->getParent();
1053
1054 if (UserBB == DefBB) {
1055 // If the shift and truncate instruction are in the same BB. The use of
1056 // the truncate(TruncUse) may still introduce another truncate if not
1057 // legal. In this case, we would like to sink both shift and truncate
1058 // instruction to the BB of TruncUse.
1059 // for example:
1060 // BB1:
1061 // i64 shift.result = lshr i64 opnd, imm
1062 // trunc.result = trunc shift.result to i16
1063 //
1064 // BB2:
1065 // ----> We will have an implicit truncate here if the architecture does
1066 // not have i16 compare.
1067 // cmp i16 trunc.result, opnd2
1068 //
1069 if (isa<TruncInst>(User) && shiftIsLegal
1070 // If the type of the truncate is legal, no trucate will be
1071 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001072 &&
1073 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001074 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001075 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001076
1077 continue;
1078 }
1079 // If we have already inserted a shift into this block, use it.
1080 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1081
1082 if (!InsertedShift) {
1083 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001084 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001085
1086 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001087 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1088 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001089 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001090 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1091 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001092
1093 MadeChange = true;
1094 }
1095
1096 // Replace a use of the shift with a use of the new shift.
1097 TheUse = InsertedShift;
1098 }
1099
1100 // If we removed all uses, nuke the shift.
1101 if (ShiftI->use_empty())
1102 ShiftI->eraseFromParent();
1103
1104 return MadeChange;
1105}
1106
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001107// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001108// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1109// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001110// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001111// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001112//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001113// %1 = bitcast i8* %addr to i32*
1114// %2 = extractelement <16 x i1> %mask, i32 0
1115// %3 = icmp eq i1 %2, true
1116// br i1 %3, label %cond.load, label %else
1117//
1118//cond.load: ; preds = %0
1119// %4 = getelementptr i32* %1, i32 0
1120// %5 = load i32* %4
1121// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1122// br label %else
1123//
1124//else: ; preds = %0, %cond.load
1125// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1126// %7 = extractelement <16 x i1> %mask, i32 1
1127// %8 = icmp eq i1 %7, true
1128// br i1 %8, label %cond.load1, label %else2
1129//
1130//cond.load1: ; preds = %else
1131// %9 = getelementptr i32* %1, i32 1
1132// %10 = load i32* %9
1133// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1134// br label %else2
1135//
1136//else2: ; preds = %else, %cond.load1
1137// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1138// %12 = extractelement <16 x i1> %mask, i32 2
1139// %13 = icmp eq i1 %12, true
1140// br i1 %13, label %cond.load4, label %else5
1141//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001142static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001143 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001144 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001145 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001146 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001147
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001148 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1149 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001150 assert(VecType && "Unexpected return type of masked load intrinsic");
1151
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001152 Type *EltTy = CI->getType()->getVectorElementType();
1153
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001154 IRBuilder<> Builder(CI->getContext());
1155 Instruction *InsertPt = CI;
1156 BasicBlock *IfBlock = CI->getParent();
1157 BasicBlock *CondBlock = nullptr;
1158 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001159
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001160 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001161 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1162
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001163 // Short-cut if the mask is all-true.
1164 bool IsAllOnesMask = isa<Constant>(Mask) &&
1165 cast<Constant>(Mask)->isAllOnesValue();
1166
1167 if (IsAllOnesMask) {
1168 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1169 CI->replaceAllUsesWith(NewI);
1170 CI->eraseFromParent();
1171 return;
1172 }
1173
1174 // Adjust alignment for the scalar instruction.
1175 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001176 // Bitcast %addr fron i8* to EltTy*
1177 Type *NewPtrType =
1178 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1179 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001180 unsigned VectorWidth = VecType->getNumElements();
1181
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001182 Value *UndefVal = UndefValue::get(VecType);
1183
1184 // The result vector
1185 Value *VResult = UndefVal;
1186
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001187 if (isa<ConstantVector>(Mask)) {
1188 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1189 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1190 continue;
1191 Value *Gep =
1192 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1193 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1194 VResult = Builder.CreateInsertElement(VResult, Load,
1195 Builder.getInt32(Idx));
1196 }
1197 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1198 CI->replaceAllUsesWith(NewI);
1199 CI->eraseFromParent();
1200 return;
1201 }
1202
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001203 PHINode *Phi = nullptr;
1204 Value *PrevPhi = UndefVal;
1205
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001206 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1207
1208 // Fill the "else" block, created in the previous iteration
1209 //
1210 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1211 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1212 // %to_load = icmp eq i1 %mask_1, true
1213 // br i1 %to_load, label %cond.load, label %else
1214 //
1215 if (Idx > 0) {
1216 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1217 Phi->addIncoming(VResult, CondBlock);
1218 Phi->addIncoming(PrevPhi, PrevIfBlock);
1219 PrevPhi = Phi;
1220 VResult = Phi;
1221 }
1222
1223 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1224 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1225 ConstantInt::get(Predicate->getType(), 1));
1226
1227 // Create "cond" block
1228 //
1229 // %EltAddr = getelementptr i32* %1, i32 0
1230 // %Elt = load i32* %EltAddr
1231 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1232 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001233 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001234 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001235
1236 Value *Gep =
1237 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001238 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001239 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1240
1241 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001242 BasicBlock *NewIfBlock =
1243 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001244 Builder.SetInsertPoint(InsertPt);
1245 Instruction *OldBr = IfBlock->getTerminator();
1246 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1247 OldBr->eraseFromParent();
1248 PrevIfBlock = IfBlock;
1249 IfBlock = NewIfBlock;
1250 }
1251
1252 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1253 Phi->addIncoming(VResult, CondBlock);
1254 Phi->addIncoming(PrevPhi, PrevIfBlock);
1255 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1256 CI->replaceAllUsesWith(NewI);
1257 CI->eraseFromParent();
1258}
1259
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001260// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001261// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1262// <16 x i1> %mask)
1263// to a chain of basic blocks, that stores element one-by-one if
1264// the appropriate mask bit is set
1265//
1266// %1 = bitcast i8* %addr to i32*
1267// %2 = extractelement <16 x i1> %mask, i32 0
1268// %3 = icmp eq i1 %2, true
1269// br i1 %3, label %cond.store, label %else
1270//
1271// cond.store: ; preds = %0
1272// %4 = extractelement <16 x i32> %val, i32 0
1273// %5 = getelementptr i32* %1, i32 0
1274// store i32 %4, i32* %5
1275// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001276//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001277// else: ; preds = %0, %cond.store
1278// %6 = extractelement <16 x i1> %mask, i32 1
1279// %7 = icmp eq i1 %6, true
1280// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001281//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001282// cond.store1: ; preds = %else
1283// %8 = extractelement <16 x i32> %val, i32 1
1284// %9 = getelementptr i32* %1, i32 1
1285// store i32 %8, i32* %9
1286// br label %else2
1287// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001288static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001289 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001290 Value *Ptr = CI->getArgOperand(1);
1291 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001292 Value *Mask = CI->getArgOperand(3);
1293
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001294 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001295 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001296 assert(VecType && "Unexpected data type in masked store intrinsic");
1297
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001298 Type *EltTy = VecType->getElementType();
1299
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001300 IRBuilder<> Builder(CI->getContext());
1301 Instruction *InsertPt = CI;
1302 BasicBlock *IfBlock = CI->getParent();
1303 Builder.SetInsertPoint(InsertPt);
1304 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1305
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001306 // Short-cut if the mask is all-true.
1307 bool IsAllOnesMask = isa<Constant>(Mask) &&
1308 cast<Constant>(Mask)->isAllOnesValue();
1309
1310 if (IsAllOnesMask) {
1311 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1312 CI->eraseFromParent();
1313 return;
1314 }
1315
1316 // Adjust alignment for the scalar instruction.
1317 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001318 // Bitcast %addr fron i8* to EltTy*
1319 Type *NewPtrType =
1320 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1321 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001322 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001323
1324 if (isa<ConstantVector>(Mask)) {
1325 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1326 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1327 continue;
1328 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1329 Value *Gep =
1330 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1331 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1332 }
1333 CI->eraseFromParent();
1334 return;
1335 }
1336
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001337 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1338
1339 // Fill the "else" block, created in the previous iteration
1340 //
1341 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1342 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001343 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001344 //
1345 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1346 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1347 ConstantInt::get(Predicate->getType(), 1));
1348
1349 // Create "cond" block
1350 //
1351 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1352 // %EltAddr = getelementptr i32* %1, i32 0
1353 // %store i32 %OneElt, i32* %EltAddr
1354 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001355 BasicBlock *CondBlock =
1356 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001357 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001358
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001359 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001360 Value *Gep =
1361 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001362 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001363
1364 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001365 BasicBlock *NewIfBlock =
1366 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001367 Builder.SetInsertPoint(InsertPt);
1368 Instruction *OldBr = IfBlock->getTerminator();
1369 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1370 OldBr->eraseFromParent();
1371 IfBlock = NewIfBlock;
1372 }
1373 CI->eraseFromParent();
1374}
1375
Elena Demikhovsky09285852015-10-25 15:37:55 +00001376// Translate a masked gather intrinsic like
1377// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1378// <16 x i1> %Mask, <16 x i32> %Src)
1379// to a chain of basic blocks, with loading element one-by-one if
1380// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001381//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001382// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1383// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1384// % ToLoad0 = icmp eq i1 % Mask0, true
1385// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001386//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001387// cond.load:
1388// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1389// % Load0 = load i32, i32* % Ptr0, align 4
1390// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1391// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001392//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001393// else:
1394// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1395// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1396// % ToLoad1 = icmp eq i1 % Mask1, true
1397// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001398//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001399// cond.load1:
1400// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1401// % Load1 = load i32, i32* % Ptr1, align 4
1402// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1403// br label %else2
1404// . . .
1405// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1406// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001407static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001408 Value *Ptrs = CI->getArgOperand(0);
1409 Value *Alignment = CI->getArgOperand(1);
1410 Value *Mask = CI->getArgOperand(2);
1411 Value *Src0 = CI->getArgOperand(3);
1412
1413 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1414
1415 assert(VecType && "Unexpected return type of masked load intrinsic");
1416
1417 IRBuilder<> Builder(CI->getContext());
1418 Instruction *InsertPt = CI;
1419 BasicBlock *IfBlock = CI->getParent();
1420 BasicBlock *CondBlock = nullptr;
1421 BasicBlock *PrevIfBlock = CI->getParent();
1422 Builder.SetInsertPoint(InsertPt);
1423 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1424
1425 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1426
1427 Value *UndefVal = UndefValue::get(VecType);
1428
1429 // The result vector
1430 Value *VResult = UndefVal;
1431 unsigned VectorWidth = VecType->getNumElements();
1432
1433 // Shorten the way if the mask is a vector of constants.
1434 bool IsConstMask = isa<ConstantVector>(Mask);
1435
1436 if (IsConstMask) {
1437 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1438 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1439 continue;
1440 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1441 "Ptr" + Twine(Idx));
1442 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1443 "Load" + Twine(Idx));
1444 VResult = Builder.CreateInsertElement(VResult, Load,
1445 Builder.getInt32(Idx),
1446 "Res" + Twine(Idx));
1447 }
1448 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1449 CI->replaceAllUsesWith(NewI);
1450 CI->eraseFromParent();
1451 return;
1452 }
1453
1454 PHINode *Phi = nullptr;
1455 Value *PrevPhi = UndefVal;
1456
1457 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1458
1459 // Fill the "else" block, created in the previous iteration
1460 //
1461 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1462 // %ToLoad1 = icmp eq i1 %Mask1, true
1463 // br i1 %ToLoad1, label %cond.load, label %else
1464 //
1465 if (Idx > 0) {
1466 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1467 Phi->addIncoming(VResult, CondBlock);
1468 Phi->addIncoming(PrevPhi, PrevIfBlock);
1469 PrevPhi = Phi;
1470 VResult = Phi;
1471 }
1472
1473 Value *Predicate = Builder.CreateExtractElement(Mask,
1474 Builder.getInt32(Idx),
1475 "Mask" + Twine(Idx));
1476 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1477 ConstantInt::get(Predicate->getType(), 1),
1478 "ToLoad" + Twine(Idx));
1479
1480 // Create "cond" block
1481 //
1482 // %EltAddr = getelementptr i32* %1, i32 0
1483 // %Elt = load i32* %EltAddr
1484 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1485 //
1486 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1487 Builder.SetInsertPoint(InsertPt);
1488
1489 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1490 "Ptr" + Twine(Idx));
1491 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1492 "Load" + Twine(Idx));
1493 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1494 "Res" + Twine(Idx));
1495
1496 // Create "else" block, fill it in the next iteration
1497 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1498 Builder.SetInsertPoint(InsertPt);
1499 Instruction *OldBr = IfBlock->getTerminator();
1500 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1501 OldBr->eraseFromParent();
1502 PrevIfBlock = IfBlock;
1503 IfBlock = NewIfBlock;
1504 }
1505
1506 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1507 Phi->addIncoming(VResult, CondBlock);
1508 Phi->addIncoming(PrevPhi, PrevIfBlock);
1509 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1510 CI->replaceAllUsesWith(NewI);
1511 CI->eraseFromParent();
1512}
1513
1514// Translate a masked scatter intrinsic, like
1515// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1516// <16 x i1> %Mask)
1517// to a chain of basic blocks, that stores element one-by-one if
1518// the appropriate mask bit is set.
1519//
1520// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1521// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1522// % ToStore0 = icmp eq i1 % Mask0, true
1523// br i1 %ToStore0, label %cond.store, label %else
1524//
1525// cond.store:
1526// % Elt0 = extractelement <16 x i32> %Src, i32 0
1527// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1528// store i32 %Elt0, i32* % Ptr0, align 4
1529// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001530//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001531// else:
1532// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1533// % ToStore1 = icmp eq i1 % Mask1, true
1534// br i1 % ToStore1, label %cond.store1, label %else2
1535//
1536// cond.store1:
1537// % Elt1 = extractelement <16 x i32> %Src, i32 1
1538// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1539// store i32 % Elt1, i32* % Ptr1, align 4
1540// br label %else2
1541// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001542static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001543 Value *Src = CI->getArgOperand(0);
1544 Value *Ptrs = CI->getArgOperand(1);
1545 Value *Alignment = CI->getArgOperand(2);
1546 Value *Mask = CI->getArgOperand(3);
1547
1548 assert(isa<VectorType>(Src->getType()) &&
1549 "Unexpected data type in masked scatter intrinsic");
1550 assert(isa<VectorType>(Ptrs->getType()) &&
1551 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1552 "Vector of pointers is expected in masked scatter intrinsic");
1553
1554 IRBuilder<> Builder(CI->getContext());
1555 Instruction *InsertPt = CI;
1556 BasicBlock *IfBlock = CI->getParent();
1557 Builder.SetInsertPoint(InsertPt);
1558 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1559
1560 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1561 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1562
1563 // Shorten the way if the mask is a vector of constants.
1564 bool IsConstMask = isa<ConstantVector>(Mask);
1565
1566 if (IsConstMask) {
1567 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1568 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1569 continue;
1570 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1571 "Elt" + Twine(Idx));
1572 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1573 "Ptr" + Twine(Idx));
1574 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1575 }
1576 CI->eraseFromParent();
1577 return;
1578 }
1579 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1580 // Fill the "else" block, created in the previous iteration
1581 //
1582 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1583 // % ToStore = icmp eq i1 % Mask1, true
1584 // br i1 % ToStore, label %cond.store, label %else
1585 //
1586 Value *Predicate = Builder.CreateExtractElement(Mask,
1587 Builder.getInt32(Idx),
1588 "Mask" + Twine(Idx));
1589 Value *Cmp =
1590 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1591 ConstantInt::get(Predicate->getType(), 1),
1592 "ToStore" + Twine(Idx));
1593
1594 // Create "cond" block
1595 //
1596 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1597 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1598 // %store i32 % Elt1, i32* % Ptr1
1599 //
1600 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1601 Builder.SetInsertPoint(InsertPt);
1602
1603 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1604 "Elt" + Twine(Idx));
1605 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1606 "Ptr" + Twine(Idx));
1607 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1608
1609 // Create "else" block, fill it in the next iteration
1610 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1611 Builder.SetInsertPoint(InsertPt);
1612 Instruction *OldBr = IfBlock->getTerminator();
1613 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1614 OldBr->eraseFromParent();
1615 IfBlock = NewIfBlock;
1616 }
1617 CI->eraseFromParent();
1618}
1619
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001620/// If counting leading or trailing zeros is an expensive operation and a zero
1621/// input is defined, add a check for zero to avoid calling the intrinsic.
1622///
1623/// We want to transform:
1624/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1625///
1626/// into:
1627/// entry:
1628/// %cmpz = icmp eq i64 %A, 0
1629/// br i1 %cmpz, label %cond.end, label %cond.false
1630/// cond.false:
1631/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1632/// br label %cond.end
1633/// cond.end:
1634/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1635///
1636/// If the transform is performed, return true and set ModifiedDT to true.
1637static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1638 const TargetLowering *TLI,
1639 const DataLayout *DL,
1640 bool &ModifiedDT) {
1641 if (!TLI || !DL)
1642 return false;
1643
1644 // If a zero input is undefined, it doesn't make sense to despeculate that.
1645 if (match(CountZeros->getOperand(1), m_One()))
1646 return false;
1647
1648 // If it's cheap to speculate, there's nothing to do.
1649 auto IntrinsicID = CountZeros->getIntrinsicID();
1650 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1651 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1652 return false;
1653
1654 // Only handle legal scalar cases. Anything else requires too much work.
1655 Type *Ty = CountZeros->getType();
1656 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1657 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
1658 return false;
1659
1660 // The intrinsic will be sunk behind a compare against zero and branch.
1661 BasicBlock *StartBlock = CountZeros->getParent();
1662 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1663
1664 // Create another block after the count zero intrinsic. A PHI will be added
1665 // in this block to select the result of the intrinsic or the bit-width
1666 // constant if the input to the intrinsic is zero.
1667 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1668 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1669
1670 // Set up a builder to create a compare, conditional branch, and PHI.
1671 IRBuilder<> Builder(CountZeros->getContext());
1672 Builder.SetInsertPoint(StartBlock->getTerminator());
1673 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1674
1675 // Replace the unconditional branch that was created by the first split with
1676 // a compare against zero and a conditional branch.
1677 Value *Zero = Constant::getNullValue(Ty);
1678 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1679 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1680 StartBlock->getTerminator()->eraseFromParent();
1681
1682 // Create a PHI in the end block to select either the output of the intrinsic
1683 // or the bit width of the operand.
1684 Builder.SetInsertPoint(&EndBlock->front());
1685 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1686 CountZeros->replaceAllUsesWith(PN);
1687 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1688 PN->addIncoming(BitWidth, StartBlock);
1689 PN->addIncoming(CountZeros, CallBlock);
1690
1691 // We are explicitly handling the zero case, so we can set the intrinsic's
1692 // undefined zero argument to 'true'. This will also prevent reprocessing the
1693 // intrinsic; we only despeculate when a zero input is defined.
1694 CountZeros->setArgOperand(1, Builder.getTrue());
1695 ModifiedDT = true;
1696 return true;
1697}
1698
Sanjay Patelfc580a62015-09-21 23:03:16 +00001699bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001700 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001701
Chris Lattner7a277142011-01-15 07:14:54 +00001702 // Lower inline assembly if we can.
1703 // If we found an inline asm expession, and if the target knows how to
1704 // lower it to normal LLVM code, do so now.
1705 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1706 if (TLI->ExpandInlineAsm(CI)) {
1707 // Avoid invalidating the iterator.
1708 CurInstIterator = BB->begin();
1709 // Avoid processing instructions out of order, which could cause
1710 // reuse before a value is defined.
1711 SunkAddrs.clear();
1712 return true;
1713 }
1714 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001715 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001716 return true;
1717 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001718
John Brawn0dbcd652015-03-18 12:01:59 +00001719 // Align the pointer arguments to this call if the target thinks it's a good
1720 // idea
1721 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001722 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001723 for (auto &Arg : CI->arg_operands()) {
1724 // We want to align both objects whose address is used directly and
1725 // objects whose address is used in casts and GEPs, though it only makes
1726 // sense for GEPs if the offset is a multiple of the desired alignment and
1727 // if size - offset meets the size threshold.
1728 if (!Arg->getType()->isPointerTy())
1729 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001730 APInt Offset(DL->getPointerSizeInBits(
1731 cast<PointerType>(Arg->getType())->getAddressSpace()),
1732 0);
1733 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001734 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001735 if ((Offset2 & (PrefAlign-1)) != 0)
1736 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001737 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001738 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1739 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001740 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001741 // Global variables can only be aligned if they are defined in this
1742 // object (i.e. they are uniquely initialized in this object), and
1743 // over-aligning global variables that have an explicit section is
1744 // forbidden.
1745 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001746 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
1747 GV->getAlignment() < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001748 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001749 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001750 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001751 }
1752 // If this is a memcpy (or similar) then we may be able to improve the
1753 // alignment
1754 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001755 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001756 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001757 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001758 if (Align > MI->getAlignment())
1759 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001760 }
1761 }
1762
Eric Christopher4b7948e2010-03-11 02:41:03 +00001763 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001764 if (II) {
1765 switch (II->getIntrinsicID()) {
1766 default: break;
1767 case Intrinsic::objectsize: {
1768 // Lower all uses of llvm.objectsize.*
1769 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1770 Type *ReturnTy = CI->getType();
1771 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001772
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001773 // Substituting this can cause recursive simplifications, which can
1774 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1775 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001776 Value *CurValue = &*CurInstIterator;
1777 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001778
Sanjay Patel545a4562016-01-20 18:59:16 +00001779 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001780
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001781 // If the iterator instruction was recursively deleted, start over at the
1782 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001783 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001784 CurInstIterator = BB->begin();
1785 SunkAddrs.clear();
1786 }
1787 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001788 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001789 case Intrinsic::masked_load: {
1790 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001791 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001792 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001793 ModifiedDT = true;
1794 return true;
1795 }
1796 return false;
1797 }
1798 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001799 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001800 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001801 ModifiedDT = true;
1802 return true;
1803 }
1804 return false;
1805 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001806 case Intrinsic::masked_gather: {
1807 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001808 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001809 ModifiedDT = true;
1810 return true;
1811 }
1812 return false;
1813 }
1814 case Intrinsic::masked_scatter: {
1815 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001816 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001817 ModifiedDT = true;
1818 return true;
1819 }
1820 return false;
1821 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001822 case Intrinsic::aarch64_stlxr:
1823 case Intrinsic::aarch64_stxr: {
1824 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1825 if (!ExtVal || !ExtVal->hasOneUse() ||
1826 ExtVal->getParent() == CI->getParent())
1827 return false;
1828 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1829 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001830 // Mark this instruction as "inserted by CGP", so that other
1831 // optimizations don't touch it.
1832 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001833 return true;
1834 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001835 case Intrinsic::invariant_group_barrier:
1836 II->replaceAllUsesWith(II->getArgOperand(0));
1837 II->eraseFromParent();
1838 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001839
1840 case Intrinsic::cttz:
1841 case Intrinsic::ctlz:
1842 // If counting zeros is expensive, try to avoid it.
1843 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001844 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001845
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001846 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001847 // Unknown address space.
1848 // TODO: Target hook to pick which address space the intrinsic cares
1849 // about?
1850 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001851 SmallVector<Value*, 2> PtrOps;
1852 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001853 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001854 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001855 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001856 return true;
1857 }
Pete Cooper615fd892012-03-13 20:59:56 +00001858 }
1859
Eric Christopher4b7948e2010-03-11 02:41:03 +00001860 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001861 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001862
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001863 // Lower all default uses of _chk calls. This is very similar
1864 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001865 // to fortified library functions (e.g. __memcpy_chk) that have the default
1866 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001867 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001868 if (Value *V = Simplifier.optimizeCall(CI)) {
1869 CI->replaceAllUsesWith(V);
1870 CI->eraseFromParent();
1871 return true;
1872 }
1873 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001874}
Chris Lattner1b93be52011-01-15 07:25:29 +00001875
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001876/// Look for opportunities to duplicate return instructions to the predecessor
1877/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001878/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001879/// bb0:
1880/// %tmp0 = tail call i32 @f0()
1881/// br label %return
1882/// bb1:
1883/// %tmp1 = tail call i32 @f1()
1884/// br label %return
1885/// bb2:
1886/// %tmp2 = tail call i32 @f2()
1887/// br label %return
1888/// return:
1889/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1890/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001891/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001892///
1893/// =>
1894///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001895/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001896/// bb0:
1897/// %tmp0 = tail call i32 @f0()
1898/// ret i32 %tmp0
1899/// bb1:
1900/// %tmp1 = tail call i32 @f1()
1901/// ret i32 %tmp1
1902/// bb2:
1903/// %tmp2 = tail call i32 @f2()
1904/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001905/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001906bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001907 if (!TLI)
1908 return false;
1909
Benjamin Kramer455fa352012-11-23 19:17:06 +00001910 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1911 if (!RI)
1912 return false;
1913
Craig Topperc0196b12014-04-14 00:51:57 +00001914 PHINode *PN = nullptr;
1915 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001916 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001917 if (V) {
1918 BCI = dyn_cast<BitCastInst>(V);
1919 if (BCI)
1920 V = BCI->getOperand(0);
1921
1922 PN = dyn_cast<PHINode>(V);
1923 if (!PN)
1924 return false;
1925 }
Evan Cheng0663f232011-03-21 01:19:09 +00001926
Cameron Zwarich4649f172011-03-24 04:52:10 +00001927 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001928 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001929
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001930 // It's not safe to eliminate the sign / zero extension of the return value.
1931 // See llvm::isInTailCallPosition().
1932 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001933 AttributeSet CallerAttrs = F->getAttributes();
1934 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1935 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001936 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001937
Cameron Zwarich4649f172011-03-24 04:52:10 +00001938 // Make sure there are no instructions between the PHI and return, or that the
1939 // return is the first instruction in the block.
1940 if (PN) {
1941 BasicBlock::iterator BI = BB->begin();
1942 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001943 if (&*BI == BCI)
1944 // Also skip over the bitcast.
1945 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001946 if (&*BI != RI)
1947 return false;
1948 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001949 BasicBlock::iterator BI = BB->begin();
1950 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1951 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001952 return false;
1953 }
Evan Cheng0663f232011-03-21 01:19:09 +00001954
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001955 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1956 /// call.
1957 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001958 if (PN) {
1959 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1960 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1961 // Make sure the phi value is indeed produced by the tail call.
1962 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1963 TLI->mayBeEmittedAsTailCall(CI))
1964 TailCalls.push_back(CI);
1965 }
1966 } else {
1967 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001968 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001969 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001970 continue;
1971
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001972 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001973 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1974 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001975 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1976 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001977 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001978
Cameron Zwarich4649f172011-03-24 04:52:10 +00001979 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001980 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001981 TailCalls.push_back(CI);
1982 }
Evan Cheng0663f232011-03-21 01:19:09 +00001983 }
1984
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001985 bool Changed = false;
1986 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1987 CallInst *CI = TailCalls[i];
1988 CallSite CS(CI);
1989
1990 // Conservatively require the attributes of the call to match those of the
1991 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001992 AttributeSet CalleeAttrs = CS.getAttributes();
1993 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001994 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001995 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001996 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001997 continue;
1998
1999 // Make sure the call instruction is followed by an unconditional branch to
2000 // the return block.
2001 BasicBlock *CallBB = CI->getParent();
2002 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2003 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2004 continue;
2005
2006 // Duplicate the return into CallBB.
2007 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002008 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002009 ++NumRetsDup;
2010 }
2011
2012 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002013 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002014 BB->eraseFromParent();
2015
2016 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002017}
2018
Chris Lattner728f9022008-11-25 07:09:13 +00002019//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002020// Memory Optimization
2021//===----------------------------------------------------------------------===//
2022
Chandler Carruthc8925912013-01-05 02:09:22 +00002023namespace {
2024
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002025/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002026/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002027struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002028 Value *BaseReg;
2029 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002030 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002031 void print(raw_ostream &OS) const;
2032 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002033
Chandler Carruthc8925912013-01-05 02:09:22 +00002034 bool operator==(const ExtAddrMode& O) const {
2035 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2036 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2037 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2038 }
2039};
2040
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002041#ifndef NDEBUG
2042static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2043 AM.print(OS);
2044 return OS;
2045}
2046#endif
2047
Chandler Carruthc8925912013-01-05 02:09:22 +00002048void ExtAddrMode::print(raw_ostream &OS) const {
2049 bool NeedPlus = false;
2050 OS << "[";
2051 if (BaseGV) {
2052 OS << (NeedPlus ? " + " : "")
2053 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002054 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002055 NeedPlus = true;
2056 }
2057
Richard Trieuc0f91212014-05-30 03:15:17 +00002058 if (BaseOffs) {
2059 OS << (NeedPlus ? " + " : "")
2060 << BaseOffs;
2061 NeedPlus = true;
2062 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002063
2064 if (BaseReg) {
2065 OS << (NeedPlus ? " + " : "")
2066 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002067 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002068 NeedPlus = true;
2069 }
2070 if (Scale) {
2071 OS << (NeedPlus ? " + " : "")
2072 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002073 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002074 }
2075
2076 OS << ']';
2077}
2078
2079#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002080LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002081 print(dbgs());
2082 dbgs() << '\n';
2083}
2084#endif
2085
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002086/// \brief This class provides transaction based operation on the IR.
2087/// Every change made through this class is recorded in the internal state and
2088/// can be undone (rollback) until commit is called.
2089class TypePromotionTransaction {
2090
2091 /// \brief This represents the common interface of the individual transaction.
2092 /// Each class implements the logic for doing one specific modification on
2093 /// the IR via the TypePromotionTransaction.
2094 class TypePromotionAction {
2095 protected:
2096 /// The Instruction modified.
2097 Instruction *Inst;
2098
2099 public:
2100 /// \brief Constructor of the action.
2101 /// The constructor performs the related action on the IR.
2102 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2103
2104 virtual ~TypePromotionAction() {}
2105
2106 /// \brief Undo the modification done by this action.
2107 /// When this method is called, the IR must be in the same state as it was
2108 /// before this action was applied.
2109 /// \pre Undoing the action works if and only if the IR is in the exact same
2110 /// state as it was directly after this action was applied.
2111 virtual void undo() = 0;
2112
2113 /// \brief Advocate every change made by this action.
2114 /// When the results on the IR of the action are to be kept, it is important
2115 /// to call this function, otherwise hidden information may be kept forever.
2116 virtual void commit() {
2117 // Nothing to be done, this action is not doing anything.
2118 }
2119 };
2120
2121 /// \brief Utility to remember the position of an instruction.
2122 class InsertionHandler {
2123 /// Position of an instruction.
2124 /// Either an instruction:
2125 /// - Is the first in a basic block: BB is used.
2126 /// - Has a previous instructon: PrevInst is used.
2127 union {
2128 Instruction *PrevInst;
2129 BasicBlock *BB;
2130 } Point;
2131 /// Remember whether or not the instruction had a previous instruction.
2132 bool HasPrevInstruction;
2133
2134 public:
2135 /// \brief Record the position of \p Inst.
2136 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002137 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002138 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2139 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002140 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002141 else
2142 Point.BB = Inst->getParent();
2143 }
2144
2145 /// \brief Insert \p Inst at the recorded position.
2146 void insert(Instruction *Inst) {
2147 if (HasPrevInstruction) {
2148 if (Inst->getParent())
2149 Inst->removeFromParent();
2150 Inst->insertAfter(Point.PrevInst);
2151 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002152 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002153 if (Inst->getParent())
2154 Inst->moveBefore(Position);
2155 else
2156 Inst->insertBefore(Position);
2157 }
2158 }
2159 };
2160
2161 /// \brief Move an instruction before another.
2162 class InstructionMoveBefore : public TypePromotionAction {
2163 /// Original position of the instruction.
2164 InsertionHandler Position;
2165
2166 public:
2167 /// \brief Move \p Inst before \p Before.
2168 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2169 : TypePromotionAction(Inst), Position(Inst) {
2170 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2171 Inst->moveBefore(Before);
2172 }
2173
2174 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002175 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002176 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2177 Position.insert(Inst);
2178 }
2179 };
2180
2181 /// \brief Set the operand of an instruction with a new value.
2182 class OperandSetter : public TypePromotionAction {
2183 /// Original operand of the instruction.
2184 Value *Origin;
2185 /// Index of the modified instruction.
2186 unsigned Idx;
2187
2188 public:
2189 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2190 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2191 : TypePromotionAction(Inst), Idx(Idx) {
2192 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2193 << "for:" << *Inst << "\n"
2194 << "with:" << *NewVal << "\n");
2195 Origin = Inst->getOperand(Idx);
2196 Inst->setOperand(Idx, NewVal);
2197 }
2198
2199 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002200 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002201 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2202 << "for: " << *Inst << "\n"
2203 << "with: " << *Origin << "\n");
2204 Inst->setOperand(Idx, Origin);
2205 }
2206 };
2207
2208 /// \brief Hide the operands of an instruction.
2209 /// Do as if this instruction was not using any of its operands.
2210 class OperandsHider : public TypePromotionAction {
2211 /// The list of original operands.
2212 SmallVector<Value *, 4> OriginalValues;
2213
2214 public:
2215 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2216 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2217 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2218 unsigned NumOpnds = Inst->getNumOperands();
2219 OriginalValues.reserve(NumOpnds);
2220 for (unsigned It = 0; It < NumOpnds; ++It) {
2221 // Save the current operand.
2222 Value *Val = Inst->getOperand(It);
2223 OriginalValues.push_back(Val);
2224 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002225 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002226 // that we are not willing to pay.
2227 Inst->setOperand(It, UndefValue::get(Val->getType()));
2228 }
2229 }
2230
2231 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002232 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002233 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2234 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2235 Inst->setOperand(It, OriginalValues[It]);
2236 }
2237 };
2238
2239 /// \brief Build a truncate instruction.
2240 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002241 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002242 public:
2243 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2244 /// result.
2245 /// trunc Opnd to Ty.
2246 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2247 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002248 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2249 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002250 }
2251
Quentin Colombetac55b152014-09-16 22:36:07 +00002252 /// \brief Get the built value.
2253 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002254
2255 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002256 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002257 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2258 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2259 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002260 }
2261 };
2262
2263 /// \brief Build a sign extension instruction.
2264 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002265 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002266 public:
2267 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2268 /// result.
2269 /// sext Opnd to Ty.
2270 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002271 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002272 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002273 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2274 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002275 }
2276
Quentin Colombetac55b152014-09-16 22:36:07 +00002277 /// \brief Get the built value.
2278 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002279
2280 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002281 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002282 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2283 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2284 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002285 }
2286 };
2287
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002288 /// \brief Build a zero extension instruction.
2289 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002290 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002291 public:
2292 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2293 /// result.
2294 /// zext Opnd to Ty.
2295 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002296 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002297 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002298 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2299 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002300 }
2301
Quentin Colombetac55b152014-09-16 22:36:07 +00002302 /// \brief Get the built value.
2303 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002304
2305 /// \brief Remove the built instruction.
2306 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002307 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2308 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2309 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002310 }
2311 };
2312
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002313 /// \brief Mutate an instruction to another type.
2314 class TypeMutator : public TypePromotionAction {
2315 /// Record the original type.
2316 Type *OrigTy;
2317
2318 public:
2319 /// \brief Mutate the type of \p Inst into \p NewTy.
2320 TypeMutator(Instruction *Inst, Type *NewTy)
2321 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2322 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2323 << "\n");
2324 Inst->mutateType(NewTy);
2325 }
2326
2327 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002328 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002329 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2330 << "\n");
2331 Inst->mutateType(OrigTy);
2332 }
2333 };
2334
2335 /// \brief Replace the uses of an instruction by another instruction.
2336 class UsesReplacer : public TypePromotionAction {
2337 /// Helper structure to keep track of the replaced uses.
2338 struct InstructionAndIdx {
2339 /// The instruction using the instruction.
2340 Instruction *Inst;
2341 /// The index where this instruction is used for Inst.
2342 unsigned Idx;
2343 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2344 : Inst(Inst), Idx(Idx) {}
2345 };
2346
2347 /// Keep track of the original uses (pair Instruction, Index).
2348 SmallVector<InstructionAndIdx, 4> OriginalUses;
2349 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2350
2351 public:
2352 /// \brief Replace all the use of \p Inst by \p New.
2353 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2354 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2355 << "\n");
2356 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002357 for (Use &U : Inst->uses()) {
2358 Instruction *UserI = cast<Instruction>(U.getUser());
2359 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002360 }
2361 // Now, we can replace the uses.
2362 Inst->replaceAllUsesWith(New);
2363 }
2364
2365 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002366 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002367 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2368 for (use_iterator UseIt = OriginalUses.begin(),
2369 EndIt = OriginalUses.end();
2370 UseIt != EndIt; ++UseIt) {
2371 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2372 }
2373 }
2374 };
2375
2376 /// \brief Remove an instruction from the IR.
2377 class InstructionRemover : public TypePromotionAction {
2378 /// Original position of the instruction.
2379 InsertionHandler Inserter;
2380 /// Helper structure to hide all the link to the instruction. In other
2381 /// words, this helps to do as if the instruction was removed.
2382 OperandsHider Hider;
2383 /// Keep track of the uses replaced, if any.
2384 UsesReplacer *Replacer;
2385
2386 public:
2387 /// \brief Remove all reference of \p Inst and optinally replace all its
2388 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002389 /// \pre If !Inst->use_empty(), then New != nullptr
2390 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002391 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002392 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002393 if (New)
2394 Replacer = new UsesReplacer(Inst, New);
2395 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2396 Inst->removeFromParent();
2397 }
2398
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002399 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002400
2401 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002402 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002403
2404 /// \brief Resurrect the instruction and reassign it to the proper uses if
2405 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002406 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002407 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2408 Inserter.insert(Inst);
2409 if (Replacer)
2410 Replacer->undo();
2411 Hider.undo();
2412 }
2413 };
2414
2415public:
2416 /// Restoration point.
2417 /// The restoration point is a pointer to an action instead of an iterator
2418 /// because the iterator may be invalidated but not the pointer.
2419 typedef const TypePromotionAction *ConstRestorationPt;
2420 /// Advocate every changes made in that transaction.
2421 void commit();
2422 /// Undo all the changes made after the given point.
2423 void rollback(ConstRestorationPt Point);
2424 /// Get the current restoration point.
2425 ConstRestorationPt getRestorationPoint() const;
2426
2427 /// \name API for IR modification with state keeping to support rollback.
2428 /// @{
2429 /// Same as Instruction::setOperand.
2430 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2431 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002432 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433 /// Same as Value::replaceAllUsesWith.
2434 void replaceAllUsesWith(Instruction *Inst, Value *New);
2435 /// Same as Value::mutateType.
2436 void mutateType(Instruction *Inst, Type *NewTy);
2437 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002438 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002440 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002441 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002442 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443 /// Same as Instruction::moveBefore.
2444 void moveBefore(Instruction *Inst, Instruction *Before);
2445 /// @}
2446
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002447private:
2448 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002449 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2450 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002451};
2452
2453void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2454 Value *NewVal) {
2455 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002456 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002457}
2458
2459void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2460 Value *NewVal) {
2461 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002462 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002463}
2464
2465void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2466 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002467 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002468}
2469
2470void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002471 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002472}
2473
Quentin Colombetac55b152014-09-16 22:36:07 +00002474Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2475 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002476 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002477 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002478 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002479 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002480}
2481
Quentin Colombetac55b152014-09-16 22:36:07 +00002482Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2483 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002484 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002485 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002486 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002487 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002488}
2489
Quentin Colombetac55b152014-09-16 22:36:07 +00002490Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2491 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002492 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002493 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002494 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002495 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002496}
2497
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002498void TypePromotionTransaction::moveBefore(Instruction *Inst,
2499 Instruction *Before) {
2500 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002501 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502}
2503
2504TypePromotionTransaction::ConstRestorationPt
2505TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002506 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002507}
2508
2509void TypePromotionTransaction::commit() {
2510 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002511 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002512 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002513 Actions.clear();
2514}
2515
2516void TypePromotionTransaction::rollback(
2517 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002518 while (!Actions.empty() && Point != Actions.back().get()) {
2519 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002520 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002521 }
2522}
2523
Chandler Carruthc8925912013-01-05 02:09:22 +00002524/// \brief A helper class for matching addressing modes.
2525///
2526/// This encapsulates the logic for matching the target-legal addressing modes.
2527class AddressingModeMatcher {
2528 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002529 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002530 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002531 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002532
2533 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2534 /// the memory instruction that we're computing this address for.
2535 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002536 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002537 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002538
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002539 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002540 /// part of the return value of this addressing mode matching stuff.
2541 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002542
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002543 /// The instructions inserted by other CodeGenPrepare optimizations.
2544 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002545 /// A map from the instructions to their type before promotion.
2546 InstrToOrigTy &PromotedInsts;
2547 /// The ongoing transaction where every action should be registered.
2548 TypePromotionTransaction &TPT;
2549
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002550 /// This is set to true when we should not do profitability checks.
2551 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002552 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002553
Eric Christopherd75c00c2015-02-26 22:38:34 +00002554 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002555 const TargetMachine &TM, Type *AT, unsigned AS,
2556 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002557 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002558 InstrToOrigTy &PromotedInsts,
2559 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002560 : AddrModeInsts(AMI), TM(TM),
2561 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2562 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002563 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2564 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2565 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002566 IgnoreProfitability = false;
2567 }
2568public:
Stephen Lin837bba12013-07-15 17:55:02 +00002569
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002570 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002571 /// give an access type of AccessTy. This returns a list of involved
2572 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002573 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002574 /// optimizations.
2575 /// \p PromotedInsts maps the instructions to their type before promotion.
2576 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002577 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002578 Instruction *MemoryInst,
2579 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002580 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002581 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582 InstrToOrigTy &PromotedInsts,
2583 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002584 ExtAddrMode Result;
2585
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002586 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002587 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002588 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002589 (void)Success; assert(Success && "Couldn't select *anything*?");
2590 return Result;
2591 }
2592private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002593 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2594 bool matchAddr(Value *V, unsigned Depth);
2595 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002596 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002597 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002598 ExtAddrMode &AMBefore,
2599 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002600 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2601 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002602 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002603};
2604
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002605/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002606/// Return true and update AddrMode if this addr mode is legal for the target,
2607/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002608bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002609 unsigned Depth) {
2610 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2611 // mode. Just process that directly.
2612 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002613 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002614
Chandler Carruthc8925912013-01-05 02:09:22 +00002615 // If the scale is 0, it takes nothing to add this.
2616 if (Scale == 0)
2617 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002618
Chandler Carruthc8925912013-01-05 02:09:22 +00002619 // If we already have a scale of this value, we can add to it, otherwise, we
2620 // need an available scale field.
2621 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2622 return false;
2623
2624 ExtAddrMode TestAddrMode = AddrMode;
2625
2626 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2627 // [A+B + A*7] -> [B+A*8].
2628 TestAddrMode.Scale += Scale;
2629 TestAddrMode.ScaledReg = ScaleReg;
2630
2631 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002632 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002633 return false;
2634
2635 // It was legal, so commit it.
2636 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002637
Chandler Carruthc8925912013-01-05 02:09:22 +00002638 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2639 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2640 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002641 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002642 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2643 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2644 TestAddrMode.ScaledReg = AddLHS;
2645 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002646
Chandler Carruthc8925912013-01-05 02:09:22 +00002647 // If this addressing mode is legal, commit it and remember that we folded
2648 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002649 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002650 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2651 AddrMode = TestAddrMode;
2652 return true;
2653 }
2654 }
2655
2656 // Otherwise, not (x+c)*scale, just return what we have.
2657 return true;
2658}
2659
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002660/// This is a little filter, which returns true if an addressing computation
2661/// involving I might be folded into a load/store accessing it.
2662/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002663/// the set of instructions that MatchOperationAddr can.
2664static bool MightBeFoldableInst(Instruction *I) {
2665 switch (I->getOpcode()) {
2666 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002667 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002668 // Don't touch identity bitcasts.
2669 if (I->getType() == I->getOperand(0)->getType())
2670 return false;
2671 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2672 case Instruction::PtrToInt:
2673 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2674 return true;
2675 case Instruction::IntToPtr:
2676 // We know the input is intptr_t, so this is foldable.
2677 return true;
2678 case Instruction::Add:
2679 return true;
2680 case Instruction::Mul:
2681 case Instruction::Shl:
2682 // Can only handle X*C and X << C.
2683 return isa<ConstantInt>(I->getOperand(1));
2684 case Instruction::GetElementPtr:
2685 return true;
2686 default:
2687 return false;
2688 }
2689}
2690
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002691/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2692/// \note \p Val is assumed to be the product of some type promotion.
2693/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2694/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002695static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2696 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002697 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2698 if (!PromotedInst)
2699 return false;
2700 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2701 // If the ISDOpcode is undefined, it was undefined before the promotion.
2702 if (!ISDOpcode)
2703 return true;
2704 // Otherwise, check if the promoted instruction is legal or not.
2705 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002706 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002707}
2708
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002709/// \brief Hepler class to perform type promotion.
2710class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002711 /// \brief Utility function to check whether or not a sign or zero extension
2712 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2713 /// either using the operands of \p Inst or promoting \p Inst.
2714 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002715 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002716 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002717 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002718 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002719 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002720 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002721 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002722 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2723 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002724
2725 /// \brief Utility function to determine if \p OpIdx should be promoted when
2726 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002727 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002728 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002729 }
2730
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002731 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002732 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002733 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002734 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002735 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002736 /// Newly added extensions are inserted in \p Exts.
2737 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002738 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002739 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002740 static Value *promoteOperandForTruncAndAnyExt(
2741 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002742 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002743 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002744 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002745
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002746 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002747 /// operand is promotable and is not a supported trunc or sext.
2748 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002749 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002750 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002751 /// Newly added extensions are inserted in \p Exts.
2752 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002753 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002754 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002755 static Value *promoteOperandForOther(Instruction *Ext,
2756 TypePromotionTransaction &TPT,
2757 InstrToOrigTy &PromotedInsts,
2758 unsigned &CreatedInstsCost,
2759 SmallVectorImpl<Instruction *> *Exts,
2760 SmallVectorImpl<Instruction *> *Truncs,
2761 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002762
2763 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002764 static Value *signExtendOperandForOther(
2765 Instruction *Ext, TypePromotionTransaction &TPT,
2766 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2767 SmallVectorImpl<Instruction *> *Exts,
2768 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2769 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2770 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002771 }
2772
2773 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002774 static Value *zeroExtendOperandForOther(
2775 Instruction *Ext, TypePromotionTransaction &TPT,
2776 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2777 SmallVectorImpl<Instruction *> *Exts,
2778 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2779 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2780 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002781 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002782
2783public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002784 /// Type for the utility function that promotes the operand of Ext.
2785 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002786 InstrToOrigTy &PromotedInsts,
2787 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002788 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002789 SmallVectorImpl<Instruction *> *Truncs,
2790 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002791 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2792 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002793 /// \return NULL if no promotable action is possible with the current
2794 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002795 /// \p InsertedInsts keeps track of all the instructions inserted by the
2796 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002797 /// because we do not want to promote these instructions as CodeGenPrepare
2798 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2799 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002800 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002801 const TargetLowering &TLI,
2802 const InstrToOrigTy &PromotedInsts);
2803};
2804
2805bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002806 Type *ConsideredExtType,
2807 const InstrToOrigTy &PromotedInsts,
2808 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002809 // The promotion helper does not know how to deal with vector types yet.
2810 // To be able to fix that, we would need to fix the places where we
2811 // statically extend, e.g., constants and such.
2812 if (Inst->getType()->isVectorTy())
2813 return false;
2814
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002815 // We can always get through zext.
2816 if (isa<ZExtInst>(Inst))
2817 return true;
2818
2819 // sext(sext) is ok too.
2820 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002821 return true;
2822
2823 // We can get through binary operator, if it is legal. In other words, the
2824 // binary operator must have a nuw or nsw flag.
2825 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2826 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002827 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2828 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002829 return true;
2830
2831 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002832 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002833 if (!isa<TruncInst>(Inst))
2834 return false;
2835
2836 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002837 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002838 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002839 if (!OpndVal->getType()->isIntegerTy() ||
2840 OpndVal->getType()->getIntegerBitWidth() >
2841 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002842 return false;
2843
2844 // If the operand of the truncate is not an instruction, we will not have
2845 // any information on the dropped bits.
2846 // (Actually we could for constant but it is not worth the extra logic).
2847 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2848 if (!Opnd)
2849 return false;
2850
2851 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002852 // I.e., check that trunc just drops extended bits of the same kind of
2853 // the extension.
2854 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002855 const Type *OpndType;
2856 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002857 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2858 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002859 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2860 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002861 else
2862 return false;
2863
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002864 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002865 return Inst->getType()->getIntegerBitWidth() >=
2866 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002867}
2868
2869TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002870 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002871 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002872 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2873 "Unexpected instruction type");
2874 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2875 Type *ExtTy = Ext->getType();
2876 bool IsSExt = isa<SExtInst>(Ext);
2877 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002878 // get through.
2879 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002880 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002881 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002882
2883 // Do not promote if the operand has been added by codegenprepare.
2884 // Otherwise, it means we are undoing an optimization that is likely to be
2885 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002886 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002887 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002888
2889 // SExt or Trunc instructions.
2890 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002891 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2892 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002893 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002894
2895 // Regular instruction.
2896 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002897 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002898 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002899 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002900}
2901
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002902Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002903 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002904 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002905 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002906 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002907 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2908 // get through it and this method should not be called.
2909 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002910 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002911 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002912 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002913 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002914 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002915 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002916 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002917 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2918 TPT.replaceAllUsesWith(SExt, ZExt);
2919 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002920 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002921 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002922 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2923 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002924 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2925 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002926 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002927
2928 // Remove dead code.
2929 if (SExtOpnd->use_empty())
2930 TPT.eraseInstruction(SExtOpnd);
2931
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002932 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002933 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002934 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002935 if (ExtInst) {
2936 if (Exts)
2937 Exts->push_back(ExtInst);
2938 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2939 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002940 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002941 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002942
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002943 // At this point we have: ext ty opnd to ty.
2944 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2945 Value *NextVal = ExtInst->getOperand(0);
2946 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002947 return NextVal;
2948}
2949
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002950Value *TypePromotionHelper::promoteOperandForOther(
2951 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002952 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002953 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002954 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2955 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002956 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002957 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002958 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002959 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002960 if (!ExtOpnd->hasOneUse()) {
2961 // ExtOpnd will be promoted.
2962 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002963 // promoted version.
2964 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002965 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002966 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2967 ITrunc->removeFromParent();
2968 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002969 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002970 if (Truncs)
2971 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002972 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002973
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002974 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002975 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002976 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002977 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002978 }
2979
2980 // Get through the Instruction:
2981 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002982 // 2. Replace the uses of Ext by Inst.
2983 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002984
2985 // Remember the original type of the instruction before promotion.
2986 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002987 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2988 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002989 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002990 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002991 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002992 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002993 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002994 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002995
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002996 DEBUG(dbgs() << "Propagate Ext to operands\n");
2997 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002998 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002999 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3000 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3001 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003002 DEBUG(dbgs() << "No need to propagate\n");
3003 continue;
3004 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003005 // Check if we can statically extend the operand.
3006 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003007 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003008 DEBUG(dbgs() << "Statically extend\n");
3009 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3010 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3011 : Cst->getValue().zext(BitWidth);
3012 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003013 continue;
3014 }
3015 // UndefValue are typed, so we have to statically sign extend them.
3016 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003017 DEBUG(dbgs() << "Statically extend\n");
3018 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003019 continue;
3020 }
3021
3022 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003023 // Check if Ext was reused to extend an operand.
3024 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003025 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003026 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003027 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3028 : TPT.createZExt(Ext, Opnd, Ext->getType());
3029 if (!isa<Instruction>(ValForExtOpnd)) {
3030 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3031 continue;
3032 }
3033 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003034 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003035 if (Exts)
3036 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003037 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003038
3039 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003040 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3041 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003042 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003043 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003044 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003045 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003046 if (ExtForOpnd == Ext) {
3047 DEBUG(dbgs() << "Extension is useless now\n");
3048 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003049 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003050 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003051}
3052
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003053/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003054/// \p NewCost gives the cost of extension instructions created by the
3055/// promotion.
3056/// \p OldCost gives the cost of extension instructions before the promotion
3057/// plus the number of instructions that have been
3058/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003059/// \p PromotedOperand is the value that has been promoted.
3060/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003061bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003062 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3063 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3064 // The cost of the new extensions is greater than the cost of the
3065 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003066 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003067 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003068 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003069 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003070 return true;
3071 // The promotion is neutral but it may help folding the sign extension in
3072 // loads for instance.
3073 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003074 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003075}
3076
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003077/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003078/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003079/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003080/// If \p MovedAway is not NULL, it contains the information of whether or
3081/// not AddrInst has to be folded into the addressing mode on success.
3082/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3083/// because it has been moved away.
3084/// Thus AddrInst must not be added in the matched instructions.
3085/// This state can happen when AddrInst is a sext, since it may be moved away.
3086/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3087/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003088bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003089 unsigned Depth,
3090 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003091 // Avoid exponential behavior on extremely deep expression trees.
3092 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003093
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003094 // By default, all matched instructions stay in place.
3095 if (MovedAway)
3096 *MovedAway = false;
3097
Chandler Carruthc8925912013-01-05 02:09:22 +00003098 switch (Opcode) {
3099 case Instruction::PtrToInt:
3100 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003101 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003102 case Instruction::IntToPtr: {
3103 auto AS = AddrInst->getType()->getPointerAddressSpace();
3104 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003105 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003106 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003107 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003108 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003109 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003110 case Instruction::BitCast:
3111 // BitCast is always a noop, and we can handle it as long as it is
3112 // int->int or pointer->pointer (we don't want int<->fp or something).
3113 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3114 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3115 // Don't touch identity bitcasts. These were probably put here by LSR,
3116 // and we don't want to mess around with them. Assume it knows what it
3117 // is doing.
3118 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003119 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003120 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003121 case Instruction::AddrSpaceCast: {
3122 unsigned SrcAS
3123 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3124 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3125 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003126 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003127 return false;
3128 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003129 case Instruction::Add: {
3130 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3131 ExtAddrMode BackupAddrMode = AddrMode;
3132 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003133 // Start a transaction at this point.
3134 // The LHS may match but not the RHS.
3135 // Therefore, we need a higher level restoration point to undo partially
3136 // matched operation.
3137 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3138 TPT.getRestorationPoint();
3139
Sanjay Patelfc580a62015-09-21 23:03:16 +00003140 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3141 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003142 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003143
Chandler Carruthc8925912013-01-05 02:09:22 +00003144 // Restore the old addr mode info.
3145 AddrMode = BackupAddrMode;
3146 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003147 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003148
Chandler Carruthc8925912013-01-05 02:09:22 +00003149 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003150 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3151 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003152 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003153
Chandler Carruthc8925912013-01-05 02:09:22 +00003154 // Otherwise we definitely can't merge the ADD in.
3155 AddrMode = BackupAddrMode;
3156 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003157 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003158 break;
3159 }
3160 //case Instruction::Or:
3161 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3162 //break;
3163 case Instruction::Mul:
3164 case Instruction::Shl: {
3165 // Can only handle X*C and X << C.
3166 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003167 if (!RHS)
3168 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003169 int64_t Scale = RHS->getSExtValue();
3170 if (Opcode == Instruction::Shl)
3171 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003172
Sanjay Patelfc580a62015-09-21 23:03:16 +00003173 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003174 }
3175 case Instruction::GetElementPtr: {
3176 // Scan the GEP. We check it if it contains constant offsets and at most
3177 // one variable offset.
3178 int VariableOperand = -1;
3179 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003180
Chandler Carruthc8925912013-01-05 02:09:22 +00003181 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003182 gep_type_iterator GTI = gep_type_begin(AddrInst);
3183 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3184 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003185 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003186 unsigned Idx =
3187 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3188 ConstantOffset += SL->getElementOffset(Idx);
3189 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003190 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003191 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3192 ConstantOffset += CI->getSExtValue()*TypeSize;
3193 } else if (TypeSize) { // Scales of zero don't do anything.
3194 // We only allow one variable index at the moment.
3195 if (VariableOperand != -1)
3196 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003197
Chandler Carruthc8925912013-01-05 02:09:22 +00003198 // Remember the variable index.
3199 VariableOperand = i;
3200 VariableScale = TypeSize;
3201 }
3202 }
3203 }
Stephen Lin837bba12013-07-15 17:55:02 +00003204
Chandler Carruthc8925912013-01-05 02:09:22 +00003205 // A common case is for the GEP to only do a constant offset. In this case,
3206 // just add it to the disp field and check validity.
3207 if (VariableOperand == -1) {
3208 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003209 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003210 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003211 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003212 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003213 return true;
3214 }
3215 AddrMode.BaseOffs -= ConstantOffset;
3216 return false;
3217 }
3218
3219 // Save the valid addressing mode in case we can't match.
3220 ExtAddrMode BackupAddrMode = AddrMode;
3221 unsigned OldSize = AddrModeInsts.size();
3222
3223 // See if the scale and offset amount is valid for this target.
3224 AddrMode.BaseOffs += ConstantOffset;
3225
3226 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003227 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003228 // If it couldn't be matched, just stuff the value in a register.
3229 if (AddrMode.HasBaseReg) {
3230 AddrMode = BackupAddrMode;
3231 AddrModeInsts.resize(OldSize);
3232 return false;
3233 }
3234 AddrMode.HasBaseReg = true;
3235 AddrMode.BaseReg = AddrInst->getOperand(0);
3236 }
3237
3238 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003239 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003240 Depth)) {
3241 // If it couldn't be matched, try stuffing the base into a register
3242 // instead of matching it, and retrying the match of the scale.
3243 AddrMode = BackupAddrMode;
3244 AddrModeInsts.resize(OldSize);
3245 if (AddrMode.HasBaseReg)
3246 return false;
3247 AddrMode.HasBaseReg = true;
3248 AddrMode.BaseReg = AddrInst->getOperand(0);
3249 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003250 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003251 VariableScale, Depth)) {
3252 // If even that didn't work, bail.
3253 AddrMode = BackupAddrMode;
3254 AddrModeInsts.resize(OldSize);
3255 return false;
3256 }
3257 }
3258
3259 return true;
3260 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003261 case Instruction::SExt:
3262 case Instruction::ZExt: {
3263 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3264 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003265 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003266
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003267 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003268 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003269 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003270 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003271 if (!TPH)
3272 return false;
3273
3274 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3275 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003276 unsigned CreatedInstsCost = 0;
3277 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003278 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003279 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003280 // SExt has been moved away.
3281 // Thus either it will be rematched later in the recursive calls or it is
3282 // gone. Anyway, we must not fold it into the addressing mode at this point.
3283 // E.g.,
3284 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003285 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003286 // addr = gep base, idx
3287 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003288 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003289 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3290 // addr = gep base, op <- match
3291 if (MovedAway)
3292 *MovedAway = true;
3293
3294 assert(PromotedOperand &&
3295 "TypePromotionHelper should have filtered out those cases");
3296
3297 ExtAddrMode BackupAddrMode = AddrMode;
3298 unsigned OldSize = AddrModeInsts.size();
3299
Sanjay Patelfc580a62015-09-21 23:03:16 +00003300 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003301 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003302 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003303 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003304 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003305 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003306 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003307 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003308 AddrMode = BackupAddrMode;
3309 AddrModeInsts.resize(OldSize);
3310 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3311 TPT.rollback(LastKnownGood);
3312 return false;
3313 }
3314 return true;
3315 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003316 }
3317 return false;
3318}
3319
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003320/// If we can, try to add the value of 'Addr' into the current addressing mode.
3321/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3322/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3323/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003324///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003325bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003326 // Start a transaction at this point that we will rollback if the matching
3327 // fails.
3328 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3329 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003330 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3331 // Fold in immediates if legal for the target.
3332 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003333 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003334 return true;
3335 AddrMode.BaseOffs -= CI->getSExtValue();
3336 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3337 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003338 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003339 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003340 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003341 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003342 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003343 }
3344 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3345 ExtAddrMode BackupAddrMode = AddrMode;
3346 unsigned OldSize = AddrModeInsts.size();
3347
3348 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003349 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003350 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003351 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003352 // to check here.
3353 if (MovedAway)
3354 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003355 // Okay, it's possible to fold this. Check to see if it is actually
3356 // *profitable* to do so. We use a simple cost model to avoid increasing
3357 // register pressure too much.
3358 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003359 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003360 AddrModeInsts.push_back(I);
3361 return true;
3362 }
Stephen Lin837bba12013-07-15 17:55:02 +00003363
Chandler Carruthc8925912013-01-05 02:09:22 +00003364 // It isn't profitable to do this, roll back.
3365 //cerr << "NOT FOLDING: " << *I;
3366 AddrMode = BackupAddrMode;
3367 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003368 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003369 }
3370 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003371 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003372 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003373 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003374 } else if (isa<ConstantPointerNull>(Addr)) {
3375 // Null pointer gets folded without affecting the addressing mode.
3376 return true;
3377 }
3378
3379 // Worse case, the target should support [reg] addressing modes. :)
3380 if (!AddrMode.HasBaseReg) {
3381 AddrMode.HasBaseReg = true;
3382 AddrMode.BaseReg = Addr;
3383 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003384 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003385 return true;
3386 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003387 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003388 }
3389
3390 // If the base register is already taken, see if we can do [r+r].
3391 if (AddrMode.Scale == 0) {
3392 AddrMode.Scale = 1;
3393 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003394 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003395 return true;
3396 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003397 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003398 }
3399 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003400 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003401 return false;
3402}
3403
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003404/// Check to see if all uses of OpVal by the specified inline asm call are due
3405/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003406static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003407 const TargetMachine &TM) {
3408 const Function *F = CI->getParent()->getParent();
3409 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3410 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003411 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003412 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3413 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003414 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3415 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003416
Chandler Carruthc8925912013-01-05 02:09:22 +00003417 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003418 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003419
3420 // If this asm operand is our Value*, and if it isn't an indirect memory
3421 // operand, we can't fold it!
3422 if (OpInfo.CallOperandVal == OpVal &&
3423 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3424 !OpInfo.isIndirect))
3425 return false;
3426 }
3427
3428 return true;
3429}
3430
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003431/// Recursively walk all the uses of I until we find a memory use.
3432/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003433/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003434static bool FindAllMemoryUses(
3435 Instruction *I,
3436 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3437 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003438 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003439 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003440 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003441
Chandler Carruthc8925912013-01-05 02:09:22 +00003442 // If this is an obviously unfoldable instruction, bail out.
3443 if (!MightBeFoldableInst(I))
3444 return true;
3445
3446 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003447 for (Use &U : I->uses()) {
3448 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003449
Chandler Carruthcdf47882014-03-09 03:16:01 +00003450 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3451 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003452 continue;
3453 }
Stephen Lin837bba12013-07-15 17:55:02 +00003454
Chandler Carruthcdf47882014-03-09 03:16:01 +00003455 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3456 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003457 if (opNo == 0) return true; // Storing addr, not into addr.
3458 MemoryUses.push_back(std::make_pair(SI, opNo));
3459 continue;
3460 }
Stephen Lin837bba12013-07-15 17:55:02 +00003461
Chandler Carruthcdf47882014-03-09 03:16:01 +00003462 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003463 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3464 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003465
Chandler Carruthc8925912013-01-05 02:09:22 +00003466 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003467 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003468 return true;
3469 continue;
3470 }
Stephen Lin837bba12013-07-15 17:55:02 +00003471
Eric Christopher11e4df72015-02-26 22:38:43 +00003472 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003473 return true;
3474 }
3475
3476 return false;
3477}
3478
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003479/// Return true if Val is already known to be live at the use site that we're
3480/// folding it into. If so, there is no cost to include it in the addressing
3481/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3482/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003483bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003484 Value *KnownLive2) {
3485 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003486 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003487 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003488
Chandler Carruthc8925912013-01-05 02:09:22 +00003489 // All values other than instructions and arguments (e.g. constants) are live.
3490 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003491
Chandler Carruthc8925912013-01-05 02:09:22 +00003492 // If Val is a constant sized alloca in the entry block, it is live, this is
3493 // true because it is just a reference to the stack/frame pointer, which is
3494 // live for the whole function.
3495 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3496 if (AI->isStaticAlloca())
3497 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003498
Chandler Carruthc8925912013-01-05 02:09:22 +00003499 // Check to see if this value is already used in the memory instruction's
3500 // block. If so, it's already live into the block at the very least, so we
3501 // can reasonably fold it.
3502 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3503}
3504
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003505/// It is possible for the addressing mode of the machine to fold the specified
3506/// instruction into a load or store that ultimately uses it.
3507/// However, the specified instruction has multiple uses.
3508/// Given this, it may actually increase register pressure to fold it
3509/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003510///
3511/// X = ...
3512/// Y = X+1
3513/// use(Y) -> nonload/store
3514/// Z = Y+1
3515/// load Z
3516///
3517/// In this case, Y has multiple uses, and can be folded into the load of Z
3518/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3519/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3520/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3521/// number of computations either.
3522///
3523/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3524/// X was live across 'load Z' for other reasons, we actually *would* want to
3525/// fold the addressing mode in the Z case. This would make Y die earlier.
3526bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003527isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003528 ExtAddrMode &AMAfter) {
3529 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003530
Chandler Carruthc8925912013-01-05 02:09:22 +00003531 // AMBefore is the addressing mode before this instruction was folded into it,
3532 // and AMAfter is the addressing mode after the instruction was folded. Get
3533 // the set of registers referenced by AMAfter and subtract out those
3534 // referenced by AMBefore: this is the set of values which folding in this
3535 // address extends the lifetime of.
3536 //
3537 // Note that there are only two potential values being referenced here,
3538 // BaseReg and ScaleReg (global addresses are always available, as are any
3539 // folded immediates).
3540 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003541
Chandler Carruthc8925912013-01-05 02:09:22 +00003542 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3543 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003544 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003545 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003546 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003547 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003548
3549 // If folding this instruction (and it's subexprs) didn't extend any live
3550 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003551 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003552 return true;
3553
3554 // If all uses of this instruction are ultimately load/store/inlineasm's,
3555 // check to see if their addressing modes will include this instruction. If
3556 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3557 // uses.
3558 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3559 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003560 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003561 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003562
Chandler Carruthc8925912013-01-05 02:09:22 +00003563 // Now that we know that all uses of this instruction are part of a chain of
3564 // computation involving only operations that could theoretically be folded
3565 // into a memory use, loop over each of these uses and see if they could
3566 // *actually* fold the instruction.
3567 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3568 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3569 Instruction *User = MemoryUses[i].first;
3570 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003571
Chandler Carruthc8925912013-01-05 02:09:22 +00003572 // Get the access type of this use. If the use isn't a pointer, we don't
3573 // know what it accesses.
3574 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003575 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3576 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003577 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003578 Type *AddressAccessTy = AddrTy->getElementType();
3579 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003580
Chandler Carruthc8925912013-01-05 02:09:22 +00003581 // Do a match against the root of this address, ignoring profitability. This
3582 // will tell us if the addressing mode for the memory operation will
3583 // *actually* cover the shared instruction.
3584 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003585 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3586 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003587 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003588 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003589 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003590 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003591 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003592 (void)Success; assert(Success && "Couldn't select *anything*?");
3593
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003594 // The match was to check the profitability, the changes made are not
3595 // part of the original matcher. Therefore, they should be dropped
3596 // otherwise the original matcher will not present the right state.
3597 TPT.rollback(LastKnownGood);
3598
Chandler Carruthc8925912013-01-05 02:09:22 +00003599 // If the match didn't cover I, then it won't be shared by it.
3600 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3601 I) == MatchedAddrModeInsts.end())
3602 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003603
Chandler Carruthc8925912013-01-05 02:09:22 +00003604 MatchedAddrModeInsts.clear();
3605 }
Stephen Lin837bba12013-07-15 17:55:02 +00003606
Chandler Carruthc8925912013-01-05 02:09:22 +00003607 return true;
3608}
3609
3610} // end anonymous namespace
3611
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003612/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003613/// different basic block than BB.
3614static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3615 if (Instruction *I = dyn_cast<Instruction>(V))
3616 return I->getParent() != BB;
3617 return false;
3618}
3619
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003620/// Load and Store Instructions often have addressing modes that can do
3621/// significant amounts of computation. As such, instruction selection will try
3622/// to get the load or store to do as much computation as possible for the
3623/// program. The problem is that isel can only see within a single block. As
3624/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003625///
3626/// This method is used to optimize both load/store and inline asms with memory
3627/// operands.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003628bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003629 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003630 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003631
3632 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003633 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003634 SmallVector<Value*, 8> worklist;
3635 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003636 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003637
Owen Anderson8ba5f392010-11-27 08:15:55 +00003638 // Use a worklist to iteratively look through PHI nodes, and ensure that
3639 // the addressing mode obtained from the non-PHI roots of the graph
3640 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003641 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003642 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003643 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003644 SmallVector<Instruction*, 16> AddrModeInsts;
3645 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003646 TypePromotionTransaction TPT;
3647 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3648 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003649 while (!worklist.empty()) {
3650 Value *V = worklist.back();
3651 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003652
Owen Anderson8ba5f392010-11-27 08:15:55 +00003653 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003654 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003655 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003656 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003657 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003658
Owen Anderson8ba5f392010-11-27 08:15:55 +00003659 // For a PHI node, push all of its incoming values.
3660 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003661 for (Value *IncValue : P->incoming_values())
3662 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003663 continue;
3664 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003665
Owen Anderson8ba5f392010-11-27 08:15:55 +00003666 // For non-PHIs, determine the addressing mode being computed.
3667 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003668 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003669 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003670 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003671
3672 // This check is broken into two cases with very similar code to avoid using
3673 // getNumUses() as much as possible. Some values have a lot of uses, so
3674 // calling getNumUses() unconditionally caused a significant compile-time
3675 // regression.
3676 if (!Consensus) {
3677 Consensus = V;
3678 AddrMode = NewAddrMode;
3679 AddrModeInsts = NewAddrModeInsts;
3680 continue;
3681 } else if (NewAddrMode == AddrMode) {
3682 if (!IsNumUsesConsensusValid) {
3683 NumUsesConsensus = Consensus->getNumUses();
3684 IsNumUsesConsensusValid = true;
3685 }
3686
3687 // Ensure that the obtained addressing mode is equivalent to that obtained
3688 // for all other roots of the PHI traversal. Also, when choosing one
3689 // such root as representative, select the one with the most uses in order
3690 // to keep the cost modeling heuristics in AddressingModeMatcher
3691 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003692 unsigned NumUses = V->getNumUses();
3693 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003694 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003695 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003696 AddrModeInsts = NewAddrModeInsts;
3697 }
3698 continue;
3699 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003700
Craig Topperc0196b12014-04-14 00:51:57 +00003701 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003702 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003703 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003704
Owen Anderson8ba5f392010-11-27 08:15:55 +00003705 // If the addressing mode couldn't be determined, or if multiple different
3706 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003707 if (!Consensus) {
3708 TPT.rollback(LastKnownGood);
3709 return false;
3710 }
3711 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003712
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003713 // Check to see if any of the instructions supersumed by this addr mode are
3714 // non-local to I's BB.
3715 bool AnyNonLocal = false;
3716 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003717 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003718 AnyNonLocal = true;
3719 break;
3720 }
3721 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003722
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003723 // If all the instructions matched are already in this BB, don't do anything.
3724 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003725 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003726 return false;
3727 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003728
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003729 // Insert this computation right after this user. Since our caller is
3730 // scanning from the top of the BB to the bottom, reuse of the expr are
3731 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003732 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003733
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003734 // Now that we determined the addressing expression we want to use and know
3735 // that we have to sink it into this block. Check to see if we have already
3736 // done this for some other load/store instr in this block. If so, reuse the
3737 // computation.
3738 Value *&SunkAddr = SunkAddrs[Addr];
3739 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003740 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003741 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003742 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003743 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003744 } else if (AddrSinkUsingGEPs ||
3745 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003746 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3747 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003748 // By default, we use the GEP-based method when AA is used later. This
3749 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3750 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003751 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003752 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003753 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003754
3755 // First, find the pointer.
3756 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3757 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003758 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003759 }
3760
3761 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3762 // We can't add more than one pointer together, nor can we scale a
3763 // pointer (both of which seem meaningless).
3764 if (ResultPtr || AddrMode.Scale != 1)
3765 return false;
3766
3767 ResultPtr = AddrMode.ScaledReg;
3768 AddrMode.Scale = 0;
3769 }
3770
3771 if (AddrMode.BaseGV) {
3772 if (ResultPtr)
3773 return false;
3774
3775 ResultPtr = AddrMode.BaseGV;
3776 }
3777
3778 // If the real base value actually came from an inttoptr, then the matcher
3779 // will look through it and provide only the integer value. In that case,
3780 // use it here.
3781 if (!ResultPtr && AddrMode.BaseReg) {
3782 ResultPtr =
3783 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003784 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003785 } else if (!ResultPtr && AddrMode.Scale == 1) {
3786 ResultPtr =
3787 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3788 AddrMode.Scale = 0;
3789 }
3790
3791 if (!ResultPtr &&
3792 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3793 SunkAddr = Constant::getNullValue(Addr->getType());
3794 } else if (!ResultPtr) {
3795 return false;
3796 } else {
3797 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003798 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3799 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003800
3801 // Start with the base register. Do this first so that subsequent address
3802 // matching finds it last, which will prevent it from trying to match it
3803 // as the scaled value in case it happens to be a mul. That would be
3804 // problematic if we've sunk a different mul for the scale, because then
3805 // we'd end up sinking both muls.
3806 if (AddrMode.BaseReg) {
3807 Value *V = AddrMode.BaseReg;
3808 if (V->getType() != IntPtrTy)
3809 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3810
3811 ResultIndex = V;
3812 }
3813
3814 // Add the scale value.
3815 if (AddrMode.Scale) {
3816 Value *V = AddrMode.ScaledReg;
3817 if (V->getType() == IntPtrTy) {
3818 // done.
3819 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3820 cast<IntegerType>(V->getType())->getBitWidth()) {
3821 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3822 } else {
3823 // It is only safe to sign extend the BaseReg if we know that the math
3824 // required to create it did not overflow before we extend it. Since
3825 // the original IR value was tossed in favor of a constant back when
3826 // the AddrMode was created we need to bail out gracefully if widths
3827 // do not match instead of extending it.
3828 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3829 if (I && (ResultIndex != AddrMode.BaseReg))
3830 I->eraseFromParent();
3831 return false;
3832 }
3833
3834 if (AddrMode.Scale != 1)
3835 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3836 "sunkaddr");
3837 if (ResultIndex)
3838 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3839 else
3840 ResultIndex = V;
3841 }
3842
3843 // Add in the Base Offset if present.
3844 if (AddrMode.BaseOffs) {
3845 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3846 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003847 // We need to add this separately from the scale above to help with
3848 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003849 if (ResultPtr->getType() != I8PtrTy)
3850 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003851 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003852 }
3853
3854 ResultIndex = V;
3855 }
3856
3857 if (!ResultIndex) {
3858 SunkAddr = ResultPtr;
3859 } else {
3860 if (ResultPtr->getType() != I8PtrTy)
3861 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003862 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003863 }
3864
3865 if (SunkAddr->getType() != Addr->getType())
3866 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3867 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003868 } else {
David Greene74e2d492010-01-05 01:27:11 +00003869 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003870 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003871 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003872 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003873
3874 // Start with the base register. Do this first so that subsequent address
3875 // matching finds it last, which will prevent it from trying to match it
3876 // as the scaled value in case it happens to be a mul. That would be
3877 // problematic if we've sunk a different mul for the scale, because then
3878 // we'd end up sinking both muls.
3879 if (AddrMode.BaseReg) {
3880 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003881 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003882 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003883 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003884 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003885 Result = V;
3886 }
3887
3888 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003889 if (AddrMode.Scale) {
3890 Value *V = AddrMode.ScaledReg;
3891 if (V->getType() == IntPtrTy) {
3892 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003893 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003894 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003895 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3896 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003897 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003898 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003899 // It is only safe to sign extend the BaseReg if we know that the math
3900 // required to create it did not overflow before we extend it. Since
3901 // the original IR value was tossed in favor of a constant back when
3902 // the AddrMode was created we need to bail out gracefully if widths
3903 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003904 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003905 if (I && (Result != AddrMode.BaseReg))
3906 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003907 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003908 }
3909 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003910 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3911 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003912 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003913 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003914 else
3915 Result = V;
3916 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003917
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003918 // Add in the BaseGV if present.
3919 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003920 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003921 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003922 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003923 else
3924 Result = V;
3925 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003926
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003927 // Add in the Base Offset if present.
3928 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003929 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003930 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003931 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003932 else
3933 Result = V;
3934 }
3935
Craig Topperc0196b12014-04-14 00:51:57 +00003936 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003937 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003938 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003939 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003940 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003941
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003942 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003943
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003944 // If we have no uses, recursively delete the value and all dead instructions
3945 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003946 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003947 // This can cause recursive deletion, which can invalidate our iterator.
3948 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00003949 Value *CurValue = &*CurInstIterator;
3950 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003951 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003952
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003953 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003954
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00003955 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003956 // If the iterator instruction was recursively deleted, start over at the
3957 // start of the block.
3958 CurInstIterator = BB->begin();
3959 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003960 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003961 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003962 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003963 return true;
3964}
3965
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003966/// If there are any memory operands, use OptimizeMemoryInst to sink their
3967/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003968bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003969 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003970
Eric Christopher11e4df72015-02-26 22:38:43 +00003971 const TargetRegisterInfo *TRI =
3972 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003973 TargetLowering::AsmOperandInfoVector TargetConstraints =
3974 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003975 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003976 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3977 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003978
Evan Cheng1da25002008-02-26 02:42:37 +00003979 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003980 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003981
Eli Friedman666bbe32008-02-26 18:37:49 +00003982 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3983 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003984 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003985 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003986 } else if (OpInfo.Type == InlineAsm::isInput)
3987 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003988 }
3989
3990 return MadeChange;
3991}
3992
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003993/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3994/// sign extensions.
3995static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3996 assert(!Inst->use_empty() && "Input must have at least one use");
3997 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3998 bool IsSExt = isa<SExtInst>(FirstUser);
3999 Type *ExtTy = FirstUser->getType();
4000 for (const User *U : Inst->users()) {
4001 const Instruction *UI = cast<Instruction>(U);
4002 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4003 return false;
4004 Type *CurTy = UI->getType();
4005 // Same input and output types: Same instruction after CSE.
4006 if (CurTy == ExtTy)
4007 continue;
4008
4009 // If IsSExt is true, we are in this situation:
4010 // a = Inst
4011 // b = sext ty1 a to ty2
4012 // c = sext ty1 a to ty3
4013 // Assuming ty2 is shorter than ty3, this could be turned into:
4014 // a = Inst
4015 // b = sext ty1 a to ty2
4016 // c = sext ty2 b to ty3
4017 // However, the last sext is not free.
4018 if (IsSExt)
4019 return false;
4020
4021 // This is a ZExt, maybe this is free to extend from one type to another.
4022 // In that case, we would not account for a different use.
4023 Type *NarrowTy;
4024 Type *LargeTy;
4025 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4026 CurTy->getScalarType()->getIntegerBitWidth()) {
4027 NarrowTy = CurTy;
4028 LargeTy = ExtTy;
4029 } else {
4030 NarrowTy = ExtTy;
4031 LargeTy = CurTy;
4032 }
4033
4034 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4035 return false;
4036 }
4037 // All uses are the same or can be derived from one another for free.
4038 return true;
4039}
4040
4041/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4042/// load instruction.
4043/// If an ext(load) can be formed, it is returned via \p LI for the load
4044/// and \p Inst for the extension.
4045/// Otherwise LI == nullptr and Inst == nullptr.
4046/// When some promotion happened, \p TPT contains the proper state to
4047/// revert them.
4048///
4049/// \return true when promoting was necessary to expose the ext(load)
4050/// opportunity, false otherwise.
4051///
4052/// Example:
4053/// \code
4054/// %ld = load i32* %addr
4055/// %add = add nuw i32 %ld, 4
4056/// %zext = zext i32 %add to i64
4057/// \endcode
4058/// =>
4059/// \code
4060/// %ld = load i32* %addr
4061/// %zext = zext i32 %ld to i64
4062/// %add = add nuw i64 %zext, 4
4063/// \encode
4064/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004065bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004066 LoadInst *&LI, Instruction *&Inst,
4067 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004068 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004069 // Iterate over all the extensions to see if one form an ext(load).
4070 for (auto I : Exts) {
4071 // Check if we directly have ext(load).
4072 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4073 Inst = I;
4074 // No promotion happened here.
4075 return false;
4076 }
4077 // Check whether or not we want to do any promotion.
4078 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4079 continue;
4080 // Get the action to perform the promotion.
4081 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004082 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004083 // Check if we can promote.
4084 if (!TPH)
4085 continue;
4086 // Save the current state.
4087 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4088 TPT.getRestorationPoint();
4089 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004090 unsigned NewCreatedInstsCost = 0;
4091 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004092 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004093 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4094 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004095 assert(PromotedVal &&
4096 "TypePromotionHelper should have filtered out those cases");
4097
4098 // We would be able to merge only one extension in a load.
4099 // Therefore, if we have more than 1 new extension we heuristically
4100 // cut this search path, because it means we degrade the code quality.
4101 // With exactly 2, the transformation is neutral, because we will merge
4102 // one extension but leave one. However, we optimistically keep going,
4103 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004104 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4105 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004106 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004107 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004108 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004109 // The promotion is not profitable, rollback to the previous state.
4110 TPT.rollback(LastKnownGood);
4111 continue;
4112 }
4113 // The promotion is profitable.
4114 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004115 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004116 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004117 // If we have created a new extension, i.e., now we have two
4118 // extensions. We must make sure one of them is merged with
4119 // the load, otherwise we may degrade the code quality.
4120 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4121 // Promotion happened.
4122 return true;
4123 // If this does not help to expose an ext(load) then, rollback.
4124 TPT.rollback(LastKnownGood);
4125 }
4126 // None of the extension can form an ext(load).
4127 LI = nullptr;
4128 Inst = nullptr;
4129 return false;
4130}
4131
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004132/// Move a zext or sext fed by a load into the same basic block as the load,
4133/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4134/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004135/// \p I[in/out] the extension may be modified during the process if some
4136/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004137///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004138bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004139 // Try to promote a chain of computation if it allows to form
4140 // an extended load.
4141 TypePromotionTransaction TPT;
4142 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4143 TPT.getRestorationPoint();
4144 SmallVector<Instruction *, 1> Exts;
4145 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004146 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004147 LoadInst *LI = nullptr;
4148 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004149 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004150 if (!LI || !I) {
4151 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4152 "the code must remain the same");
4153 I = OldExt;
4154 return false;
4155 }
Dan Gohman99429a02009-10-16 20:59:35 +00004156
4157 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004158 // Make the cheap checks first if we did not promote.
4159 // If we promoted, we need to check if it is indeed profitable.
4160 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004161 return false;
4162
Mehdi Amini44ede332015-07-09 02:09:04 +00004163 EVT VT = TLI->getValueType(*DL, I->getType());
4164 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004165
Dan Gohman99429a02009-10-16 20:59:35 +00004166 // If the load has other users and the truncate is not free, this probably
4167 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004168 if (!LI->hasOneUse() && TLI &&
4169 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004170 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4171 I = OldExt;
4172 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004173 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004174 }
Dan Gohman99429a02009-10-16 20:59:35 +00004175
4176 // Check whether the target supports casts folded into loads.
4177 unsigned LType;
4178 if (isa<ZExtInst>(I))
4179 LType = ISD::ZEXTLOAD;
4180 else {
4181 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4182 LType = ISD::SEXTLOAD;
4183 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004184 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004185 I = OldExt;
4186 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004187 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004188 }
Dan Gohman99429a02009-10-16 20:59:35 +00004189
4190 // Move the extend into the same block as the load, so that SelectionDAG
4191 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004192 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004193 I->removeFromParent();
4194 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004195 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004196 return true;
4197}
4198
Sanjay Patelfc580a62015-09-21 23:03:16 +00004199bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004200 BasicBlock *DefBB = I->getParent();
4201
Bob Wilsonff714f92010-09-21 21:44:14 +00004202 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004203 // other uses of the source with result of extension.
4204 Value *Src = I->getOperand(0);
4205 if (Src->hasOneUse())
4206 return false;
4207
Evan Cheng2011df42007-12-13 07:50:36 +00004208 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004209 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004210 return false;
4211
Evan Cheng7bc89422007-12-12 00:51:06 +00004212 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004213 // this block.
4214 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004215 return false;
4216
Evan Chengd3d80172007-12-05 23:58:20 +00004217 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004218 for (User *U : I->users()) {
4219 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004220
4221 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004222 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004223 if (UserBB == DefBB) continue;
4224 DefIsLiveOut = true;
4225 break;
4226 }
4227 if (!DefIsLiveOut)
4228 return false;
4229
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004230 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004231 for (User *U : Src->users()) {
4232 Instruction *UI = cast<Instruction>(U);
4233 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004234 if (UserBB == DefBB) continue;
4235 // Be conservative. We don't want this xform to end up introducing
4236 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004237 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004238 return false;
4239 }
4240
Evan Chengd3d80172007-12-05 23:58:20 +00004241 // InsertedTruncs - Only insert one trunc in each block once.
4242 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4243
4244 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004245 for (Use &U : Src->uses()) {
4246 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004247
4248 // Figure out which BB this ext is used in.
4249 BasicBlock *UserBB = User->getParent();
4250 if (UserBB == DefBB) continue;
4251
4252 // Both src and def are live in this block. Rewrite the use.
4253 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4254
4255 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004256 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004257 assert(InsertPt != UserBB->end());
4258 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004259 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004260 }
4261
4262 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004263 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004264 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004265 MadeChange = true;
4266 }
4267
4268 return MadeChange;
4269}
4270
Geoff Berry5256fca2015-11-20 22:34:39 +00004271// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4272// just after the load if the target can fold this into one extload instruction,
4273// with the hope of eliminating some of the other later "and" instructions using
4274// the loaded value. "and"s that are made trivially redundant by the insertion
4275// of the new "and" are removed by this function, while others (e.g. those whose
4276// path from the load goes through a phi) are left for isel to potentially
4277// remove.
4278//
4279// For example:
4280//
4281// b0:
4282// x = load i32
4283// ...
4284// b1:
4285// y = and x, 0xff
4286// z = use y
4287//
4288// becomes:
4289//
4290// b0:
4291// x = load i32
4292// x' = and x, 0xff
4293// ...
4294// b1:
4295// z = use x'
4296//
4297// whereas:
4298//
4299// b0:
4300// x1 = load i32
4301// ...
4302// b1:
4303// x2 = load i32
4304// ...
4305// b2:
4306// x = phi x1, x2
4307// y = and x, 0xff
4308//
4309// becomes (after a call to optimizeLoadExt for each load):
4310//
4311// b0:
4312// x1 = load i32
4313// x1' = and x1, 0xff
4314// ...
4315// b1:
4316// x2 = load i32
4317// x2' = and x2, 0xff
4318// ...
4319// b2:
4320// x = phi x1', x2'
4321// y = and x, 0xff
4322//
4323
4324bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4325
4326 if (!Load->isSimple() ||
4327 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4328 return false;
4329
4330 // Skip loads we've already transformed or have no reason to transform.
4331 if (Load->hasOneUse()) {
4332 User *LoadUser = *Load->user_begin();
4333 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4334 !dyn_cast<PHINode>(LoadUser))
4335 return false;
4336 }
4337
4338 // Look at all uses of Load, looking through phis, to determine how many bits
4339 // of the loaded value are needed.
4340 SmallVector<Instruction *, 8> WorkList;
4341 SmallPtrSet<Instruction *, 16> Visited;
4342 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4343 for (auto *U : Load->users())
4344 WorkList.push_back(cast<Instruction>(U));
4345
4346 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4347 unsigned BitWidth = LoadResultVT.getSizeInBits();
4348 APInt DemandBits(BitWidth, 0);
4349 APInt WidestAndBits(BitWidth, 0);
4350
4351 while (!WorkList.empty()) {
4352 Instruction *I = WorkList.back();
4353 WorkList.pop_back();
4354
4355 // Break use-def graph loops.
4356 if (!Visited.insert(I).second)
4357 continue;
4358
4359 // For a PHI node, push all of its users.
4360 if (auto *Phi = dyn_cast<PHINode>(I)) {
4361 for (auto *U : Phi->users())
4362 WorkList.push_back(cast<Instruction>(U));
4363 continue;
4364 }
4365
4366 switch (I->getOpcode()) {
4367 case llvm::Instruction::And: {
4368 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4369 if (!AndC)
4370 return false;
4371 APInt AndBits = AndC->getValue();
4372 DemandBits |= AndBits;
4373 // Keep track of the widest and mask we see.
4374 if (AndBits.ugt(WidestAndBits))
4375 WidestAndBits = AndBits;
4376 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4377 AndsToMaybeRemove.push_back(I);
4378 break;
4379 }
4380
4381 case llvm::Instruction::Shl: {
4382 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4383 if (!ShlC)
4384 return false;
4385 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4386 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4387 DemandBits |= ShlDemandBits;
4388 break;
4389 }
4390
4391 case llvm::Instruction::Trunc: {
4392 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4393 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4394 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4395 DemandBits |= TruncBits;
4396 break;
4397 }
4398
4399 default:
4400 return false;
4401 }
4402 }
4403
4404 uint32_t ActiveBits = DemandBits.getActiveBits();
4405 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4406 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4407 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4408 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4409 // followed by an AND.
4410 // TODO: Look into removing this restriction by fixing backends to either
4411 // return false for isLoadExtLegal for i1 or have them select this pattern to
4412 // a single instruction.
4413 //
4414 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4415 // mask, since these are the only ands that will be removed by isel.
4416 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4417 WidestAndBits != DemandBits)
4418 return false;
4419
4420 LLVMContext &Ctx = Load->getType()->getContext();
4421 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4422 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4423
4424 // Reject cases that won't be matched as extloads.
4425 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4426 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4427 return false;
4428
4429 IRBuilder<> Builder(Load->getNextNode());
4430 auto *NewAnd = dyn_cast<Instruction>(
4431 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4432
4433 // Replace all uses of load with new and (except for the use of load in the
4434 // new and itself).
4435 Load->replaceAllUsesWith(NewAnd);
4436 NewAnd->setOperand(0, Load);
4437
4438 // Remove any and instructions that are now redundant.
4439 for (auto *And : AndsToMaybeRemove)
4440 // Check that the and mask is the same as the one we decided to put on the
4441 // new and.
4442 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4443 And->replaceAllUsesWith(NewAnd);
4444 if (&*CurInstIterator == And)
4445 CurInstIterator = std::next(And->getIterator());
4446 And->eraseFromParent();
4447 ++NumAndUses;
4448 }
4449
4450 ++NumAndsAdded;
4451 return true;
4452}
4453
Sanjay Patel69a50a12015-10-19 21:59:12 +00004454/// Check if V (an operand of a select instruction) is an expensive instruction
4455/// that is only used once.
4456static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4457 auto *I = dyn_cast<Instruction>(V);
4458 // If it's safe to speculatively execute, then it should not have side
4459 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004460 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4461 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004462}
4463
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004464/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004465static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
4466 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004467 // FIXME: This should use the same heuristics as IfConversion to determine
4468 // whether a select is better represented as a branch. This requires that
4469 // branch probability metadata is preserved for the select, which is not the
4470 // case currently.
4471
4472 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4473
Sanjay Patel4e652762015-09-28 22:14:51 +00004474 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4475 // comparison condition. If the compare has more than one use, there's
4476 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004477 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004478 return false;
4479
4480 Value *CmpOp0 = Cmp->getOperand(0);
4481 Value *CmpOp1 = Cmp->getOperand(1);
4482
Sanjay Patel4e652762015-09-28 22:14:51 +00004483 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
4484 // on a load from memory. But if the load is used more than once, do not
4485 // change the select to a branch because the load is probably needed
4486 // regardless of whether the branch is taken or not.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004487 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
4488 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
4489 return true;
4490
4491 // If either operand of the select is expensive and only needed on one side
4492 // of the select, we should form a branch.
4493 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4494 sinkSelectOperand(TTI, SI->getFalseValue()))
4495 return true;
4496
4497 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004498}
4499
4500
Nadav Rotem9d832022012-09-02 12:10:19 +00004501/// If we have a SelectInst that will likely profit from branch prediction,
4502/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004503bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00004504 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4505
4506 // Can we convert the 'select' to CF ?
4507 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004508 return false;
4509
Nadav Rotem9d832022012-09-02 12:10:19 +00004510 TargetLowering::SelectSupportKind SelectKind;
4511 if (VectorCond)
4512 SelectKind = TargetLowering::VectorMaskSelect;
4513 else if (SI->getType()->isVectorTy())
4514 SelectKind = TargetLowering::ScalarCondVectorVal;
4515 else
4516 SelectKind = TargetLowering::ScalarValSelect;
4517
4518 // Do we have efficient codegen support for this kind of 'selects' ?
4519 if (TLI->isSelectSupported(SelectKind)) {
4520 // We have efficient codegen support for the select instruction.
4521 // Check if it is profitable to keep this 'select'.
4522 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00004523 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00004524 return false;
4525 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004526
4527 ModifiedDT = true;
4528
Sanjay Patel69a50a12015-10-19 21:59:12 +00004529 // Transform a sequence like this:
4530 // start:
4531 // %cmp = cmp uge i32 %a, %b
4532 // %sel = select i1 %cmp, i32 %c, i32 %d
4533 //
4534 // Into:
4535 // start:
4536 // %cmp = cmp uge i32 %a, %b
4537 // br i1 %cmp, label %select.true, label %select.false
4538 // select.true:
4539 // br label %select.end
4540 // select.false:
4541 // br label %select.end
4542 // select.end:
4543 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4544 //
4545 // In addition, we may sink instructions that produce %c or %d from
4546 // the entry block into the destination(s) of the new branch.
4547 // If the true or false blocks do not contain a sunken instruction, that
4548 // block and its branch may be optimized away. In that case, one side of the
4549 // first branch will point directly to select.end, and the corresponding PHI
4550 // predecessor block will be the start block.
4551
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004552 // First, we split the block containing the select into 2 blocks.
4553 BasicBlock *StartBlock = SI->getParent();
4554 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004555 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004556
Sanjay Patel69a50a12015-10-19 21:59:12 +00004557 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004558 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004559
4560 // These are the new basic blocks for the conditional branch.
4561 // At least one will become an actual new basic block.
4562 BasicBlock *TrueBlock = nullptr;
4563 BasicBlock *FalseBlock = nullptr;
4564
4565 // Sink expensive instructions into the conditional blocks to avoid executing
4566 // them speculatively.
4567 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4568 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4569 EndBlock->getParent(), EndBlock);
4570 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4571 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4572 TrueInst->moveBefore(TrueBranch);
4573 }
4574 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4575 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4576 EndBlock->getParent(), EndBlock);
4577 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4578 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4579 FalseInst->moveBefore(FalseBranch);
4580 }
4581
4582 // If there was nothing to sink, then arbitrarily choose the 'false' side
4583 // for a new input value to the PHI.
4584 if (TrueBlock == FalseBlock) {
4585 assert(TrueBlock == nullptr &&
4586 "Unexpected basic block transform while optimizing select");
4587
4588 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4589 EndBlock->getParent(), EndBlock);
4590 BranchInst::Create(EndBlock, FalseBlock);
4591 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004592
4593 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004594 // If we did not create a new block for one of the 'true' or 'false' paths
4595 // of the condition, it means that side of the branch goes to the end block
4596 // directly and the path originates from the start block from the point of
4597 // view of the new PHI.
4598 if (TrueBlock == nullptr) {
4599 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
4600 TrueBlock = StartBlock;
4601 } else if (FalseBlock == nullptr) {
4602 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4603 FalseBlock = StartBlock;
4604 } else {
4605 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4606 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004607
4608 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004609 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004610 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004611 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4612 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4613
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004614 SI->replaceAllUsesWith(PN);
4615 SI->eraseFromParent();
4616
4617 // Instruct OptimizeBlock to skip to the next block.
4618 CurInstIterator = StartBlock->end();
4619 ++NumSelectsExpanded;
4620 return true;
4621}
4622
Benjamin Kramer573ff362014-03-01 17:24:40 +00004623static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004624 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4625 int SplatElem = -1;
4626 for (unsigned i = 0; i < Mask.size(); ++i) {
4627 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4628 return false;
4629 SplatElem = Mask[i];
4630 }
4631
4632 return true;
4633}
4634
4635/// Some targets have expensive vector shifts if the lanes aren't all the same
4636/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4637/// it's often worth sinking a shufflevector splat down to its use so that
4638/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004639bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004640 BasicBlock *DefBB = SVI->getParent();
4641
4642 // Only do this xform if variable vector shifts are particularly expensive.
4643 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4644 return false;
4645
4646 // We only expect better codegen by sinking a shuffle if we can recognise a
4647 // constant splat.
4648 if (!isBroadcastShuffle(SVI))
4649 return false;
4650
4651 // InsertedShuffles - Only insert a shuffle in each block once.
4652 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4653
4654 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004655 for (User *U : SVI->users()) {
4656 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004657
4658 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004659 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004660 if (UserBB == DefBB) continue;
4661
4662 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004663 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004664
4665 // Everything checks out, sink the shuffle if the user's block doesn't
4666 // already have a copy.
4667 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4668
4669 if (!InsertedShuffle) {
4670 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004671 assert(InsertPt != UserBB->end());
4672 InsertedShuffle =
4673 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4674 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004675 }
4676
Chandler Carruthcdf47882014-03-09 03:16:01 +00004677 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004678 MadeChange = true;
4679 }
4680
4681 // If we removed all uses, nuke the shuffle.
4682 if (SVI->use_empty()) {
4683 SVI->eraseFromParent();
4684 MadeChange = true;
4685 }
4686
4687 return MadeChange;
4688}
4689
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004690bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4691 if (!TLI || !DL)
4692 return false;
4693
4694 Value *Cond = SI->getCondition();
4695 Type *OldType = Cond->getType();
4696 LLVMContext &Context = Cond->getContext();
4697 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4698 unsigned RegWidth = RegType.getSizeInBits();
4699
4700 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4701 return false;
4702
4703 // If the register width is greater than the type width, expand the condition
4704 // of the switch instruction and each case constant to the width of the
4705 // register. By widening the type of the switch condition, subsequent
4706 // comparisons (for case comparisons) will not need to be extended to the
4707 // preferred register width, so we will potentially eliminate N-1 extends,
4708 // where N is the number of cases in the switch.
4709 auto *NewType = Type::getIntNTy(Context, RegWidth);
4710
4711 // Zero-extend the switch condition and case constants unless the switch
4712 // condition is a function argument that is already being sign-extended.
4713 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4714 // everything instead.
4715 Instruction::CastOps ExtType = Instruction::ZExt;
4716 if (auto *Arg = dyn_cast<Argument>(Cond))
4717 if (Arg->hasSExtAttr())
4718 ExtType = Instruction::SExt;
4719
4720 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4721 ExtInst->insertBefore(SI);
4722 SI->setCondition(ExtInst);
4723 for (SwitchInst::CaseIt Case : SI->cases()) {
4724 APInt NarrowConst = Case.getCaseValue()->getValue();
4725 APInt WideConst = (ExtType == Instruction::ZExt) ?
4726 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4727 Case.setValue(ConstantInt::get(Context, WideConst));
4728 }
4729
4730 return true;
4731}
4732
Quentin Colombetc32615d2014-10-31 17:52:53 +00004733namespace {
4734/// \brief Helper class to promote a scalar operation to a vector one.
4735/// This class is used to move downward extractelement transition.
4736/// E.g.,
4737/// a = vector_op <2 x i32>
4738/// b = extractelement <2 x i32> a, i32 0
4739/// c = scalar_op b
4740/// store c
4741///
4742/// =>
4743/// a = vector_op <2 x i32>
4744/// c = vector_op a (equivalent to scalar_op on the related lane)
4745/// * d = extractelement <2 x i32> c, i32 0
4746/// * store d
4747/// Assuming both extractelement and store can be combine, we get rid of the
4748/// transition.
4749class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004750 /// DataLayout associated with the current module.
4751 const DataLayout &DL;
4752
Quentin Colombetc32615d2014-10-31 17:52:53 +00004753 /// Used to perform some checks on the legality of vector operations.
4754 const TargetLowering &TLI;
4755
4756 /// Used to estimated the cost of the promoted chain.
4757 const TargetTransformInfo &TTI;
4758
4759 /// The transition being moved downwards.
4760 Instruction *Transition;
4761 /// The sequence of instructions to be promoted.
4762 SmallVector<Instruction *, 4> InstsToBePromoted;
4763 /// Cost of combining a store and an extract.
4764 unsigned StoreExtractCombineCost;
4765 /// Instruction that will be combined with the transition.
4766 Instruction *CombineInst;
4767
4768 /// \brief The instruction that represents the current end of the transition.
4769 /// Since we are faking the promotion until we reach the end of the chain
4770 /// of computation, we need a way to get the current end of the transition.
4771 Instruction *getEndOfTransition() const {
4772 if (InstsToBePromoted.empty())
4773 return Transition;
4774 return InstsToBePromoted.back();
4775 }
4776
4777 /// \brief Return the index of the original value in the transition.
4778 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4779 /// c, is at index 0.
4780 unsigned getTransitionOriginalValueIdx() const {
4781 assert(isa<ExtractElementInst>(Transition) &&
4782 "Other kind of transitions are not supported yet");
4783 return 0;
4784 }
4785
4786 /// \brief Return the index of the index in the transition.
4787 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4788 /// is at index 1.
4789 unsigned getTransitionIdx() const {
4790 assert(isa<ExtractElementInst>(Transition) &&
4791 "Other kind of transitions are not supported yet");
4792 return 1;
4793 }
4794
4795 /// \brief Get the type of the transition.
4796 /// This is the type of the original value.
4797 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4798 /// transition is <2 x i32>.
4799 Type *getTransitionType() const {
4800 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4801 }
4802
4803 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4804 /// I.e., we have the following sequence:
4805 /// Def = Transition <ty1> a to <ty2>
4806 /// b = ToBePromoted <ty2> Def, ...
4807 /// =>
4808 /// b = ToBePromoted <ty1> a, ...
4809 /// Def = Transition <ty1> ToBePromoted to <ty2>
4810 void promoteImpl(Instruction *ToBePromoted);
4811
4812 /// \brief Check whether or not it is profitable to promote all the
4813 /// instructions enqueued to be promoted.
4814 bool isProfitableToPromote() {
4815 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4816 unsigned Index = isa<ConstantInt>(ValIdx)
4817 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4818 : -1;
4819 Type *PromotedType = getTransitionType();
4820
4821 StoreInst *ST = cast<StoreInst>(CombineInst);
4822 unsigned AS = ST->getPointerAddressSpace();
4823 unsigned Align = ST->getAlignment();
4824 // Check if this store is supported.
4825 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004826 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4827 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004828 // If this is not supported, there is no way we can combine
4829 // the extract with the store.
4830 return false;
4831 }
4832
4833 // The scalar chain of computation has to pay for the transition
4834 // scalar to vector.
4835 // The vector chain has to account for the combining cost.
4836 uint64_t ScalarCost =
4837 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4838 uint64_t VectorCost = StoreExtractCombineCost;
4839 for (const auto &Inst : InstsToBePromoted) {
4840 // Compute the cost.
4841 // By construction, all instructions being promoted are arithmetic ones.
4842 // Moreover, one argument is a constant that can be viewed as a splat
4843 // constant.
4844 Value *Arg0 = Inst->getOperand(0);
4845 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4846 isa<ConstantFP>(Arg0);
4847 TargetTransformInfo::OperandValueKind Arg0OVK =
4848 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4849 : TargetTransformInfo::OK_AnyValue;
4850 TargetTransformInfo::OperandValueKind Arg1OVK =
4851 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4852 : TargetTransformInfo::OK_AnyValue;
4853 ScalarCost += TTI.getArithmeticInstrCost(
4854 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4855 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4856 Arg0OVK, Arg1OVK);
4857 }
4858 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4859 << ScalarCost << "\nVector: " << VectorCost << '\n');
4860 return ScalarCost > VectorCost;
4861 }
4862
4863 /// \brief Generate a constant vector with \p Val with the same
4864 /// number of elements as the transition.
4865 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004866 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004867 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4868 /// otherwise we generate a vector with as many undef as possible:
4869 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4870 /// used at the index of the extract.
4871 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4872 unsigned ExtractIdx = UINT_MAX;
4873 if (!UseSplat) {
4874 // If we cannot determine where the constant must be, we have to
4875 // use a splat constant.
4876 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4877 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4878 ExtractIdx = CstVal->getSExtValue();
4879 else
4880 UseSplat = true;
4881 }
4882
4883 unsigned End = getTransitionType()->getVectorNumElements();
4884 if (UseSplat)
4885 return ConstantVector::getSplat(End, Val);
4886
4887 SmallVector<Constant *, 4> ConstVec;
4888 UndefValue *UndefVal = UndefValue::get(Val->getType());
4889 for (unsigned Idx = 0; Idx != End; ++Idx) {
4890 if (Idx == ExtractIdx)
4891 ConstVec.push_back(Val);
4892 else
4893 ConstVec.push_back(UndefVal);
4894 }
4895 return ConstantVector::get(ConstVec);
4896 }
4897
4898 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4899 /// in \p Use can trigger undefined behavior.
4900 static bool canCauseUndefinedBehavior(const Instruction *Use,
4901 unsigned OperandIdx) {
4902 // This is not safe to introduce undef when the operand is on
4903 // the right hand side of a division-like instruction.
4904 if (OperandIdx != 1)
4905 return false;
4906 switch (Use->getOpcode()) {
4907 default:
4908 return false;
4909 case Instruction::SDiv:
4910 case Instruction::UDiv:
4911 case Instruction::SRem:
4912 case Instruction::URem:
4913 return true;
4914 case Instruction::FDiv:
4915 case Instruction::FRem:
4916 return !Use->hasNoNaNs();
4917 }
4918 llvm_unreachable(nullptr);
4919 }
4920
4921public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004922 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4923 const TargetTransformInfo &TTI, Instruction *Transition,
4924 unsigned CombineCost)
4925 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004926 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4927 assert(Transition && "Do not know how to promote null");
4928 }
4929
4930 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4931 bool canPromote(const Instruction *ToBePromoted) const {
4932 // We could support CastInst too.
4933 return isa<BinaryOperator>(ToBePromoted);
4934 }
4935
4936 /// \brief Check if it is profitable to promote \p ToBePromoted
4937 /// by moving downward the transition through.
4938 bool shouldPromote(const Instruction *ToBePromoted) const {
4939 // Promote only if all the operands can be statically expanded.
4940 // Indeed, we do not want to introduce any new kind of transitions.
4941 for (const Use &U : ToBePromoted->operands()) {
4942 const Value *Val = U.get();
4943 if (Val == getEndOfTransition()) {
4944 // If the use is a division and the transition is on the rhs,
4945 // we cannot promote the operation, otherwise we may create a
4946 // division by zero.
4947 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4948 return false;
4949 continue;
4950 }
4951 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4952 !isa<ConstantFP>(Val))
4953 return false;
4954 }
4955 // Check that the resulting operation is legal.
4956 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4957 if (!ISDOpcode)
4958 return false;
4959 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004960 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004961 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004962 }
4963
4964 /// \brief Check whether or not \p Use can be combined
4965 /// with the transition.
4966 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4967 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4968
4969 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4970 void enqueueForPromotion(Instruction *ToBePromoted) {
4971 InstsToBePromoted.push_back(ToBePromoted);
4972 }
4973
4974 /// \brief Set the instruction that will be combined with the transition.
4975 void recordCombineInstruction(Instruction *ToBeCombined) {
4976 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4977 CombineInst = ToBeCombined;
4978 }
4979
4980 /// \brief Promote all the instructions enqueued for promotion if it is
4981 /// is profitable.
4982 /// \return True if the promotion happened, false otherwise.
4983 bool promote() {
4984 // Check if there is something to promote.
4985 // Right now, if we do not have anything to combine with,
4986 // we assume the promotion is not profitable.
4987 if (InstsToBePromoted.empty() || !CombineInst)
4988 return false;
4989
4990 // Check cost.
4991 if (!StressStoreExtract && !isProfitableToPromote())
4992 return false;
4993
4994 // Promote.
4995 for (auto &ToBePromoted : InstsToBePromoted)
4996 promoteImpl(ToBePromoted);
4997 InstsToBePromoted.clear();
4998 return true;
4999 }
5000};
5001} // End of anonymous namespace.
5002
5003void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5004 // At this point, we know that all the operands of ToBePromoted but Def
5005 // can be statically promoted.
5006 // For Def, we need to use its parameter in ToBePromoted:
5007 // b = ToBePromoted ty1 a
5008 // Def = Transition ty1 b to ty2
5009 // Move the transition down.
5010 // 1. Replace all uses of the promoted operation by the transition.
5011 // = ... b => = ... Def.
5012 assert(ToBePromoted->getType() == Transition->getType() &&
5013 "The type of the result of the transition does not match "
5014 "the final type");
5015 ToBePromoted->replaceAllUsesWith(Transition);
5016 // 2. Update the type of the uses.
5017 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5018 Type *TransitionTy = getTransitionType();
5019 ToBePromoted->mutateType(TransitionTy);
5020 // 3. Update all the operands of the promoted operation with promoted
5021 // operands.
5022 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5023 for (Use &U : ToBePromoted->operands()) {
5024 Value *Val = U.get();
5025 Value *NewVal = nullptr;
5026 if (Val == Transition)
5027 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5028 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5029 isa<ConstantFP>(Val)) {
5030 // Use a splat constant if it is not safe to use undef.
5031 NewVal = getConstantVector(
5032 cast<Constant>(Val),
5033 isa<UndefValue>(Val) ||
5034 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5035 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005036 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5037 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005038 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5039 }
5040 Transition->removeFromParent();
5041 Transition->insertAfter(ToBePromoted);
5042 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5043}
5044
5045/// Some targets can do store(extractelement) with one instruction.
5046/// Try to push the extractelement towards the stores when the target
5047/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005048bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005049 unsigned CombineCost = UINT_MAX;
5050 if (DisableStoreExtract || !TLI ||
5051 (!StressStoreExtract &&
5052 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5053 Inst->getOperand(1), CombineCost)))
5054 return false;
5055
5056 // At this point we know that Inst is a vector to scalar transition.
5057 // Try to move it down the def-use chain, until:
5058 // - We can combine the transition with its single use
5059 // => we got rid of the transition.
5060 // - We escape the current basic block
5061 // => we would need to check that we are moving it at a cheaper place and
5062 // we do not do that for now.
5063 BasicBlock *Parent = Inst->getParent();
5064 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005065 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005066 // If the transition has more than one use, assume this is not going to be
5067 // beneficial.
5068 while (Inst->hasOneUse()) {
5069 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5070 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5071
5072 if (ToBePromoted->getParent() != Parent) {
5073 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5074 << ToBePromoted->getParent()->getName()
5075 << ") than the transition (" << Parent->getName() << ").\n");
5076 return false;
5077 }
5078
5079 if (VPH.canCombine(ToBePromoted)) {
5080 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5081 << "will be combined with: " << *ToBePromoted << '\n');
5082 VPH.recordCombineInstruction(ToBePromoted);
5083 bool Changed = VPH.promote();
5084 NumStoreExtractExposed += Changed;
5085 return Changed;
5086 }
5087
5088 DEBUG(dbgs() << "Try promoting.\n");
5089 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5090 return false;
5091
5092 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5093
5094 VPH.enqueueForPromotion(ToBePromoted);
5095 Inst = ToBePromoted;
5096 }
5097 return false;
5098}
5099
Sanjay Patelfc580a62015-09-21 23:03:16 +00005100bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005101 // Bail out if we inserted the instruction to prevent optimizations from
5102 // stepping on each other's toes.
5103 if (InsertedInsts.count(I))
5104 return false;
5105
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005106 if (PHINode *P = dyn_cast<PHINode>(I)) {
5107 // It is possible for very late stage optimizations (such as SimplifyCFG)
5108 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5109 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005110 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005111 P->replaceAllUsesWith(V);
5112 P->eraseFromParent();
5113 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005114 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005115 }
Chris Lattneree588de2011-01-15 07:29:01 +00005116 return false;
5117 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005118
Chris Lattneree588de2011-01-15 07:29:01 +00005119 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005120 // If the source of the cast is a constant, then this should have
5121 // already been constant folded. The only reason NOT to constant fold
5122 // it is if something (e.g. LSR) was careful to place the constant
5123 // evaluation in a block other than then one that uses it (e.g. to hoist
5124 // the address of globals out of a loop). If this is the case, we don't
5125 // want to forward-subst the cast.
5126 if (isa<Constant>(CI->getOperand(0)))
5127 return false;
5128
Mehdi Amini44ede332015-07-09 02:09:04 +00005129 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005130 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005131
Chris Lattneree588de2011-01-15 07:29:01 +00005132 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005133 /// Sink a zext or sext into its user blocks if the target type doesn't
5134 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005135 if (TLI &&
5136 TLI->getTypeAction(CI->getContext(),
5137 TLI->getValueType(*DL, CI->getType())) ==
5138 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005139 return SinkCast(CI);
5140 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005141 bool MadeChange = moveExtToFormExtLoad(I);
5142 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005143 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005144 }
Chris Lattneree588de2011-01-15 07:29:01 +00005145 return false;
5146 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005147
Chris Lattneree588de2011-01-15 07:29:01 +00005148 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005149 if (!TLI || !TLI->hasMultipleConditionRegisters())
5150 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005151
Chris Lattneree588de2011-01-15 07:29:01 +00005152 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005153 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005154 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005155 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005156 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005157 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5158 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005159 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005160 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005161 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005162
Chris Lattneree588de2011-01-15 07:29:01 +00005163 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005164 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005165 if (TLI) {
5166 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005167 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005168 SI->getOperand(0)->getType(), AS);
5169 }
Chris Lattneree588de2011-01-15 07:29:01 +00005170 return false;
5171 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005172
Yi Jiangd069f632014-04-21 19:34:27 +00005173 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5174
5175 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5176 BinOp->getOpcode() == Instruction::LShr)) {
5177 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5178 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005179 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005180
5181 return false;
5182 }
5183
Chris Lattneree588de2011-01-15 07:29:01 +00005184 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005185 if (GEPI->hasAllZeroIndices()) {
5186 /// The GEP operand must be a pointer, so must its result -> BitCast
5187 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5188 GEPI->getName(), GEPI);
5189 GEPI->replaceAllUsesWith(NC);
5190 GEPI->eraseFromParent();
5191 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005192 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005193 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005194 }
Chris Lattneree588de2011-01-15 07:29:01 +00005195 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005196 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005197
Chris Lattneree588de2011-01-15 07:29:01 +00005198 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005199 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005200
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005201 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005202 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005203
Tim Northoveraeb8e062014-02-19 10:02:43 +00005204 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005205 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005206
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005207 if (auto *Switch = dyn_cast<SwitchInst>(I))
5208 return optimizeSwitchInst(Switch);
5209
Quentin Colombetc32615d2014-10-31 17:52:53 +00005210 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005211 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005212
Chris Lattneree588de2011-01-15 07:29:01 +00005213 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005214}
5215
James Molloyf01488e2016-01-15 09:20:19 +00005216/// Given an OR instruction, check to see if this is a bitreverse
5217/// idiom. If so, insert the new intrinsic and return true.
5218static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5219 const TargetLowering &TLI) {
5220 if (!I.getType()->isIntegerTy() ||
5221 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5222 TLI.getValueType(DL, I.getType(), true)))
5223 return false;
5224
5225 SmallVector<Instruction*, 4> Insts;
5226 if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
5227 return false;
5228 Instruction *LastInst = Insts.back();
5229 I.replaceAllUsesWith(LastInst);
5230 RecursivelyDeleteTriviallyDeadInstructions(&I);
5231 return true;
5232}
5233
Chris Lattnerf2836d12007-03-31 04:06:36 +00005234// In this pass we look for GEP and cast instructions that are used
5235// across basic blocks and rewrite them to improve basic-block-at-a-time
5236// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005237bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005238 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005239 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005240
Chris Lattner7a277142011-01-15 07:14:54 +00005241 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005242 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005243 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005244 if (ModifiedDT)
5245 return true;
5246 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005247
James Molloyf01488e2016-01-15 09:20:19 +00005248 bool MadeBitReverse = true;
5249 while (TLI && MadeBitReverse) {
5250 MadeBitReverse = false;
5251 for (auto &I : reverse(BB)) {
5252 if (makeBitReverse(I, *DL, *TLI)) {
5253 MadeBitReverse = MadeChange = true;
5254 break;
5255 }
5256 }
5257 }
James Molloy3ef84c42016-01-15 10:36:01 +00005258 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005259
Chris Lattnerf2836d12007-03-31 04:06:36 +00005260 return MadeChange;
5261}
Devang Patel53771ba2011-08-18 00:50:51 +00005262
5263// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005264// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005265// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005266bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005267 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005268 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005269 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005270 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005271 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005272 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005273 // Leave dbg.values that refer to an alloca alone. These
5274 // instrinsics describe the address of a variable (= the alloca)
5275 // being taken. They should not be moved next to the alloca
5276 // (and to the beginning of the scope), but rather stay close to
5277 // where said address is used.
5278 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005279 PrevNonDbgInst = Insn;
5280 continue;
5281 }
5282
5283 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5284 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005285 // If VI is a phi in a block with an EHPad terminator, we can't insert
5286 // after it.
5287 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5288 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005289 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5290 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005291 if (isa<PHINode>(VI))
5292 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5293 else
5294 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005295 MadeChange = true;
5296 ++NumDbgValueMoved;
5297 }
5298 }
5299 }
5300 return MadeChange;
5301}
Tim Northovercea0abb2014-03-29 08:22:29 +00005302
5303// If there is a sequence that branches based on comparing a single bit
5304// against zero that can be combined into a single instruction, and the
5305// target supports folding these into a single instruction, sink the
5306// mask and compare into the branch uses. Do this before OptimizeBlock ->
5307// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5308// searched for.
5309bool CodeGenPrepare::sinkAndCmp(Function &F) {
5310 if (!EnableAndCmpSinking)
5311 return false;
5312 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5313 return false;
5314 bool MadeChange = false;
5315 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005316 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00005317
5318 // Does this BB end with the following?
5319 // %andVal = and %val, #single-bit-set
5320 // %icmpVal = icmp %andResult, 0
5321 // br i1 %cmpVal label %dest1, label %dest2"
5322 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
5323 if (!Brcc || !Brcc->isConditional())
5324 continue;
5325 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
5326 if (!Cmp || Cmp->getParent() != BB)
5327 continue;
5328 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5329 if (!Zero || !Zero->isZero())
5330 continue;
5331 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
5332 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
5333 continue;
5334 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5335 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5336 continue;
5337 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
5338
5339 // Push the "and; icmp" for any users that are conditional branches.
5340 // Since there can only be one branch use per BB, we don't need to keep
5341 // track of which BBs we insert into.
5342 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
5343 UI != E; ) {
5344 Use &TheUse = *UI;
5345 // Find brcc use.
5346 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
5347 ++UI;
5348 if (!BrccUser || !BrccUser->isConditional())
5349 continue;
5350 BasicBlock *UserBB = BrccUser->getParent();
5351 if (UserBB == BB) continue;
5352 DEBUG(dbgs() << "found Brcc use\n");
5353
5354 // Sink the "and; icmp" to use.
5355 MadeChange = true;
5356 BinaryOperator *NewAnd =
5357 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5358 BrccUser);
5359 CmpInst *NewCmp =
5360 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5361 "", BrccUser);
5362 TheUse = NewCmp;
5363 ++NumAndCmpsMoved;
5364 DEBUG(BrccUser->getParent()->dump());
5365 }
5366 }
5367 return MadeChange;
5368}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005369
Juergen Ributzka194350a2014-12-09 17:32:12 +00005370/// \brief Retrieve the probabilities of a conditional branch. Returns true on
5371/// success, or returns false if no or invalid metadata was found.
5372static bool extractBranchMetadata(BranchInst *BI,
5373 uint64_t &ProbTrue, uint64_t &ProbFalse) {
5374 assert(BI->isConditional() &&
5375 "Looking for probabilities on unconditional branch?");
5376 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
5377 if (!ProfileData || ProfileData->getNumOperands() != 3)
5378 return false;
5379
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005380 const auto *CITrue =
5381 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
5382 const auto *CIFalse =
5383 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00005384 if (!CITrue || !CIFalse)
5385 return false;
5386
5387 ProbTrue = CITrue->getValue().getZExtValue();
5388 ProbFalse = CIFalse->getValue().getZExtValue();
5389
5390 return true;
5391}
5392
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005393/// \brief Scale down both weights to fit into uint32_t.
5394static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5395 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5396 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5397 NewTrue = NewTrue / Scale;
5398 NewFalse = NewFalse / Scale;
5399}
5400
5401/// \brief Some targets prefer to split a conditional branch like:
5402/// \code
5403/// %0 = icmp ne i32 %a, 0
5404/// %1 = icmp ne i32 %b, 0
5405/// %or.cond = or i1 %0, %1
5406/// br i1 %or.cond, label %TrueBB, label %FalseBB
5407/// \endcode
5408/// into multiple branch instructions like:
5409/// \code
5410/// bb1:
5411/// %0 = icmp ne i32 %a, 0
5412/// br i1 %0, label %TrueBB, label %bb2
5413/// bb2:
5414/// %1 = icmp ne i32 %b, 0
5415/// br i1 %1, label %TrueBB, label %FalseBB
5416/// \endcode
5417/// This usually allows instruction selection to do even further optimizations
5418/// and combine the compare with the branch instruction. Currently this is
5419/// applied for targets which have "cheap" jump instructions.
5420///
5421/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5422///
5423bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005424 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005425 return false;
5426
5427 bool MadeChange = false;
5428 for (auto &BB : F) {
5429 // Does this BB end with the following?
5430 // %cond1 = icmp|fcmp|binary instruction ...
5431 // %cond2 = icmp|fcmp|binary instruction ...
5432 // %cond.or = or|and i1 %cond1, cond2
5433 // br i1 %cond.or label %dest1, label %dest2"
5434 BinaryOperator *LogicOp;
5435 BasicBlock *TBB, *FBB;
5436 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5437 continue;
5438
Sanjay Patel42574202015-09-02 19:23:23 +00005439 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5440 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5441 continue;
5442
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005443 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005444 Value *Cond1, *Cond2;
5445 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5446 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005447 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005448 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5449 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005450 Opc = Instruction::Or;
5451 else
5452 continue;
5453
5454 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5455 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5456 continue;
5457
5458 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5459
5460 // Create a new BB.
5461 auto *InsertBefore = std::next(Function::iterator(BB))
5462 .getNodePtrUnchecked();
5463 auto TmpBB = BasicBlock::Create(BB.getContext(),
5464 BB.getName() + ".cond.split",
5465 BB.getParent(), InsertBefore);
5466
5467 // Update original basic block by using the first condition directly by the
5468 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005469 Br1->setCondition(Cond1);
5470 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005471
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005472 // Depending on the conditon we have to either replace the true or the false
5473 // successor of the original branch instruction.
5474 if (Opc == Instruction::And)
5475 Br1->setSuccessor(0, TmpBB);
5476 else
5477 Br1->setSuccessor(1, TmpBB);
5478
5479 // Fill in the new basic block.
5480 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005481 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5482 I->removeFromParent();
5483 I->insertBefore(Br2);
5484 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005485
5486 // Update PHI nodes in both successors. The original BB needs to be
5487 // replaced in one succesor's PHI nodes, because the branch comes now from
5488 // the newly generated BB (NewBB). In the other successor we need to add one
5489 // incoming edge to the PHI nodes, because both branch instructions target
5490 // now the same successor. Depending on the original branch condition
5491 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5492 // we perfrom the correct update for the PHI nodes.
5493 // This doesn't change the successor order of the just created branch
5494 // instruction (or any other instruction).
5495 if (Opc == Instruction::Or)
5496 std::swap(TBB, FBB);
5497
5498 // Replace the old BB with the new BB.
5499 for (auto &I : *TBB) {
5500 PHINode *PN = dyn_cast<PHINode>(&I);
5501 if (!PN)
5502 break;
5503 int i;
5504 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5505 PN->setIncomingBlock(i, TmpBB);
5506 }
5507
5508 // Add another incoming edge form the new BB.
5509 for (auto &I : *FBB) {
5510 PHINode *PN = dyn_cast<PHINode>(&I);
5511 if (!PN)
5512 break;
5513 auto *Val = PN->getIncomingValueForBlock(&BB);
5514 PN->addIncoming(Val, TmpBB);
5515 }
5516
5517 // Update the branch weights (from SelectionDAGBuilder::
5518 // FindMergedConditions).
5519 if (Opc == Instruction::Or) {
5520 // Codegen X | Y as:
5521 // BB1:
5522 // jmp_if_X TBB
5523 // jmp TmpBB
5524 // TmpBB:
5525 // jmp_if_Y TBB
5526 // jmp FBB
5527 //
5528
5529 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5530 // The requirement is that
5531 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5532 // = TrueProb for orignal BB.
5533 // Assuming the orignal weights are A and B, one choice is to set BB1's
5534 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5535 // assumes that
5536 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5537 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5538 // TmpBB, but the math is more complicated.
5539 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005540 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005541 uint64_t NewTrueWeight = TrueWeight;
5542 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5543 scaleWeights(NewTrueWeight, NewFalseWeight);
5544 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5545 .createBranchWeights(TrueWeight, FalseWeight));
5546
5547 NewTrueWeight = TrueWeight;
5548 NewFalseWeight = 2 * FalseWeight;
5549 scaleWeights(NewTrueWeight, NewFalseWeight);
5550 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5551 .createBranchWeights(TrueWeight, FalseWeight));
5552 }
5553 } else {
5554 // Codegen X & Y as:
5555 // BB1:
5556 // jmp_if_X TmpBB
5557 // jmp FBB
5558 // TmpBB:
5559 // jmp_if_Y TBB
5560 // jmp FBB
5561 //
5562 // This requires creation of TmpBB after CurBB.
5563
5564 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5565 // The requirement is that
5566 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5567 // = FalseProb for orignal BB.
5568 // Assuming the orignal weights are A and B, one choice is to set BB1's
5569 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5570 // assumes that
5571 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5572 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005573 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005574 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5575 uint64_t NewFalseWeight = FalseWeight;
5576 scaleWeights(NewTrueWeight, NewFalseWeight);
5577 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5578 .createBranchWeights(TrueWeight, FalseWeight));
5579
5580 NewTrueWeight = 2 * TrueWeight;
5581 NewFalseWeight = FalseWeight;
5582 scaleWeights(NewTrueWeight, NewFalseWeight);
5583 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5584 .createBranchWeights(TrueWeight, FalseWeight));
5585 }
5586 }
5587
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005588 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005589 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005590 ModifiedDT = true;
5591
5592 MadeChange = true;
5593
5594 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5595 TmpBB->dump());
5596 }
5597 return MadeChange;
5598}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005599
5600void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005601 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005602 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5603}