blob: 4fd1c4bda433ac1996fbc34ce957859b010ed45c [file] [log] [blame]
Bill Wendlingca678352010-08-09 23:59:04 +00001//===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Perform peephole optimizations on the machine code:
11//
12// - Optimize Extensions
13//
14// Optimization of sign / zero extension instructions. It may be extended to
15// handle other instructions with similar properties.
16//
17// On some targets, some instructions, e.g. X86 sign / zero extension, may
18// leave the source value in the lower part of the result. This optimization
19// will replace some uses of the pre-extension value with uses of the
20// sub-register of the results.
21//
22// - Optimize Comparisons
23//
24// Optimization of comparison instructions. For instance, in this code:
25//
26// sub r1, 1
27// cmp r1, 0
28// bz L1
29//
30// If the "sub" instruction all ready sets (or could be modified to set) the
31// same flag that the "cmp" instruction sets and that "bz" uses, then we can
32// eliminate the "cmp" instruction.
Evan Chenge4b8ac92011-03-15 05:13:13 +000033//
Manman Rendc8ad002012-05-11 01:30:47 +000034// Another instance, in this code:
35//
36// sub r1, r3 | sub r1, imm
37// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38// bge L1
39//
40// If the branch instruction can use flag from "sub", then we can replace
41// "sub" with "subs" and eliminate the "cmp" instruction.
42//
Joel Jones24e440d2012-12-11 16:10:25 +000043// - Optimize Loads:
44//
45// Loads that can be folded into a later instruction. A load is foldable
Matt Arsenault30991562015-09-09 00:38:33 +000046// if it loads to virtual registers and the virtual register defined has
Joel Jones24e440d2012-12-11 16:10:25 +000047// a single use.
Quentin Colombetcf71c632013-09-13 18:26:31 +000048//
Quentin Colombet03e43f82014-08-20 17:41:48 +000049// - Optimize Copies and Bitcast (more generally, target specific copies):
Quentin Colombetcf71c632013-09-13 18:26:31 +000050//
51// Rewrite copies and bitcasts to avoid cross register bank copies
52// when possible.
53// E.g., Consider the following example, where capital and lower
54// letters denote different register file:
55// b = copy A <-- cross-bank copy
56// C = copy b <-- cross-bank copy
57// =>
58// b = copy A <-- cross-bank copy
59// C = copy A <-- same-bank copy
60//
61// E.g., for bitcast:
62// b = bitcast A <-- cross-bank copy
63// C = bitcast b <-- cross-bank copy
64// =>
65// b = bitcast A <-- cross-bank copy
66// C = copy A <-- same-bank copy
Bill Wendlingca678352010-08-09 23:59:04 +000067//===----------------------------------------------------------------------===//
68
Bill Wendlingca678352010-08-09 23:59:04 +000069#include "llvm/CodeGen/Passes.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000070#include "llvm/ADT/DenseMap.h"
Bill Wendlingca678352010-08-09 23:59:04 +000071#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000072#include "llvm/ADT/SmallSet.h"
Bill Wendlingca678352010-08-09 23:59:04 +000073#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000074#include "llvm/CodeGen/MachineDominators.h"
75#include "llvm/CodeGen/MachineInstrBuilder.h"
76#include "llvm/CodeGen/MachineRegisterInfo.h"
77#include "llvm/Support/CommandLine.h"
Craig Topper588ceec2012-12-17 03:56:00 +000078#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000079#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000080#include "llvm/Target/TargetInstrInfo.h"
81#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000082#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet03e43f82014-08-20 17:41:48 +000083#include <utility>
Bill Wendlingca678352010-08-09 23:59:04 +000084using namespace llvm;
85
Chandler Carruth1b9dde02014-04-22 02:02:50 +000086#define DEBUG_TYPE "peephole-opt"
87
Bill Wendlingca678352010-08-09 23:59:04 +000088// Optimize Extensions
89static cl::opt<bool>
90Aggressive("aggressive-ext-opt", cl::Hidden,
91 cl::desc("Aggressive extension optimization"));
92
Bill Wendlingc6627ee2010-11-01 20:41:43 +000093static cl::opt<bool>
94DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
95 cl::desc("Disable the peephole optimizer"));
96
Quentin Colombet1111e6f2014-07-01 14:33:36 +000097static cl::opt<bool>
Quentin Colombet6674b092014-08-21 22:23:52 +000098DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
Quentin Colombet1111e6f2014-07-01 14:33:36 +000099 cl::desc("Disable advanced copy optimization"));
100
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000101// Limit the number of PHI instructions to process
102// in PeepholeOptimizer::getNextSource.
103static cl::opt<unsigned> RewritePHILimit(
104 "rewrite-phi-limit", cl::Hidden, cl::init(10),
105 cl::desc("Limit the length of PHI chains to lookup"));
106
Bill Wendling66284312010-08-27 20:39:09 +0000107STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000108STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000109STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000110STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000111STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000112STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
113STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
Bill Wendlingca678352010-08-09 23:59:04 +0000114
115namespace {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000116 class ValueTrackerResult;
117
Bill Wendlingca678352010-08-09 23:59:04 +0000118 class PeepholeOptimizer : public MachineFunctionPass {
Bill Wendlingca678352010-08-09 23:59:04 +0000119 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000120 const TargetRegisterInfo *TRI;
Bill Wendlingca678352010-08-09 23:59:04 +0000121 MachineRegisterInfo *MRI;
122 MachineDominatorTree *DT; // Machine dominator tree
123
124 public:
125 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000126 PeepholeOptimizer() : MachineFunctionPass(ID) {
127 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
128 }
Bill Wendlingca678352010-08-09 23:59:04 +0000129
Craig Topper4584cd52014-03-07 09:26:03 +0000130 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000131
Craig Topper4584cd52014-03-07 09:26:03 +0000132 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000133 AU.setPreservesCFG();
134 MachineFunctionPass::getAnalysisUsage(AU);
135 if (Aggressive) {
136 AU.addRequired<MachineDominatorTree>();
137 AU.addPreserved<MachineDominatorTree>();
138 }
139 }
140
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000141 /// \brief Track Def -> Use info used for rewriting copies.
142 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
143 RewriteMapTy;
144
Bill Wendlingca678352010-08-09 23:59:04 +0000145 private:
Jim Grosbachedcb8682012-05-01 23:21:41 +0000146 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
147 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000148 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Mehdi Amini22e59742015-01-13 07:07:13 +0000149 bool optimizeSelect(MachineInstr *MI,
150 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000151 bool optimizeCondBranch(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000152 bool optimizeCoalescableCopy(MachineInstr *MI);
153 bool optimizeUncoalescableCopy(MachineInstr *MI,
154 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000155 bool findNextSource(unsigned Reg, unsigned SubReg,
156 RewriteMapTy &RewriteMap);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000157 bool isMoveImmediate(MachineInstr *MI,
158 SmallSet<unsigned, 4> &ImmDefRegs,
159 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000160 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000161 SmallSet<unsigned, 4> &ImmDefRegs,
162 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000163
164 /// \brief If copy instruction \p MI is a virtual register copy, track it in
165 /// the set \p CopiedFromRegs and \p CopyMIs. If this virtual register was
166 /// previously seen as a copy, replace the uses of this copy with the
167 /// previously seen copy's destination register.
168 bool foldRedundantCopy(MachineInstr *MI,
169 SmallSet<unsigned, 4> &CopiedFromRegs,
170 DenseMap<unsigned, MachineInstr*> &CopyMIs);
171
Lang Hames5dc14bd2014-04-02 22:59:58 +0000172 bool isLoadFoldable(MachineInstr *MI,
173 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000174
175 /// \brief Check whether \p MI is understood by the register coalescer
176 /// but may require some rewriting.
177 bool isCoalescableCopy(const MachineInstr &MI) {
178 // SubregToRegs are not interesting, because they are already register
179 // coalescer friendly.
180 return MI.isCopy() || (!DisableAdvCopyOpt &&
181 (MI.isRegSequence() || MI.isInsertSubreg() ||
182 MI.isExtractSubreg()));
183 }
184
185 /// \brief Check whether \p MI is a copy like instruction that is
186 /// not recognized by the register coalescer.
187 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000188 return MI.isBitcast() ||
189 (!DisableAdvCopyOpt &&
190 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
191 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000192 }
Bill Wendlingca678352010-08-09 23:59:04 +0000193 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000194
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000195 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
196 /// returned sources for a given search and the instructions where the sources
197 /// were tracked from.
198 class ValueTrackerResult {
199 private:
200 /// Track all sources found by one ValueTracker query.
201 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
202
203 /// Instruction using the sources in 'RegSrcs'.
204 const MachineInstr *Inst;
205
206 public:
207 ValueTrackerResult() : Inst(nullptr) {}
208 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
209 addSource(Reg, SubReg);
210 }
211
212 bool isValid() const { return getNumSources() > 0; }
213
214 void setInst(const MachineInstr *I) { Inst = I; }
215 const MachineInstr *getInst() const { return Inst; }
216
217 void clear() {
218 RegSrcs.clear();
219 Inst = nullptr;
220 }
221
222 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
223 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
224 }
225
226 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
227 assert(Idx < getNumSources() && "Reg pair source out of index");
228 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
229 }
230
231 int getNumSources() const { return RegSrcs.size(); }
232
233 unsigned getSrcReg(int Idx) const {
234 assert(Idx < getNumSources() && "Reg source out of index");
235 return RegSrcs[Idx].Reg;
236 }
237
238 unsigned getSrcSubReg(int Idx) const {
239 assert(Idx < getNumSources() && "SubReg source out of index");
240 return RegSrcs[Idx].SubReg;
241 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000242
243 bool operator==(const ValueTrackerResult &Other) {
244 if (Other.getInst() != getInst())
245 return false;
246
247 if (Other.getNumSources() != getNumSources())
248 return false;
249
250 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
251 if (Other.getSrcReg(i) != getSrcReg(i) ||
252 Other.getSrcSubReg(i) != getSrcSubReg(i))
253 return false;
254 return true;
255 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000256 };
257
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000258 /// \brief Helper class to track the possible sources of a value defined by
259 /// a (chain of) copy related instructions.
260 /// Given a definition (instruction and definition index), this class
261 /// follows the use-def chain to find successive suitable sources.
262 /// The given source can be used to rewrite the definition into
263 /// def = COPY src.
264 ///
265 /// For instance, let us consider the following snippet:
266 /// v0 =
267 /// v2 = INSERT_SUBREG v1, v0, sub0
268 /// def = COPY v2.sub0
269 ///
270 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
271 /// suitable sources:
272 /// v2.sub0 and v0.
273 /// Then, def can be rewritten into def = COPY v0.
274 class ValueTracker {
275 private:
276 /// The current point into the use-def chain.
277 const MachineInstr *Def;
278 /// The index of the definition in Def.
279 unsigned DefIdx;
280 /// The sub register index of the definition.
281 unsigned DefSubReg;
282 /// The register where the value can be found.
283 unsigned Reg;
284 /// Specifiy whether or not the value tracking looks through
285 /// complex instructions. When this is false, the value tracker
286 /// bails on everything that is not a copy or a bitcast.
287 ///
288 /// Note: This could have been implemented as a specialized version of
289 /// the ValueTracker class but that would have complicated the code of
290 /// the users of this class.
291 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000292 /// MachineRegisterInfo used to perform tracking.
293 const MachineRegisterInfo &MRI;
294 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000295 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000296 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000297
298 /// \brief Dispatcher to the right underlying implementation of
299 /// getNextSource.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000300 ValueTrackerResult getNextSourceImpl();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000301 /// \brief Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000302 ValueTrackerResult getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000303 /// \brief Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000304 ValueTrackerResult getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000305 /// \brief Specialized version of getNextSource for RegSequence
306 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000307 ValueTrackerResult getNextSourceFromRegSequence();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000308 /// \brief Specialized version of getNextSource for InsertSubreg
309 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000310 ValueTrackerResult getNextSourceFromInsertSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000311 /// \brief Specialized version of getNextSource for ExtractSubreg
312 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000313 ValueTrackerResult getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000314 /// \brief Specialized version of getNextSource for SubregToReg
315 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000316 ValueTrackerResult getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000317 /// \brief Specialized version of getNextSource for PHI instructions.
318 ValueTrackerResult getNextSourceFromPHI();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000319
320 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000321 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000322 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000323 /// track. It does not need to match the sub register index used in the
324 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000325 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
326 /// through complex instructions. By default (false), it handles only copy
327 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000328 /// If \p Reg is a physical register, a value tracker constructed with
329 /// this constructor will not find any alternative source.
330 /// Indeed, when \p Reg is a physical register that constructor does not
331 /// know which definition of \p Reg it should track.
332 /// Use the next constructor to track a physical register.
333 ValueTracker(unsigned Reg, unsigned DefSubReg,
334 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000335 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000336 const TargetInstrInfo *TII = nullptr)
337 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
338 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
339 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
340 Def = MRI.getVRegDef(Reg);
341 DefIdx = MRI.def_begin(Reg).getOperandNo();
342 }
343 }
344
345 /// \brief Create a ValueTracker instance for the value defined by
346 /// the pair \p MI, \p DefIdx.
347 /// Unlike the other constructor, the value tracker produced by this one
348 /// may be able to find a new source when the definition is a physical
349 /// register.
350 /// This could be useful to rewrite target specific instructions into
351 /// generic copy instructions.
352 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
353 const MachineRegisterInfo &MRI,
354 bool UseAdvancedTracking = false,
355 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000356 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000357 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
358 assert(DefIdx < Def->getDesc().getNumDefs() &&
359 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000360 Reg = Def->getOperand(DefIdx).getReg();
361 }
362
363 /// \brief Following the use-def chain, get the next available source
364 /// for the tracked value.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000365 /// \return A ValueTrackerResult containing a set of registers
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000366 /// and sub registers with tracked values. A ValueTrackerResult with
367 /// an empty set of registers means no source was found.
368 ValueTrackerResult getNextSource();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000369
370 /// \brief Get the last register where the initial value can be found.
371 /// Initially this is the register of the definition.
372 /// Then, after each successful call to getNextSource, this is the
373 /// register of the last source.
374 unsigned getReg() const { return Reg; }
375 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000376}
Bill Wendlingca678352010-08-09 23:59:04 +0000377
378char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000379char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000380INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
381 "Peephole Optimizations", false, false)
382INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
383INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000384 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000385
Jim Grosbachedcb8682012-05-01 23:21:41 +0000386/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendlingca678352010-08-09 23:59:04 +0000387/// a single register and writes a single register and it does not modify the
388/// source, and if the source value is preserved as a sub-register of the
389/// result, then replace all reachable uses of the source with the subreg of the
390/// result.
Andrew Trick9e761992012-02-08 21:22:43 +0000391///
Bill Wendlingca678352010-08-09 23:59:04 +0000392/// Do not generate an EXTRACT that is used only in a debug use, as this changes
393/// the code. Since this code does not currently share EXTRACTs, just ignore all
394/// debug uses.
395bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000396optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000397 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000398 unsigned SrcReg, DstReg, SubIdx;
399 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
400 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000401
Bill Wendlingca678352010-08-09 23:59:04 +0000402 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
403 TargetRegisterInfo::isPhysicalRegister(SrcReg))
404 return false;
405
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000406 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000407 // No other uses.
408 return false;
409
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000410 // Ensure DstReg can get a register class that actually supports
411 // sub-registers. Don't change the class until we commit.
412 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000413 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000414 if (!DstRC)
415 return false;
416
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000417 // The ext instr may be operating on a sub-register of SrcReg as well.
418 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
419 // register.
420 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
421 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000422 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000423 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000424
Bill Wendlingca678352010-08-09 23:59:04 +0000425 // The source has other uses. See if we can replace the other uses with use of
426 // the result of the extension.
427 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000428 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
429 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000430
431 // Uses that are in the same BB of uses of the result of the instruction.
432 SmallVector<MachineOperand*, 8> Uses;
433
434 // Uses that the result of the instruction can reach.
435 SmallVector<MachineOperand*, 8> ExtendedUses;
436
437 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000438 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000439 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000440 if (UseMI == MI)
441 continue;
442
443 if (UseMI->isPHI()) {
444 ExtendLife = false;
445 continue;
446 }
447
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000448 // Only accept uses of SrcReg:SubIdx.
449 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
450 continue;
451
Bill Wendlingca678352010-08-09 23:59:04 +0000452 // It's an error to translate this:
453 //
454 // %reg1025 = <sext> %reg1024
455 // ...
456 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
457 //
458 // into this:
459 //
460 // %reg1025 = <sext> %reg1024
461 // ...
462 // %reg1027 = COPY %reg1025:4
463 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
464 //
465 // The problem here is that SUBREG_TO_REG is there to assert that an
466 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
467 // the COPY here, it will give us the value after the <sext>, not the
468 // original value of %reg1024 before <sext>.
469 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
470 continue;
471
472 MachineBasicBlock *UseMBB = UseMI->getParent();
473 if (UseMBB == MBB) {
474 // Local uses that come after the extension.
475 if (!LocalMIs.count(UseMI))
476 Uses.push_back(&UseMO);
477 } else if (ReachedBBs.count(UseMBB)) {
478 // Non-local uses where the result of the extension is used. Always
479 // replace these unless it's a PHI.
480 Uses.push_back(&UseMO);
481 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
482 // We may want to extend the live range of the extension result in order
483 // to replace these uses.
484 ExtendedUses.push_back(&UseMO);
485 } else {
486 // Both will be live out of the def MBB anyway. Don't extend live range of
487 // the extension result.
488 ExtendLife = false;
489 break;
490 }
491 }
492
493 if (ExtendLife && !ExtendedUses.empty())
494 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000495 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000496
497 // Now replace all uses.
498 bool Changed = false;
499 if (!Uses.empty()) {
500 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
501
502 // Look for PHI uses of the extended result, we don't want to extend the
503 // liveness of a PHI input. It breaks all kinds of assumptions down
504 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000505 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
506 if (UI.isPHI())
507 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000508
509 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
510 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
511 MachineOperand *UseMO = Uses[i];
512 MachineInstr *UseMI = UseMO->getParent();
513 MachineBasicBlock *UseMBB = UseMI->getParent();
514 if (PHIBBs.count(UseMBB))
515 continue;
516
Lang Hamesd5862ce2012-02-25 02:01:00 +0000517 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000518 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000519 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000520 MRI->constrainRegClass(DstReg, DstRC);
521 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000522
Bill Wendlingca678352010-08-09 23:59:04 +0000523 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000524 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
525 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000526 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000527 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
528 if (UseSrcSubIdx) {
529 Copy->getOperand(0).setSubReg(SubIdx);
530 Copy->getOperand(0).setIsUndef();
531 }
Bill Wendlingca678352010-08-09 23:59:04 +0000532 UseMO->setReg(NewVR);
533 ++NumReuse;
534 Changed = true;
535 }
536 }
537
538 return Changed;
539}
540
Jim Grosbachedcb8682012-05-01 23:21:41 +0000541/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendlingca678352010-08-09 23:59:04 +0000542/// instruction it's comparing against all ready sets (or could be modified to
543/// set) the same flag as the compare, then we can remove the comparison and use
544/// the flag from the previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000545bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000546 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000547 // If this instruction is a comparison against zero and isn't comparing a
548 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000549 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000550 int CmpMask, CmpValue;
Manman Ren6fa76dc2012-06-29 21:33:59 +0000551 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
552 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
553 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000554 return false;
555
Bill Wendling27dddd12010-09-11 00:13:50 +0000556 // Attempt to optimize the comparison instruction.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000557 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000558 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000559 return true;
560 }
561
562 return false;
563}
564
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000565/// Optimize a select instruction.
Mehdi Amini22e59742015-01-13 07:07:13 +0000566bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
567 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000568 unsigned TrueOp = 0;
569 unsigned FalseOp = 0;
570 bool Optimizable = false;
571 SmallVector<MachineOperand, 4> Cond;
572 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
573 return false;
574 if (!Optimizable)
575 return false;
Mehdi Amini22e59742015-01-13 07:07:13 +0000576 if (!TII->optimizeSelect(MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000577 return false;
578 MI->eraseFromParent();
579 ++NumSelects;
580 return true;
581}
582
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000583/// \brief Check if a simpler conditional branch can be
584// generated
585bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
586 return TII->optimizeCondBranch(MI);
587}
588
Quentin Colombet03e43f82014-08-20 17:41:48 +0000589/// \brief Try to find the next source that share the same register file
590/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000591/// When true is returned, the \p RewriteMap can be used by the client to
592/// retrieve all Def -> Use along the way up to the next source. Any found
593/// Use that is not itself a key for another entry, is the next source to
594/// use. During the search for the next source, multiple sources can be found
595/// given multiple incoming sources of a PHI instruction. In this case, we
596/// look in each PHI source for the next source; all found next sources must
597/// share the same register file as \p Reg and \p SubReg. The client should
598/// then be capable to rewrite all intermediate PHIs to get the next source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000599/// \return False if no alternative sources are available. True otherwise.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000600bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
601 RewriteMapTy &RewriteMap) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000602 // Do not try to find a new source for a physical register.
603 // So far we do not have any motivating example for doing that.
604 // Thus, instead of maintaining untested code, we will revisit that if
605 // that changes at some point.
606 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000607 return false;
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000608 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000609
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000610 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
611 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
612 SrcToLook.push_back(CurSrcPair);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000613
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000614 unsigned PHICount = 0;
615 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
616 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
617 // As explained above, do not handle physical registers
618 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
619 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000620
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000621 CurSrcPair = Pair;
622 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
623 !DisableAdvCopyOpt, TII);
624 ValueTrackerResult Res;
625 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000626
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000627 do {
628 // Follow the chain of copies until we reach the top of the use-def chain
629 // or find a more suitable source.
630 Res = ValTracker.getNextSource();
631 if (!Res.isValid())
632 break;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000633
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000634 // Insert the Def -> Use entry for the recently found source.
635 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
636 if (CurSrcRes.isValid()) {
637 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
638 // An existent entry with multiple sources is a PHI cycle we must avoid.
639 // Otherwise it's an entry with a valid next source we already found.
640 if (CurSrcRes.getNumSources() > 1) {
641 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
642 return false;
643 }
644 break;
645 }
646 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
647
648 // ValueTrackerResult usually have one source unless it's the result from
649 // a PHI instruction. Add the found PHI edges to be looked up further.
650 unsigned NumSrcs = Res.getNumSources();
651 if (NumSrcs > 1) {
652 PHICount++;
653 for (unsigned i = 0; i < NumSrcs; ++i)
654 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
655 Res.getSrcReg(i), Res.getSrcSubReg(i)));
656 break;
657 }
658
659 CurSrcPair.Reg = Res.getSrcReg(0);
660 CurSrcPair.SubReg = Res.getSrcSubReg(0);
661 // Do not extend the live-ranges of physical registers as they add
662 // constraints to the register allocator. Moreover, if we want to extend
663 // the live-range of a physical register, unlike SSA virtual register,
664 // we will have to check that they aren't redefine before the related use.
665 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
666 return false;
667
668 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
Matt Arsenault68d93862015-09-24 08:36:14 +0000669 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
670 CurSrcPair.SubReg);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000671 } while (!ShouldRewrite);
672
673 // Continue looking for new sources...
674 if (Res.isValid())
675 continue;
676
677 // Do not continue searching for a new source if the there's at least
678 // one use-def which cannot be rewritten.
679 if (!ShouldRewrite)
680 return false;
681 }
682
683 if (PHICount >= RewritePHILimit) {
684 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
685 return false;
686 }
Quentin Colombetcf71c632013-09-13 18:26:31 +0000687
688 // If we did not find a more suitable source, there is nothing to optimize.
Rafael Espindola84921b92015-10-24 23:11:13 +0000689 return CurSrcPair.Reg != Reg;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000690}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000691
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000692/// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
693/// guaranteed to have the same register class. This is necessary whenever we
694/// successfully traverse a PHI instruction and find suitable sources coming
695/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
696/// suitable to be used in a new COPY instruction.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000697static MachineInstr *
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000698insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
699 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
700 MachineInstr *OrigPHI) {
701 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
702
703 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
704 unsigned NewVR = MRI->createVirtualRegister(NewRC);
705 MachineBasicBlock *MBB = OrigPHI->getParent();
706 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
707 TII->get(TargetOpcode::PHI), NewVR);
708
709 unsigned MBBOpIdx = 2;
710 for (auto RegPair : SrcRegs) {
711 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
712 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
713 // Since we're extended the lifetime of RegPair.Reg, clear the
714 // kill flags to account for that and make RegPair.Reg reaches
715 // the new PHI.
716 MRI->clearKillFlags(RegPair.Reg);
717 MBBOpIdx += 2;
718 }
719
720 return MIB;
721}
722
Quentin Colombet03e43f82014-08-20 17:41:48 +0000723namespace {
724/// \brief Helper class to rewrite the arguments of a copy-like instruction.
725class CopyRewriter {
726protected:
727 /// The copy-like instruction.
728 MachineInstr &CopyLike;
729 /// The index of the source being rewritten.
730 unsigned CurrentSrcIdx;
731
732public:
733 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
734
735 virtual ~CopyRewriter() {}
736
737 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
738 /// the related value that it affects (TrackReg, TrackSubReg).
739 /// A source is considered rewritable if its register class and the
740 /// register class of the related TrackReg may not be register
741 /// coalescer friendly. In other words, given a copy-like instruction
742 /// not all the arguments may be returned at rewritable source, since
743 /// some arguments are none to be register coalescer friendly.
744 ///
745 /// Each call of this method moves the current source to the next
746 /// rewritable source.
747 /// For instance, let CopyLike be the instruction to rewrite.
748 /// CopyLike has one definition and one source:
749 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
750 ///
751 /// The first call will give the first rewritable source, i.e.,
752 /// the only source this instruction has:
753 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
754 /// This source defines the whole definition, i.e.,
755 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
756 ///
Matt Arsenault30991562015-09-09 00:38:33 +0000757 /// The second and subsequent calls will return false, as there is only one
Quentin Colombet03e43f82014-08-20 17:41:48 +0000758 /// rewritable source.
759 ///
760 /// \return True if a rewritable source has been found, false otherwise.
761 /// The output arguments are valid if and only if true is returned.
762 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
763 unsigned &TrackReg,
764 unsigned &TrackSubReg) {
Matt Arsenault30991562015-09-09 00:38:33 +0000765 // If CurrentSrcIdx == 1, this means this function has already been called
766 // once. CopyLike has one definition and one argument, thus, there is
767 // nothing else to rewrite.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000768 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
769 return false;
770 // This is the first call to getNextRewritableSource.
771 // Move the CurrentSrcIdx to remember that we made that call.
772 CurrentSrcIdx = 1;
773 // The rewritable source is the argument.
774 const MachineOperand &MOSrc = CopyLike.getOperand(1);
775 SrcReg = MOSrc.getReg();
776 SrcSubReg = MOSrc.getSubReg();
777 // What we track are the alternative sources of the definition.
778 const MachineOperand &MODef = CopyLike.getOperand(0);
779 TrackReg = MODef.getReg();
780 TrackSubReg = MODef.getSubReg();
781 return true;
782 }
783
784 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
785 /// if possible.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000786 /// \return True if the rewriting was possible, false otherwise.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000787 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
788 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
789 return false;
790 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
791 MOSrc.setReg(NewReg);
792 MOSrc.setSubReg(NewSubReg);
793 return true;
794 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000795
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000796 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
797 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
798 /// multiple sources for a given \p Def are found along the way, we found a
799 /// PHI instructions that needs to be rewritten.
800 /// TODO: HandleMultipleSources should be removed once we test PHI handling
801 /// with coalescable copies.
802 TargetInstrInfo::RegSubRegPair
803 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
804 TargetInstrInfo::RegSubRegPair Def,
805 PeepholeOptimizer::RewriteMapTy &RewriteMap,
806 bool HandleMultipleSources = true) {
807
808 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
809 do {
810 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
811 // If there are no entries on the map, LookupSrc is the new source.
812 if (!Res.isValid())
813 return LookupSrc;
814
815 // There's only one source for this definition, keep searching...
816 unsigned NumSrcs = Res.getNumSources();
817 if (NumSrcs == 1) {
818 LookupSrc.Reg = Res.getSrcReg(0);
819 LookupSrc.SubReg = Res.getSrcSubReg(0);
820 continue;
821 }
822
Matt Arsenault30991562015-09-09 00:38:33 +0000823 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000824 if (!HandleMultipleSources)
825 break;
826
827 // Multiple sources, recurse into each source to find a new source
828 // for it. Then, rewrite the PHI accordingly to its new edges.
829 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
830 for (unsigned i = 0; i < NumSrcs; ++i) {
831 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
832 Res.getSrcSubReg(i));
833 NewPHISrcs.push_back(
834 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
835 }
836
837 // Build the new PHI node and return its def register as the new source.
838 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
839 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
840 DEBUG(dbgs() << "-- getNewSource\n");
841 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
842 DEBUG(dbgs() << " With: " << *NewPHI);
843 const MachineOperand &MODef = NewPHI->getOperand(0);
844 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
845
846 } while (1);
847
848 return TargetInstrInfo::RegSubRegPair(0, 0);
849 }
850
851 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
852 /// and create a new COPY instruction. More info about RewriteMap in
853 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
854 /// Uncoalescable copies, since they are copy like instructions that aren't
855 /// recognized by the register allocator.
856 virtual MachineInstr *
857 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
858 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000859 return nullptr;
860 }
861};
862
863/// \brief Helper class to rewrite uncoalescable copy like instructions
864/// into new COPY (coalescable friendly) instructions.
865class UncoalescableRewriter : public CopyRewriter {
866protected:
867 const TargetInstrInfo &TII;
868 MachineRegisterInfo &MRI;
869 /// The number of defs in the bitcast
870 unsigned NumDefs;
871
872public:
873 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
874 MachineRegisterInfo &MRI)
875 : CopyRewriter(MI), TII(TII), MRI(MRI) {
876 NumDefs = MI.getDesc().getNumDefs();
877 }
878
879 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
880 /// All such sources need to be considered rewritable in order to
881 /// rewrite a uncoalescable copy-like instruction. This method return
882 /// each definition that must be checked if rewritable.
883 ///
884 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
885 unsigned &TrackReg,
886 unsigned &TrackSubReg) override {
887 // Find the next non-dead definition and continue from there.
888 if (CurrentSrcIdx == NumDefs)
889 return false;
890
891 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
892 ++CurrentSrcIdx;
893 if (CurrentSrcIdx == NumDefs)
894 return false;
895 }
896
897 // What we track are the alternative sources of the definition.
898 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
899 TrackReg = MODef.getReg();
900 TrackSubReg = MODef.getSubReg();
901
902 CurrentSrcIdx++;
903 return true;
904 }
905
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000906 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
907 /// and create a new COPY instruction. More info about RewriteMap in
908 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
909 /// Uncoalescable copies, since they are copy like instructions that aren't
910 /// recognized by the register allocator.
911 MachineInstr *
912 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
913 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
914 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000915 "We do not rewrite physical registers");
916
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000917 // Find the new source to use in the COPY rewrite.
918 TargetInstrInfo::RegSubRegPair NewSrc =
919 getNewSource(&MRI, &TII, Def, RewriteMap);
920
921 // Insert the COPY.
922 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000923 unsigned NewVR = MRI.createVirtualRegister(DefRC);
924
925 MachineInstr *NewCopy =
926 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
927 TII.get(TargetOpcode::COPY), NewVR)
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000928 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000929
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000930 NewCopy->getOperand(0).setSubReg(Def.SubReg);
931 if (Def.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000932 NewCopy->getOperand(0).setIsUndef();
933
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000934 DEBUG(dbgs() << "-- RewriteSource\n");
935 DEBUG(dbgs() << " Replacing: " << CopyLike);
936 DEBUG(dbgs() << " With: " << *NewCopy);
937 MRI.replaceRegWith(Def.Reg, NewVR);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000938 MRI.clearKillFlags(NewVR);
939
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000940 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
941 // account for that.
942 MRI.clearKillFlags(NewSrc.Reg);
943
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000944 return NewCopy;
945 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000946};
947
948/// \brief Specialized rewriter for INSERT_SUBREG instruction.
949class InsertSubregRewriter : public CopyRewriter {
950public:
951 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
952 assert(MI.isInsertSubreg() && "Invalid instruction");
953 }
954
955 /// \brief See CopyRewriter::getNextRewritableSource.
956 /// Here CopyLike has the following form:
957 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
958 /// Src1 has the same register class has dst, hence, there is
959 /// nothing to rewrite.
960 /// Src2.src2SubIdx, may not be register coalescer friendly.
961 /// Therefore, the first call to this method returns:
962 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
963 /// (TrackReg, TrackSubReg) = (dst, subIdx).
964 ///
965 /// Subsequence calls will return false.
966 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
967 unsigned &TrackReg,
968 unsigned &TrackSubReg) override {
969 // If we already get the only source we can rewrite, return false.
970 if (CurrentSrcIdx == 2)
971 return false;
972 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
973 CurrentSrcIdx = 2;
974 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
975 SrcReg = MOInsertedReg.getReg();
976 SrcSubReg = MOInsertedReg.getSubReg();
977 const MachineOperand &MODef = CopyLike.getOperand(0);
978
979 // We want to track something that is compatible with the
980 // partial definition.
981 TrackReg = MODef.getReg();
982 if (MODef.getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +0000983 // Bail if we have to compose sub-register indices.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000984 return false;
985 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
986 return true;
987 }
988 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
989 if (CurrentSrcIdx != 2)
990 return false;
991 // We are rewriting the inserted reg.
992 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
993 MO.setReg(NewReg);
994 MO.setSubReg(NewSubReg);
995 return true;
996 }
997};
998
999/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1000class ExtractSubregRewriter : public CopyRewriter {
1001 const TargetInstrInfo &TII;
1002
1003public:
1004 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1005 : CopyRewriter(MI), TII(TII) {
1006 assert(MI.isExtractSubreg() && "Invalid instruction");
1007 }
1008
1009 /// \brief See CopyRewriter::getNextRewritableSource.
1010 /// Here CopyLike has the following form:
1011 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1012 /// There is only one rewritable source: Src.subIdx,
1013 /// which defines dst.dstSubIdx.
1014 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1015 unsigned &TrackReg,
1016 unsigned &TrackSubReg) override {
1017 // If we already get the only source we can rewrite, return false.
1018 if (CurrentSrcIdx == 1)
1019 return false;
1020 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1021 CurrentSrcIdx = 1;
1022 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1023 SrcReg = MOExtractedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001024 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001025 if (MOExtractedReg.getSubReg())
1026 return false;
1027
1028 SrcSubReg = CopyLike.getOperand(2).getImm();
1029
1030 // We want to track something that is compatible with the definition.
1031 const MachineOperand &MODef = CopyLike.getOperand(0);
1032 TrackReg = MODef.getReg();
1033 TrackSubReg = MODef.getSubReg();
1034 return true;
1035 }
1036
1037 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1038 // The only source we can rewrite is the input register.
1039 if (CurrentSrcIdx != 1)
1040 return false;
1041
1042 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1043
1044 // If we find a source that does not require to extract something,
1045 // rewrite the operation with a copy.
1046 if (!NewSubReg) {
1047 // Move the current index to an invalid position.
1048 // We do not want another call to this method to be able
1049 // to do any change.
1050 CurrentSrcIdx = -1;
1051 // Rewrite the operation as a COPY.
1052 // Get rid of the sub-register index.
1053 CopyLike.RemoveOperand(2);
1054 // Morph the operation into a COPY.
1055 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1056 return true;
1057 }
1058 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1059 return true;
1060 }
1061};
1062
1063/// \brief Specialized rewriter for REG_SEQUENCE instruction.
1064class RegSequenceRewriter : public CopyRewriter {
1065public:
1066 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1067 assert(MI.isRegSequence() && "Invalid instruction");
1068 }
1069
1070 /// \brief See CopyRewriter::getNextRewritableSource.
1071 /// Here CopyLike has the following form:
1072 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1073 /// Each call will return a different source, walking all the available
1074 /// source.
1075 ///
1076 /// The first call returns:
1077 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1078 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1079 ///
1080 /// The second call returns:
1081 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1082 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1083 ///
1084 /// And so on, until all the sources have been traversed, then
1085 /// it returns false.
1086 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1087 unsigned &TrackReg,
1088 unsigned &TrackSubReg) override {
1089 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1090
1091 // If this is the first call, move to the first argument.
1092 if (CurrentSrcIdx == 0) {
1093 CurrentSrcIdx = 1;
1094 } else {
1095 // Otherwise, move to the next argument and check that it is valid.
1096 CurrentSrcIdx += 2;
1097 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1098 return false;
1099 }
1100 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1101 SrcReg = MOInsertedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001102 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001103 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1104 return false;
1105
1106 // We want to track something that is compatible with the related
1107 // partial definition.
1108 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1109
1110 const MachineOperand &MODef = CopyLike.getOperand(0);
1111 TrackReg = MODef.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001112 // If we have to compose sub-registers, bail.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001113 return MODef.getSubReg() == 0;
1114 }
1115
1116 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1117 // We cannot rewrite out of bound operands.
1118 // Moreover, rewritable sources are at odd positions.
1119 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1120 return false;
1121
1122 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1123 MO.setReg(NewReg);
1124 MO.setSubReg(NewSubReg);
1125 return true;
1126 }
1127};
1128} // End namespace.
1129
1130/// \brief Get the appropriated CopyRewriter for \p MI.
1131/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1132/// if no rewriter works for \p MI.
1133static CopyRewriter *getCopyRewriter(MachineInstr &MI,
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001134 const TargetInstrInfo &TII,
1135 MachineRegisterInfo &MRI) {
1136 // Handle uncoalescable copy-like instructions.
1137 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1138 MI.isExtractSubregLike()))
1139 return new UncoalescableRewriter(MI, TII, MRI);
1140
Quentin Colombet03e43f82014-08-20 17:41:48 +00001141 switch (MI.getOpcode()) {
1142 default:
1143 return nullptr;
1144 case TargetOpcode::COPY:
1145 return new CopyRewriter(MI);
1146 case TargetOpcode::INSERT_SUBREG:
1147 return new InsertSubregRewriter(MI);
1148 case TargetOpcode::EXTRACT_SUBREG:
1149 return new ExtractSubregRewriter(MI, TII);
1150 case TargetOpcode::REG_SEQUENCE:
1151 return new RegSequenceRewriter(MI);
1152 }
1153 llvm_unreachable(nullptr);
1154}
1155
1156/// \brief Optimize generic copy instructions to avoid cross
1157/// register bank copy. The optimization looks through a chain of
1158/// copies and tries to find a source that has a compatible register
1159/// class.
1160/// Two register classes are considered to be compatible if they share
1161/// the same register bank.
1162/// New copies issued by this optimization are register allocator
1163/// friendly. This optimization does not remove any copy as it may
Matt Arsenault30991562015-09-09 00:38:33 +00001164/// overconstrain the register allocator, but replaces some operands
Quentin Colombet03e43f82014-08-20 17:41:48 +00001165/// when possible.
1166/// \pre isCoalescableCopy(*MI) is true.
1167/// \return True, when \p MI has been rewritten. False otherwise.
1168bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1169 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1170 assert(MI->getDesc().getNumDefs() == 1 &&
1171 "Coalescer can understand multiple defs?!");
1172 const MachineOperand &MODef = MI->getOperand(0);
1173 // Do not rewrite physical definitions.
1174 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1175 return false;
1176
1177 bool Changed = false;
1178 // Get the right rewriter for the current copy.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001179 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001180 // If none exists, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001181 if (!CpyRewriter)
1182 return false;
1183 // Rewrite each rewritable source.
1184 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1185 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1186 TrackSubReg)) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001187 // Keep track of PHI nodes and its incoming edges when looking for sources.
1188 RewriteMapTy RewriteMap;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001189 // Try to find a more suitable source. If we failed to do so, or get the
1190 // actual source, move to the next source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001191 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001192 continue;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001193
1194 // Get the new source to rewrite. TODO: Only enable handling of multiple
1195 // sources (PHIs) once we have a motivating example and testcases for it.
1196 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1197 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1198 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1199 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1200 continue;
1201
Quentin Colombet03e43f82014-08-20 17:41:48 +00001202 // Rewrite source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001203 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +00001204 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001205 MRI->clearKillFlags(NewSrc.Reg);
Quentin Colombet6b363372014-08-21 21:34:06 +00001206 Changed = true;
1207 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001208 }
1209 // TODO: We could have a clean-up method to tidy the instruction.
1210 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1211 // => v0 = COPY v1
1212 // Currently we haven't seen motivating example for that and we
1213 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +00001214 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001215 return Changed;
1216}
1217
1218/// \brief Optimize copy-like instructions to create
1219/// register coalescer friendly instruction.
1220/// The optimization tries to kill-off the \p MI by looking
1221/// through a chain of copies to find a source that has a compatible
1222/// register class.
1223/// If such a source is found, it replace \p MI by a generic COPY
1224/// operation.
1225/// \pre isUncoalescableCopy(*MI) is true.
1226/// \return True, when \p MI has been optimized. In that case, \p MI has
1227/// been removed from its parent.
1228/// All COPY instructions created, are inserted in \p LocalMIs.
1229bool PeepholeOptimizer::optimizeUncoalescableCopy(
1230 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1231 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1232
1233 // Check if we can rewrite all the values defined by this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001234 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001235 // Get the right rewriter for the current copy.
1236 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001237 // If none exists, bail out.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001238 if (!CpyRewriter)
1239 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001240
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001241 // Rewrite each rewritable source by generating new COPYs. This works
1242 // differently from optimizeCoalescableCopy since it first makes sure that all
1243 // definitions can be rewritten.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001244 RewriteMapTy RewriteMap;
1245 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1246 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1247 CopyDefSubReg)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001248 // If a physical register is here, this is probably for a good reason.
1249 // Do not rewrite that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001250 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001251 return false;
1252
1253 // If we do not know how to rewrite this definition, there is no point
1254 // in trying to kill this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001255 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1256 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001257 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001258
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001259 RewritePairs.push_back(Def);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001260 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001261
Quentin Colombet03e43f82014-08-20 17:41:48 +00001262 // The change is possible for all defs, do it.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001263 for (const auto &Def : RewritePairs) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001264 // Rewrite the "copy" in a way the register coalescer understands.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001265 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001266 assert(NewCopy && "Should be able to always generate a new copy");
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001267 LocalMIs.insert(NewCopy);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001268 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001269
Quentin Colombet03e43f82014-08-20 17:41:48 +00001270 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +00001271 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001272 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +00001273 return true;
1274}
1275
Manman Ren5759d012012-08-02 00:56:42 +00001276/// isLoadFoldable - Check whether MI is a candidate for folding into a later
1277/// instruction. We only fold loads to virtual registers and the virtual
1278/// register defined has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001279bool PeepholeOptimizer::isLoadFoldable(
1280 MachineInstr *MI,
1281 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +00001282 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1283 return false;
1284 const MCInstrDesc &MCID = MI->getDesc();
1285 if (MCID.getNumDefs() != 1)
1286 return false;
1287
1288 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001289 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001290 // loads. It should be checked when processing uses of the load, since
1291 // uses can be removed during peephole.
1292 if (!MI->getOperand(0).getSubReg() &&
1293 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001294 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001295 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001296 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001297 }
1298 return false;
1299}
1300
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001301bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1302 SmallSet<unsigned, 4> &ImmDefRegs,
1303 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001304 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001305 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001306 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001307 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001308 return false;
1309 unsigned Reg = MI->getOperand(0).getReg();
1310 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1311 ImmDefMIs.insert(std::make_pair(Reg, MI));
1312 ImmDefRegs.insert(Reg);
1313 return true;
1314 }
Andrew Trick9e761992012-02-08 21:22:43 +00001315
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001316 return false;
1317}
1318
Jim Grosbachedcb8682012-05-01 23:21:41 +00001319/// foldImmediate - Try folding register operands that are defined by move
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001320/// immediate instructions, i.e. a trivial constant folding optimization, if
1321/// and only if the def and use are in the same BB.
Jim Grosbachedcb8682012-05-01 23:21:41 +00001322bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001323 SmallSet<unsigned, 4> &ImmDefRegs,
1324 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1325 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1326 MachineOperand &MO = MI->getOperand(i);
1327 if (!MO.isReg() || MO.isDef())
1328 continue;
1329 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001330 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001331 continue;
1332 if (ImmDefRegs.count(Reg) == 0)
1333 continue;
1334 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1335 assert(II != ImmDefMIs.end());
1336 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1337 ++NumImmFold;
1338 return true;
1339 }
1340 }
1341 return false;
1342}
1343
Matt Arsenault10aa8072015-09-25 20:22:12 +00001344// FIXME: This is very simple and misses some cases which should be handled when
1345// motivating examples are found.
1346//
1347// The copy rewriting logic should look at uses as well as defs and be able to
1348// eliminate copies across blocks.
1349//
1350// Later copies that are subregister extracts will also not be eliminated since
1351// only the first copy is considered.
1352//
1353// e.g.
1354// %vreg1 = COPY %vreg0
1355// %vreg2 = COPY %vreg0:sub1
1356//
1357// Should replace %vreg2 uses with %vreg1:sub1
1358bool PeepholeOptimizer::foldRedundantCopy(
1359 MachineInstr *MI,
1360 SmallSet<unsigned, 4> &CopySrcRegs,
1361 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1362 assert(MI->isCopy());
1363
1364 unsigned SrcReg = MI->getOperand(1).getReg();
1365 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1366 return false;
1367
1368 unsigned DstReg = MI->getOperand(0).getReg();
1369 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1370 return false;
1371
1372 if (CopySrcRegs.insert(SrcReg).second) {
1373 // First copy of this reg seen.
1374 CopyMIs.insert(std::make_pair(SrcReg, MI));
1375 return false;
1376 }
1377
1378 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1379
1380 unsigned SrcSubReg = MI->getOperand(1).getSubReg();
1381 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1382
1383 // Can't replace different subregister extracts.
1384 if (SrcSubReg != PrevSrcSubReg)
1385 return false;
1386
1387 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1388
1389 // Only replace if the copy register class is the same.
1390 //
1391 // TODO: If we have multiple copies to different register classes, we may want
1392 // to track multiple copies of the same source register.
1393 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1394 return false;
1395
1396 MRI->replaceRegWith(DstReg, PrevDstReg);
1397
1398 // Lifetime of the previous copy has been extended.
1399 MRI->clearKillFlags(PrevDstReg);
1400 return true;
1401}
1402
Eric Christopher2181fb22014-10-15 21:06:25 +00001403bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1404 if (skipOptnoneFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001405 return false;
1406
Craig Topper588ceec2012-12-17 03:56:00 +00001407 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001408 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001409
Evan Cheng2ce016c2010-11-15 21:20:45 +00001410 if (DisablePeephole)
1411 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001412
Eric Christopher2181fb22014-10-15 21:06:25 +00001413 TII = MF.getSubtarget().getInstrInfo();
1414 TRI = MF.getSubtarget().getRegisterInfo();
1415 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001416 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendlingca678352010-08-09 23:59:04 +00001417
1418 bool Changed = false;
1419
Eric Christopher2181fb22014-10-15 21:06:25 +00001420 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Bill Wendlingca678352010-08-09 23:59:04 +00001421 MachineBasicBlock *MBB = &*I;
Andrew Trick9e761992012-02-08 21:22:43 +00001422
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001423 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001424
1425 // During this forward scan, at some point it needs to answer the question
1426 // "given a pointer to an MI in the current BB, is it located before or
1427 // after the current instruction".
1428 // To perform this, the following set keeps track of the MIs already seen
1429 // during the scan, if a MI is not in the set, it is assumed to be located
1430 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001431 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001432 SmallSet<unsigned, 4> ImmDefRegs;
1433 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1434 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001435
Matt Arsenault10aa8072015-09-25 20:22:12 +00001436 // Set of virtual registers that are copied from.
1437 SmallSet<unsigned, 4> CopySrcRegs;
1438 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1439
Bill Wendlingca678352010-08-09 23:59:04 +00001440 for (MachineBasicBlock::iterator
Bill Wendlingaee679b2010-09-10 21:55:43 +00001441 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001442 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001443 // We may be erasing MI below, increment MII now.
1444 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001445 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001446
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001447 // Skip debug values. They should not affect this peephole optimization.
1448 if (MI->isDebugValue())
1449 continue;
1450
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +00001451 // If we run into an instruction we can't fold across, discard
1452 // the load candidates.
1453 if (MI->isLoadFoldBarrier())
Michael Kuperstein82814f62015-08-11 08:19:43 +00001454 FoldAsLoadDefCandidates.clear();
1455
Rafael Espindolab1f25f12014-03-07 06:08:31 +00001456 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001457 MI->isKill() || MI->isInlineAsm() ||
Michael Kuperstein82814f62015-08-11 08:19:43 +00001458 MI->hasUnmodeledSideEffects())
Evan Cheng2ce016c2010-11-15 21:20:45 +00001459 continue;
1460
Quentin Colombet03e43f82014-08-20 17:41:48 +00001461 if ((isUncoalescableCopy(*MI) &&
1462 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001463 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
Mehdi Amini22e59742015-01-13 07:07:13 +00001464 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001465 // MI is deleted.
1466 LocalMIs.erase(MI);
1467 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001468 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001469 }
1470
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001471 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1472 Changed = true;
1473 continue;
1474 }
1475
Quentin Colombet03e43f82014-08-20 17:41:48 +00001476 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1477 // MI is just rewritten.
1478 Changed = true;
1479 continue;
1480 }
1481
Matt Arsenault10aa8072015-09-25 20:22:12 +00001482 if (MI->isCopy() && foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs)) {
1483 LocalMIs.erase(MI);
1484 MI->eraseFromParent();
1485 Changed = true;
1486 continue;
1487 }
1488
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001489 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001490 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001491 } else {
Jim Grosbachedcb8682012-05-01 23:21:41 +00001492 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001493 // optimizeExtInstr might have created new instructions after MI
1494 // and before the already incremented MII. Adjust MII so that the
1495 // next iteration sees the new instructions.
1496 MII = MI;
1497 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001498 if (SeenMoveImm)
Jim Grosbachedcb8682012-05-01 23:21:41 +00001499 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001500 }
Evan Cheng98196b42011-02-15 05:00:24 +00001501
Manman Ren5759d012012-08-02 00:56:42 +00001502 // Check whether MI is a load candidate for folding into a later
1503 // instruction. If MI is not a candidate, check whether we can fold an
1504 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001505 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1506 !FoldAsLoadDefCandidates.empty()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001507 const MCInstrDesc &MIDesc = MI->getDesc();
1508 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1509 ++i) {
1510 const MachineOperand &MOp = MI->getOperand(i);
1511 if (!MOp.isReg())
1512 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001513 unsigned FoldAsLoadDefReg = MOp.getReg();
1514 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1515 // We need to fold load after optimizeCmpInstr, since
1516 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1517 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1518 // we need it for markUsesInDebugValueAsUndef().
1519 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001520 MachineInstr *DefMI = nullptr;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001521 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1522 FoldAsLoadDefReg,
Lang Hames5dc14bd2014-04-02 22:59:58 +00001523 DefMI);
1524 if (FoldMI) {
1525 // Update LocalMIs since we replaced MI with FoldMI and deleted
1526 // DefMI.
1527 DEBUG(dbgs() << "Replacing: " << *MI);
1528 DEBUG(dbgs() << " With: " << *FoldMI);
1529 LocalMIs.erase(MI);
1530 LocalMIs.erase(DefMI);
1531 LocalMIs.insert(FoldMI);
1532 MI->eraseFromParent();
1533 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001534 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1535 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001536 ++NumLoadFold;
1537 // MI is replaced with FoldMI.
1538 Changed = true;
1539 break;
1540 }
1541 }
Manman Ren5759d012012-08-02 00:56:42 +00001542 }
1543 }
Bill Wendlingca678352010-08-09 23:59:04 +00001544 }
1545 }
1546
1547 return Changed;
1548}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001549
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001550ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001551 assert(Def->isCopy() && "Invalid definition");
1552 // Copy instruction are supposed to be: Def = Src.
1553 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001554 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001555
1556 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1557 // If we look for a different subreg, it means we want a subreg of src.
Matt Arsenault30991562015-09-09 00:38:33 +00001558 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001559 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001560 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001561 const MachineOperand &Src = Def->getOperand(1);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001562 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001563}
1564
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001565ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001566 assert(Def->isBitcast() && "Invalid definition");
1567
1568 // Bail if there are effects that a plain copy will not expose.
1569 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001570 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001571
1572 // Bitcasts with more than one def are not supported.
1573 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001574 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001575 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1576 // If we look for a different subreg, it means we want a subreg of the src.
Matt Arsenault30991562015-09-09 00:38:33 +00001577 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001578 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001579
Quentin Colombet03e43f82014-08-20 17:41:48 +00001580 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001581 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1582 ++OpIdx) {
1583 const MachineOperand &MO = Def->getOperand(OpIdx);
1584 if (!MO.isReg() || !MO.getReg())
1585 continue;
1586 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1587 if (SrcIdx != EndOpIdx)
1588 // Multiple sources?
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001589 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001590 SrcIdx = OpIdx;
1591 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001592 const MachineOperand &Src = Def->getOperand(SrcIdx);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001593 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001594}
1595
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001596ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001597 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1598 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001599
1600 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001601 // If we are composing subregs, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001602 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1603 // This should almost never happen as the SSA property is tracked at
1604 // the register level (as opposed to the subreg level).
1605 // I.e.,
1606 // Def.sub0 =
1607 // Def.sub1 =
1608 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1609 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001610 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001611 // Def.sub0 (i.e, not defining the other subregs) and we would
1612 // have this case.
1613 // If we can ascertain (or force) that this never happens, we could
1614 // turn that into an assertion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001615 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001616
Quentin Colombet03e43f82014-08-20 17:41:48 +00001617 if (!TII)
1618 // We could handle the REG_SEQUENCE here, but we do not want to
1619 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001620 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001621
1622 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1623 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001624 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001625
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001626 // We are looking at:
1627 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1628 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001629 for (auto &RegSeqInput : RegSeqInputRegs) {
1630 if (RegSeqInput.SubIdx == DefSubReg) {
1631 if (RegSeqInput.SubReg)
Matt Arsenault30991562015-09-09 00:38:33 +00001632 // Bail if we have to compose sub registers.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001633 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001634
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001635 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001636 }
1637 }
1638
1639 // If the subreg we are tracking is super-defined by another subreg,
1640 // we could follow this value. However, this would require to compose
1641 // the subreg and we do not do that for now.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001642 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001643}
1644
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001645ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
Quentin Colombet68962302014-08-21 00:19:16 +00001646 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1647 "Invalid definition");
1648
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001649 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001650 // If we are composing subreg, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001651 // Same remark as getNextSourceFromRegSequence.
1652 // I.e., this may be turned into an assert.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001653 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001654
Quentin Colombet68962302014-08-21 00:19:16 +00001655 if (!TII)
1656 // We could handle the REG_SEQUENCE here, but we do not want to
1657 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001658 return ValueTrackerResult();
Quentin Colombet68962302014-08-21 00:19:16 +00001659
Quentin Colombet03e43f82014-08-20 17:41:48 +00001660 TargetInstrInfo::RegSubRegPair BaseReg;
1661 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001662 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001663 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001664
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001665 // We are looking at:
1666 // Def = INSERT_SUBREG v0, v1, sub1
1667 // There are two cases:
1668 // 1. DefSubReg == sub1, get v1.
1669 // 2. DefSubReg != sub1, the value may be available through v0.
1670
Quentin Colombet03e43f82014-08-20 17:41:48 +00001671 // #1 Check if the inserted register matches the required sub index.
1672 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001673 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001674 }
1675 // #2 Otherwise, if the sub register we are looking for is not partial
1676 // defined by the inserted element, we can look through the main
1677 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001678 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001679 // If the result register (Def) and the base register (v0) do not
1680 // have the same register class or if we have to compose
Matt Arsenault30991562015-09-09 00:38:33 +00001681 // subregisters, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001682 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1683 BaseReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001684 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001685
Quentin Colombet03e43f82014-08-20 17:41:48 +00001686 // Get the TRI and check if the inserted sub-register overlaps with the
1687 // sub-register we are tracking.
1688 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001689 if (!TRI ||
1690 (TRI->getSubRegIndexLaneMask(DefSubReg) &
Quentin Colombet03e43f82014-08-20 17:41:48 +00001691 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001692 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001693 // At this point, the value is available in v0 via the same subreg
1694 // we used for Def.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001695 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001696}
1697
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001698ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
Quentin Colombet67639df2014-08-20 23:13:02 +00001699 assert((Def->isExtractSubreg() ||
1700 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001701 // We are looking at:
1702 // Def = EXTRACT_SUBREG v0, sub0
1703
Matt Arsenault30991562015-09-09 00:38:33 +00001704 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001705 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1706 if (DefSubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001707 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001708
Quentin Colombet67639df2014-08-20 23:13:02 +00001709 if (!TII)
1710 // We could handle the EXTRACT_SUBREG here, but we do not want to
1711 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001712 return ValueTrackerResult();
Quentin Colombet67639df2014-08-20 23:13:02 +00001713
Quentin Colombet03e43f82014-08-20 17:41:48 +00001714 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001715 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001716 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001717
Matt Arsenault30991562015-09-09 00:38:33 +00001718 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001719 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001720 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001721 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001722 // Otherwise, the value is available in the v0.sub0.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001723 return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001724}
1725
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001726ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001727 assert(Def->isSubregToReg() && "Invalid definition");
1728 // We are looking at:
1729 // Def = SUBREG_TO_REG Imm, v0, sub0
1730
Matt Arsenault30991562015-09-09 00:38:33 +00001731 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001732 // If DefSubReg != sub0, we would have to check that all the bits
1733 // we track are included in sub0 and if yes, we would have to
1734 // determine the right subreg in v0.
1735 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001736 return ValueTrackerResult();
Matt Arsenault30991562015-09-09 00:38:33 +00001737 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001738 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1739 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001740 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001741
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001742 return ValueTrackerResult(Def->getOperand(2).getReg(),
1743 Def->getOperand(3).getImm());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001744}
1745
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001746/// \brief Explore each PHI incoming operand and return its sources
1747ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1748 assert(Def->isPHI() && "Invalid definition");
1749 ValueTrackerResult Res;
1750
Matt Arsenault30991562015-09-09 00:38:33 +00001751 // If we look for a different subreg, bail as we do not support composing
1752 // subregs yet.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001753 if (Def->getOperand(0).getSubReg() != DefSubReg)
1754 return ValueTrackerResult();
1755
1756 // Return all register sources for PHI instructions.
1757 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1758 auto &MO = Def->getOperand(i);
1759 assert(MO.isReg() && "Invalid PHI instruction");
1760 Res.addSource(MO.getReg(), MO.getSubReg());
1761 }
1762
1763 return Res;
1764}
1765
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001766ValueTrackerResult ValueTracker::getNextSourceImpl() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001767 assert(Def && "This method needs a valid definition");
1768
1769 assert(
1770 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1771 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1772 if (Def->isCopy())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001773 return getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001774 if (Def->isBitcast())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001775 return getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001776 // All the remaining cases involve "complex" instructions.
Matt Arsenault30991562015-09-09 00:38:33 +00001777 // Bail if we did not ask for the advanced tracking.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001778 if (!UseAdvancedTracking)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001779 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001780 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001781 return getNextSourceFromRegSequence();
Quentin Colombet68962302014-08-21 00:19:16 +00001782 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001783 return getNextSourceFromInsertSubreg();
Quentin Colombet67639df2014-08-20 23:13:02 +00001784 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001785 return getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001786 if (Def->isSubregToReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001787 return getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001788 if (Def->isPHI())
1789 return getNextSourceFromPHI();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001790 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001791}
1792
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001793ValueTrackerResult ValueTracker::getNextSource() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001794 // If we reach a point where we cannot move up in the use-def chain,
1795 // there is nothing we can get.
1796 if (!Def)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001797 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001798
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001799 ValueTrackerResult Res = getNextSourceImpl();
1800 if (Res.isValid()) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001801 // Update definition, definition index, and subregister for the
1802 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001803 // Update the current register.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001804 bool OneRegSrc = Res.getNumSources() == 1;
1805 if (OneRegSrc)
1806 Reg = Res.getSrcReg(0);
1807 // Update the result before moving up in the use-def chain
1808 // with the instruction containing the last found sources.
1809 Res.setInst(Def);
1810
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001811 // If we can still move up in the use-def chain, move to the next
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001812 // definition.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001813 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001814 Def = MRI.getVRegDef(Reg);
1815 DefIdx = MRI.def_begin(Reg).getOperandNo();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001816 DefSubReg = Res.getSrcSubReg(0);
1817 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001818 }
1819 }
1820 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001821 // for the next iteration. Make sure any new call to getNextSource bails out
1822 // early by cutting the use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001823 Def = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001824 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001825}