blob: b13f6b68c420f2be3aa59e5e1fe010b88833dbd4 [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
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000069#include "llvm/ADT/DenseMap.h"
Bill Wendlingca678352010-08-09 23:59:04 +000070#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000071#include "llvm/ADT/SmallSet.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000072#include "llvm/ADT/SmallVector.h"
Bill Wendlingca678352010-08-09 23:59:04 +000073#include "llvm/ADT/Statistic.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000074#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000075#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000076#include "llvm/CodeGen/MachineFunction.h"
77#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000078#include "llvm/CodeGen/MachineInstrBuilder.h"
Taewook Oh0e35ea32017-06-29 23:11:24 +000079#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000080#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000081#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000082#include "llvm/CodeGen/Passes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000083#include "llvm/MC/MCInstrDesc.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000084#include "llvm/Support/CommandLine.h"
Craig Topper588ceec2012-12-17 03:56:00 +000085#include "llvm/Support/Debug.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000086#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000087#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000088#include "llvm/Target/TargetInstrInfo.h"
89#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000090#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000091#include <cassert>
92#include <cstdint>
93#include <memory>
Quentin Colombet03e43f82014-08-20 17:41:48 +000094#include <utility>
Eugene Zelenko1804a772016-08-25 00:45:04 +000095
Bill Wendlingca678352010-08-09 23:59:04 +000096using namespace llvm;
97
Chandler Carruth1b9dde02014-04-22 02:02:50 +000098#define DEBUG_TYPE "peephole-opt"
99
Bill Wendlingca678352010-08-09 23:59:04 +0000100// Optimize Extensions
101static cl::opt<bool>
102Aggressive("aggressive-ext-opt", cl::Hidden,
103 cl::desc("Aggressive extension optimization"));
104
Bill Wendlingc6627ee2010-11-01 20:41:43 +0000105static cl::opt<bool>
106DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
107 cl::desc("Disable the peephole optimizer"));
108
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000109static cl::opt<bool>
Quentin Colombet6674b092014-08-21 22:23:52 +0000110DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000111 cl::desc("Disable advanced copy optimization"));
112
JF Bastien1ac69942015-12-03 23:43:56 +0000113static cl::opt<bool> DisableNAPhysCopyOpt(
114 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
115 cl::desc("Disable non-allocatable physical register copy optimization"));
116
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000117// Limit the number of PHI instructions to process
118// in PeepholeOptimizer::getNextSource.
119static cl::opt<unsigned> RewritePHILimit(
120 "rewrite-phi-limit", cl::Hidden, cl::init(10),
121 cl::desc("Limit the length of PHI chains to lookup"));
122
Taewook Oh0e35ea32017-06-29 23:11:24 +0000123// Limit the length of recurrence chain when evaluating the benefit of
124// commuting operands.
125static cl::opt<unsigned> MaxRecurrenceChain(
126 "recurrence-chain-limit", cl::Hidden, cl::init(3),
127 cl::desc("Maximum length of recurrence chain when evaluating the benefit "
128 "of commuting operands"));
129
130
Bill Wendling66284312010-08-27 20:39:09 +0000131STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000132STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000133STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000134STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000135STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000136STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
137STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
JF Bastien1ac69942015-12-03 23:43:56 +0000138STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
Bill Wendlingca678352010-08-09 23:59:04 +0000139
140namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000141
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000142 class ValueTrackerResult;
Taewook Oh0e35ea32017-06-29 23:11:24 +0000143 class RecurrenceInstr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000144
Bill Wendlingca678352010-08-09 23:59:04 +0000145 class PeepholeOptimizer : public MachineFunctionPass {
Bill Wendlingca678352010-08-09 23:59:04 +0000146 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000147 const TargetRegisterInfo *TRI;
Bill Wendlingca678352010-08-09 23:59:04 +0000148 MachineRegisterInfo *MRI;
149 MachineDominatorTree *DT; // Machine dominator tree
Taewook Oh0e35ea32017-06-29 23:11:24 +0000150 MachineLoopInfo *MLI;
Bill Wendlingca678352010-08-09 23:59:04 +0000151
152 public:
153 static char ID; // Pass identification
Eugene Zelenko1804a772016-08-25 00:45:04 +0000154
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000155 PeepholeOptimizer() : MachineFunctionPass(ID) {
156 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
157 }
Bill Wendlingca678352010-08-09 23:59:04 +0000158
Craig Topper4584cd52014-03-07 09:26:03 +0000159 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000160
Craig Topper4584cd52014-03-07 09:26:03 +0000161 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000162 AU.setPreservesCFG();
163 MachineFunctionPass::getAnalysisUsage(AU);
Taewook Oh0e35ea32017-06-29 23:11:24 +0000164 AU.addRequired<MachineLoopInfo>();
165 AU.addPreserved<MachineLoopInfo>();
Bill Wendlingca678352010-08-09 23:59:04 +0000166 if (Aggressive) {
167 AU.addRequired<MachineDominatorTree>();
168 AU.addPreserved<MachineDominatorTree>();
169 }
170 }
171
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000172 /// \brief Track Def -> Use info used for rewriting copies.
173 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
174 RewriteMapTy;
175
Taewook Oh0e35ea32017-06-29 23:11:24 +0000176 /// \brief Sequence of instructions that formulate recurrence cycle.
177 typedef SmallVector<RecurrenceInstr, 4> RecurrenceCycle;
178
Bill Wendlingca678352010-08-09 23:59:04 +0000179 private:
Jim Grosbachedcb8682012-05-01 23:21:41 +0000180 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
181 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000182 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Mehdi Amini22e59742015-01-13 07:07:13 +0000183 bool optimizeSelect(MachineInstr *MI,
184 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000185 bool optimizeCondBranch(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000186 bool optimizeCoalescableCopy(MachineInstr *MI);
187 bool optimizeUncoalescableCopy(MachineInstr *MI,
188 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Taewook Oh0e35ea32017-06-29 23:11:24 +0000189 bool optimizeRecurrence(MachineInstr &PHI);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000190 bool findNextSource(unsigned Reg, unsigned SubReg,
191 RewriteMapTy &RewriteMap);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000192 bool isMoveImmediate(MachineInstr *MI,
193 SmallSet<unsigned, 4> &ImmDefRegs,
194 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000195 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000196 SmallSet<unsigned, 4> &ImmDefRegs,
197 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Taewook Oh0e35ea32017-06-29 23:11:24 +0000198 /// \brief Finds recurrence cycles, but only ones that formulated around
199 /// a def operand and a use operand that are tied. If there is a use
200 /// operand commutable with the tied use operand, find recurrence cycle
201 /// along that operand as well.
202 bool findTargetRecurrence(unsigned Reg,
203 const SmallSet<unsigned, 2> &TargetReg,
204 RecurrenceCycle &RC);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000205
206 /// \brief If copy instruction \p MI is a virtual register copy, track it in
JF Bastien1ac69942015-12-03 23:43:56 +0000207 /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
Matt Arsenault10aa8072015-09-25 20:22:12 +0000208 /// previously seen as a copy, replace the uses of this copy with the
209 /// previously seen copy's destination register.
210 bool foldRedundantCopy(MachineInstr *MI,
JF Bastien1ac69942015-12-03 23:43:56 +0000211 SmallSet<unsigned, 4> &CopySrcRegs,
212 DenseMap<unsigned, MachineInstr *> &CopyMIs);
213
214 /// \brief Is the register \p Reg a non-allocatable physical register?
215 bool isNAPhysCopy(unsigned Reg);
216
217 /// \brief If copy instruction \p MI is a non-allocatable virtual<->physical
218 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
219 /// non-allocatable physical register was previously copied to a virtual
220 /// registered and hasn't been clobbered, the virt->phys copy can be
221 /// deleted.
222 bool foldRedundantNAPhysCopy(
223 MachineInstr *MI,
224 DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000225
Lang Hames5dc14bd2014-04-02 22:59:58 +0000226 bool isLoadFoldable(MachineInstr *MI,
227 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000228
229 /// \brief Check whether \p MI is understood by the register coalescer
230 /// but may require some rewriting.
231 bool isCoalescableCopy(const MachineInstr &MI) {
232 // SubregToRegs are not interesting, because they are already register
233 // coalescer friendly.
234 return MI.isCopy() || (!DisableAdvCopyOpt &&
235 (MI.isRegSequence() || MI.isInsertSubreg() ||
236 MI.isExtractSubreg()));
237 }
238
239 /// \brief Check whether \p MI is a copy like instruction that is
240 /// not recognized by the register coalescer.
241 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000242 return MI.isBitcast() ||
243 (!DisableAdvCopyOpt &&
244 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
245 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000246 }
Bill Wendlingca678352010-08-09 23:59:04 +0000247 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000248
Taewook Oh0e35ea32017-06-29 23:11:24 +0000249 /// \brief Helper class to hold instructions that are inside recurrence
250 /// cycles. The recurrence cycle is formulated around 1) a def operand and its
251 /// tied use operand, or 2) a def operand and a use operand that is commutable
252 /// with another use operand which is tied to the def operand. In the latter
253 /// case, index of the tied use operand and the commutable use operand are
254 /// maintained with CommutePair.
255 class RecurrenceInstr {
256 public:
257 typedef std::pair<unsigned, unsigned> IndexPair;
258
259 RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
260 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
261 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
262
263 MachineInstr *getMI() const { return MI; }
264 Optional<IndexPair> getCommutePair() const { return CommutePair; }
265
266 private:
267 MachineInstr *MI;
268 Optional<IndexPair> CommutePair;
269 };
270
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000271 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
272 /// returned sources for a given search and the instructions where the sources
273 /// were tracked from.
274 class ValueTrackerResult {
275 private:
276 /// Track all sources found by one ValueTracker query.
277 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
278
279 /// Instruction using the sources in 'RegSrcs'.
280 const MachineInstr *Inst;
281
282 public:
283 ValueTrackerResult() : Inst(nullptr) {}
284 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
285 addSource(Reg, SubReg);
286 }
287
288 bool isValid() const { return getNumSources() > 0; }
289
290 void setInst(const MachineInstr *I) { Inst = I; }
291 const MachineInstr *getInst() const { return Inst; }
292
293 void clear() {
294 RegSrcs.clear();
295 Inst = nullptr;
296 }
297
298 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
299 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
300 }
301
302 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
303 assert(Idx < getNumSources() && "Reg pair source out of index");
304 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
305 }
306
307 int getNumSources() const { return RegSrcs.size(); }
308
309 unsigned getSrcReg(int Idx) const {
310 assert(Idx < getNumSources() && "Reg source out of index");
311 return RegSrcs[Idx].Reg;
312 }
313
314 unsigned getSrcSubReg(int Idx) const {
315 assert(Idx < getNumSources() && "SubReg source out of index");
316 return RegSrcs[Idx].SubReg;
317 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000318
319 bool operator==(const ValueTrackerResult &Other) {
320 if (Other.getInst() != getInst())
321 return false;
322
323 if (Other.getNumSources() != getNumSources())
324 return false;
325
326 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
327 if (Other.getSrcReg(i) != getSrcReg(i) ||
328 Other.getSrcSubReg(i) != getSrcSubReg(i))
329 return false;
330 return true;
331 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000332 };
333
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000334 /// \brief Helper class to track the possible sources of a value defined by
335 /// a (chain of) copy related instructions.
336 /// Given a definition (instruction and definition index), this class
337 /// follows the use-def chain to find successive suitable sources.
338 /// The given source can be used to rewrite the definition into
339 /// def = COPY src.
340 ///
341 /// For instance, let us consider the following snippet:
342 /// v0 =
343 /// v2 = INSERT_SUBREG v1, v0, sub0
344 /// def = COPY v2.sub0
345 ///
346 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
347 /// suitable sources:
348 /// v2.sub0 and v0.
349 /// Then, def can be rewritten into def = COPY v0.
350 class ValueTracker {
351 private:
352 /// The current point into the use-def chain.
353 const MachineInstr *Def;
354 /// The index of the definition in Def.
355 unsigned DefIdx;
356 /// The sub register index of the definition.
357 unsigned DefSubReg;
358 /// The register where the value can be found.
359 unsigned Reg;
360 /// Specifiy whether or not the value tracking looks through
361 /// complex instructions. When this is false, the value tracker
362 /// bails on everything that is not a copy or a bitcast.
363 ///
364 /// Note: This could have been implemented as a specialized version of
365 /// the ValueTracker class but that would have complicated the code of
366 /// the users of this class.
367 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000368 /// MachineRegisterInfo used to perform tracking.
369 const MachineRegisterInfo &MRI;
370 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000371 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000372 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000373
374 /// \brief Dispatcher to the right underlying implementation of
375 /// getNextSource.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000376 ValueTrackerResult getNextSourceImpl();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000377 /// \brief Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000378 ValueTrackerResult getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000379 /// \brief Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000380 ValueTrackerResult getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000381 /// \brief Specialized version of getNextSource for RegSequence
382 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000383 ValueTrackerResult getNextSourceFromRegSequence();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000384 /// \brief Specialized version of getNextSource for InsertSubreg
385 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000386 ValueTrackerResult getNextSourceFromInsertSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000387 /// \brief Specialized version of getNextSource for ExtractSubreg
388 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000389 ValueTrackerResult getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000390 /// \brief Specialized version of getNextSource for SubregToReg
391 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000392 ValueTrackerResult getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000393 /// \brief Specialized version of getNextSource for PHI instructions.
394 ValueTrackerResult getNextSourceFromPHI();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000395
396 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000397 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000398 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000399 /// track. It does not need to match the sub register index used in the
400 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000401 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
402 /// through complex instructions. By default (false), it handles only copy
403 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000404 /// If \p Reg is a physical register, a value tracker constructed with
405 /// this constructor will not find any alternative source.
406 /// Indeed, when \p Reg is a physical register that constructor does not
407 /// know which definition of \p Reg it should track.
408 /// Use the next constructor to track a physical register.
409 ValueTracker(unsigned Reg, unsigned DefSubReg,
410 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000411 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000412 const TargetInstrInfo *TII = nullptr)
413 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
414 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
415 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
416 Def = MRI.getVRegDef(Reg);
417 DefIdx = MRI.def_begin(Reg).getOperandNo();
418 }
419 }
420
421 /// \brief Create a ValueTracker instance for the value defined by
422 /// the pair \p MI, \p DefIdx.
423 /// Unlike the other constructor, the value tracker produced by this one
424 /// may be able to find a new source when the definition is a physical
425 /// register.
426 /// This could be useful to rewrite target specific instructions into
427 /// generic copy instructions.
428 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
429 const MachineRegisterInfo &MRI,
430 bool UseAdvancedTracking = false,
431 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000432 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000433 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
434 assert(DefIdx < Def->getDesc().getNumDefs() &&
435 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000436 Reg = Def->getOperand(DefIdx).getReg();
437 }
438
439 /// \brief Following the use-def chain, get the next available source
440 /// for the tracked value.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000441 /// \return A ValueTrackerResult containing a set of registers
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000442 /// and sub registers with tracked values. A ValueTrackerResult with
443 /// an empty set of registers means no source was found.
444 ValueTrackerResult getNextSource();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000445
446 /// \brief Get the last register where the initial value can be found.
447 /// Initially this is the register of the definition.
448 /// Then, after each successful call to getNextSource, this is the
449 /// register of the last source.
450 unsigned getReg() const { return Reg; }
451 };
Eugene Zelenko1804a772016-08-25 00:45:04 +0000452
453} // end anonymous namespace
Bill Wendlingca678352010-08-09 23:59:04 +0000454
455char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000456char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Eugene Zelenko1804a772016-08-25 00:45:04 +0000457
Matt Arsenault44540a32016-07-08 16:29:11 +0000458INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
Owen Anderson8ac477f2010-10-12 19:48:12 +0000459 "Peephole Optimizations", false, false)
460INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Taewook Oh0e35ea32017-06-29 23:11:24 +0000461INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matt Arsenault44540a32016-07-08 16:29:11 +0000462INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
Owen Andersondf7a4f22010-10-07 22:25:06 +0000463 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000464
Sanjay Patel59309cc2015-12-29 18:14:06 +0000465/// If instruction is a copy-like instruction, i.e. it reads a single register
466/// and writes a single register and it does not modify the source, and if the
467/// source value is preserved as a sub-register of the result, then replace all
468/// reachable uses of the source with the subreg of the result.
Andrew Trick9e761992012-02-08 21:22:43 +0000469///
Bill Wendlingca678352010-08-09 23:59:04 +0000470/// Do not generate an EXTRACT that is used only in a debug use, as this changes
471/// the code. Since this code does not currently share EXTRACTs, just ignore all
472/// debug uses.
473bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000474optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000475 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000476 unsigned SrcReg, DstReg, SubIdx;
477 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
478 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000479
Bill Wendlingca678352010-08-09 23:59:04 +0000480 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
481 TargetRegisterInfo::isPhysicalRegister(SrcReg))
482 return false;
483
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000484 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000485 // No other uses.
486 return false;
487
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000488 // Ensure DstReg can get a register class that actually supports
489 // sub-registers. Don't change the class until we commit.
490 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000491 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000492 if (!DstRC)
493 return false;
494
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000495 // The ext instr may be operating on a sub-register of SrcReg as well.
496 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
497 // register.
498 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
499 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000500 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000501 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000502
Bill Wendlingca678352010-08-09 23:59:04 +0000503 // The source has other uses. See if we can replace the other uses with use of
504 // the result of the extension.
505 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000506 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
507 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000508
509 // Uses that are in the same BB of uses of the result of the instruction.
510 SmallVector<MachineOperand*, 8> Uses;
511
512 // Uses that the result of the instruction can reach.
513 SmallVector<MachineOperand*, 8> ExtendedUses;
514
515 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000516 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000517 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000518 if (UseMI == MI)
519 continue;
520
521 if (UseMI->isPHI()) {
522 ExtendLife = false;
523 continue;
524 }
525
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000526 // Only accept uses of SrcReg:SubIdx.
527 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
528 continue;
529
Bill Wendlingca678352010-08-09 23:59:04 +0000530 // It's an error to translate this:
531 //
532 // %reg1025 = <sext> %reg1024
533 // ...
534 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
535 //
536 // into this:
537 //
538 // %reg1025 = <sext> %reg1024
539 // ...
540 // %reg1027 = COPY %reg1025:4
541 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
542 //
543 // The problem here is that SUBREG_TO_REG is there to assert that an
544 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
545 // the COPY here, it will give us the value after the <sext>, not the
546 // original value of %reg1024 before <sext>.
547 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
548 continue;
549
550 MachineBasicBlock *UseMBB = UseMI->getParent();
551 if (UseMBB == MBB) {
552 // Local uses that come after the extension.
553 if (!LocalMIs.count(UseMI))
554 Uses.push_back(&UseMO);
555 } else if (ReachedBBs.count(UseMBB)) {
556 // Non-local uses where the result of the extension is used. Always
557 // replace these unless it's a PHI.
558 Uses.push_back(&UseMO);
559 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
560 // We may want to extend the live range of the extension result in order
561 // to replace these uses.
562 ExtendedUses.push_back(&UseMO);
563 } else {
564 // Both will be live out of the def MBB anyway. Don't extend live range of
565 // the extension result.
566 ExtendLife = false;
567 break;
568 }
569 }
570
571 if (ExtendLife && !ExtendedUses.empty())
572 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000573 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000574
575 // Now replace all uses.
576 bool Changed = false;
577 if (!Uses.empty()) {
578 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
579
580 // Look for PHI uses of the extended result, we don't want to extend the
581 // liveness of a PHI input. It breaks all kinds of assumptions down
582 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000583 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
584 if (UI.isPHI())
585 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000586
587 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
588 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
589 MachineOperand *UseMO = Uses[i];
590 MachineInstr *UseMI = UseMO->getParent();
591 MachineBasicBlock *UseMBB = UseMI->getParent();
592 if (PHIBBs.count(UseMBB))
593 continue;
594
Lang Hamesd5862ce2012-02-25 02:01:00 +0000595 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000596 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000597 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000598 MRI->constrainRegClass(DstReg, DstRC);
599 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000600
Bill Wendlingca678352010-08-09 23:59:04 +0000601 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000602 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
603 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000604 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000605 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
606 if (UseSrcSubIdx) {
607 Copy->getOperand(0).setSubReg(SubIdx);
608 Copy->getOperand(0).setIsUndef();
609 }
Bill Wendlingca678352010-08-09 23:59:04 +0000610 UseMO->setReg(NewVR);
611 ++NumReuse;
612 Changed = true;
613 }
614 }
615
616 return Changed;
617}
618
Sanjay Patel59309cc2015-12-29 18:14:06 +0000619/// If the instruction is a compare and the previous instruction it's comparing
620/// against already sets (or could be modified to set) the same flag as the
621/// compare, then we can remove the comparison and use the flag from the
622/// previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000623bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000624 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000625 // If this instruction is a comparison against zero and isn't comparing a
626 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000627 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000628 int CmpMask, CmpValue;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000629 if (!TII->analyzeCompare(*MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
Manman Ren6fa76dc2012-06-29 21:33:59 +0000630 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
631 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000632 return false;
633
Bill Wendling27dddd12010-09-11 00:13:50 +0000634 // Attempt to optimize the comparison instruction.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000635 if (TII->optimizeCompareInstr(*MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000636 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000637 return true;
638 }
639
640 return false;
641}
642
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000643/// Optimize a select instruction.
Mehdi Amini22e59742015-01-13 07:07:13 +0000644bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
645 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000646 unsigned TrueOp = 0;
647 unsigned FalseOp = 0;
648 bool Optimizable = false;
649 SmallVector<MachineOperand, 4> Cond;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000650 if (TII->analyzeSelect(*MI, Cond, TrueOp, FalseOp, Optimizable))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000651 return false;
652 if (!Optimizable)
653 return false;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000654 if (!TII->optimizeSelect(*MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000655 return false;
656 MI->eraseFromParent();
657 ++NumSelects;
658 return true;
659}
660
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000661/// \brief Check if a simpler conditional branch can be
662// generated
663bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000664 return TII->optimizeCondBranch(*MI);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000665}
666
Quentin Colombet03e43f82014-08-20 17:41:48 +0000667/// \brief Try to find the next source that share the same register file
668/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000669/// When true is returned, the \p RewriteMap can be used by the client to
670/// retrieve all Def -> Use along the way up to the next source. Any found
671/// Use that is not itself a key for another entry, is the next source to
672/// use. During the search for the next source, multiple sources can be found
673/// given multiple incoming sources of a PHI instruction. In this case, we
674/// look in each PHI source for the next source; all found next sources must
675/// share the same register file as \p Reg and \p SubReg. The client should
676/// then be capable to rewrite all intermediate PHIs to get the next source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000677/// \return False if no alternative sources are available. True otherwise.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000678bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
679 RewriteMapTy &RewriteMap) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000680 // Do not try to find a new source for a physical register.
681 // So far we do not have any motivating example for doing that.
682 // Thus, instead of maintaining untested code, we will revisit that if
683 // that changes at some point.
684 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000685 return false;
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000686 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000687
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000688 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
689 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
690 SrcToLook.push_back(CurSrcPair);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000691
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000692 unsigned PHICount = 0;
693 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
694 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
695 // As explained above, do not handle physical registers
696 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
697 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000698
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000699 CurSrcPair = Pair;
700 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
701 !DisableAdvCopyOpt, TII);
702 ValueTrackerResult Res;
703 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000704
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000705 do {
706 // Follow the chain of copies until we reach the top of the use-def chain
707 // or find a more suitable source.
708 Res = ValTracker.getNextSource();
709 if (!Res.isValid())
710 break;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000711
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000712 // Insert the Def -> Use entry for the recently found source.
713 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
714 if (CurSrcRes.isValid()) {
715 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
716 // An existent entry with multiple sources is a PHI cycle we must avoid.
717 // Otherwise it's an entry with a valid next source we already found.
718 if (CurSrcRes.getNumSources() > 1) {
719 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
720 return false;
721 }
722 break;
723 }
724 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
725
726 // ValueTrackerResult usually have one source unless it's the result from
727 // a PHI instruction. Add the found PHI edges to be looked up further.
728 unsigned NumSrcs = Res.getNumSources();
729 if (NumSrcs > 1) {
730 PHICount++;
731 for (unsigned i = 0; i < NumSrcs; ++i)
732 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
733 Res.getSrcReg(i), Res.getSrcSubReg(i)));
734 break;
735 }
736
737 CurSrcPair.Reg = Res.getSrcReg(0);
738 CurSrcPair.SubReg = Res.getSrcSubReg(0);
739 // Do not extend the live-ranges of physical registers as they add
740 // constraints to the register allocator. Moreover, if we want to extend
741 // the live-range of a physical register, unlike SSA virtual register,
742 // we will have to check that they aren't redefine before the related use.
743 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
744 return false;
745
746 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
Matt Arsenault68d93862015-09-24 08:36:14 +0000747 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
748 CurSrcPair.SubReg);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000749 } while (!ShouldRewrite);
750
751 // Continue looking for new sources...
752 if (Res.isValid())
753 continue;
754
755 // Do not continue searching for a new source if the there's at least
756 // one use-def which cannot be rewritten.
757 if (!ShouldRewrite)
758 return false;
759 }
760
761 if (PHICount >= RewritePHILimit) {
762 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
763 return false;
764 }
Quentin Colombetcf71c632013-09-13 18:26:31 +0000765
766 // If we did not find a more suitable source, there is nothing to optimize.
Rafael Espindola84921b92015-10-24 23:11:13 +0000767 return CurSrcPair.Reg != Reg;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000768}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000769
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000770/// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
771/// guaranteed to have the same register class. This is necessary whenever we
772/// successfully traverse a PHI instruction and find suitable sources coming
773/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
774/// suitable to be used in a new COPY instruction.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000775static MachineInstr *
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000776insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
777 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
778 MachineInstr *OrigPHI) {
779 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
780
781 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
782 unsigned NewVR = MRI->createVirtualRegister(NewRC);
783 MachineBasicBlock *MBB = OrigPHI->getParent();
784 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
785 TII->get(TargetOpcode::PHI), NewVR);
786
787 unsigned MBBOpIdx = 2;
788 for (auto RegPair : SrcRegs) {
789 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
790 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
791 // Since we're extended the lifetime of RegPair.Reg, clear the
792 // kill flags to account for that and make RegPair.Reg reaches
793 // the new PHI.
794 MRI->clearKillFlags(RegPair.Reg);
795 MBBOpIdx += 2;
796 }
797
798 return MIB;
799}
800
Quentin Colombet03e43f82014-08-20 17:41:48 +0000801namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000802
Quentin Colombet03e43f82014-08-20 17:41:48 +0000803/// \brief Helper class to rewrite the arguments of a copy-like instruction.
804class CopyRewriter {
805protected:
806 /// The copy-like instruction.
807 MachineInstr &CopyLike;
808 /// The index of the source being rewritten.
809 unsigned CurrentSrcIdx;
810
811public:
812 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
813
814 virtual ~CopyRewriter() {}
815
816 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
817 /// the related value that it affects (TrackReg, TrackSubReg).
818 /// A source is considered rewritable if its register class and the
819 /// register class of the related TrackReg may not be register
820 /// coalescer friendly. In other words, given a copy-like instruction
821 /// not all the arguments may be returned at rewritable source, since
822 /// some arguments are none to be register coalescer friendly.
823 ///
824 /// Each call of this method moves the current source to the next
825 /// rewritable source.
826 /// For instance, let CopyLike be the instruction to rewrite.
827 /// CopyLike has one definition and one source:
828 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
829 ///
830 /// The first call will give the first rewritable source, i.e.,
831 /// the only source this instruction has:
832 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
833 /// This source defines the whole definition, i.e.,
834 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
835 ///
Matt Arsenault30991562015-09-09 00:38:33 +0000836 /// The second and subsequent calls will return false, as there is only one
Quentin Colombet03e43f82014-08-20 17:41:48 +0000837 /// rewritable source.
838 ///
839 /// \return True if a rewritable source has been found, false otherwise.
840 /// The output arguments are valid if and only if true is returned.
841 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
842 unsigned &TrackReg,
843 unsigned &TrackSubReg) {
Matt Arsenault30991562015-09-09 00:38:33 +0000844 // If CurrentSrcIdx == 1, this means this function has already been called
845 // once. CopyLike has one definition and one argument, thus, there is
846 // nothing else to rewrite.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000847 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
848 return false;
849 // This is the first call to getNextRewritableSource.
850 // Move the CurrentSrcIdx to remember that we made that call.
851 CurrentSrcIdx = 1;
852 // The rewritable source is the argument.
853 const MachineOperand &MOSrc = CopyLike.getOperand(1);
854 SrcReg = MOSrc.getReg();
855 SrcSubReg = MOSrc.getSubReg();
856 // What we track are the alternative sources of the definition.
857 const MachineOperand &MODef = CopyLike.getOperand(0);
858 TrackReg = MODef.getReg();
859 TrackSubReg = MODef.getSubReg();
860 return true;
861 }
862
863 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
864 /// if possible.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000865 /// \return True if the rewriting was possible, false otherwise.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000866 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
867 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
868 return false;
869 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
870 MOSrc.setReg(NewReg);
871 MOSrc.setSubReg(NewSubReg);
872 return true;
873 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000874
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000875 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
876 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
877 /// multiple sources for a given \p Def are found along the way, we found a
878 /// PHI instructions that needs to be rewritten.
879 /// TODO: HandleMultipleSources should be removed once we test PHI handling
880 /// with coalescable copies.
881 TargetInstrInfo::RegSubRegPair
882 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
883 TargetInstrInfo::RegSubRegPair Def,
884 PeepholeOptimizer::RewriteMapTy &RewriteMap,
885 bool HandleMultipleSources = true) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000886 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
887 do {
888 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
889 // If there are no entries on the map, LookupSrc is the new source.
890 if (!Res.isValid())
891 return LookupSrc;
892
893 // There's only one source for this definition, keep searching...
894 unsigned NumSrcs = Res.getNumSources();
895 if (NumSrcs == 1) {
896 LookupSrc.Reg = Res.getSrcReg(0);
897 LookupSrc.SubReg = Res.getSrcSubReg(0);
898 continue;
899 }
900
Matt Arsenault30991562015-09-09 00:38:33 +0000901 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000902 if (!HandleMultipleSources)
903 break;
904
905 // Multiple sources, recurse into each source to find a new source
906 // for it. Then, rewrite the PHI accordingly to its new edges.
907 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
908 for (unsigned i = 0; i < NumSrcs; ++i) {
909 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
910 Res.getSrcSubReg(i));
911 NewPHISrcs.push_back(
912 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
913 }
914
915 // Build the new PHI node and return its def register as the new source.
916 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
917 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
918 DEBUG(dbgs() << "-- getNewSource\n");
919 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
920 DEBUG(dbgs() << " With: " << *NewPHI);
921 const MachineOperand &MODef = NewPHI->getOperand(0);
922 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
923
Eugene Zelenko1804a772016-08-25 00:45:04 +0000924 } while (true);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000925
926 return TargetInstrInfo::RegSubRegPair(0, 0);
927 }
928
929 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
930 /// and create a new COPY instruction. More info about RewriteMap in
931 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
932 /// Uncoalescable copies, since they are copy like instructions that aren't
933 /// recognized by the register allocator.
934 virtual MachineInstr *
935 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
936 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000937 return nullptr;
938 }
939};
940
941/// \brief Helper class to rewrite uncoalescable copy like instructions
942/// into new COPY (coalescable friendly) instructions.
943class UncoalescableRewriter : public CopyRewriter {
944protected:
945 const TargetInstrInfo &TII;
946 MachineRegisterInfo &MRI;
947 /// The number of defs in the bitcast
948 unsigned NumDefs;
949
950public:
951 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
952 MachineRegisterInfo &MRI)
953 : CopyRewriter(MI), TII(TII), MRI(MRI) {
954 NumDefs = MI.getDesc().getNumDefs();
955 }
956
957 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
958 /// All such sources need to be considered rewritable in order to
959 /// rewrite a uncoalescable copy-like instruction. This method return
960 /// each definition that must be checked if rewritable.
961 ///
962 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
963 unsigned &TrackReg,
964 unsigned &TrackSubReg) override {
965 // Find the next non-dead definition and continue from there.
966 if (CurrentSrcIdx == NumDefs)
967 return false;
968
969 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
970 ++CurrentSrcIdx;
971 if (CurrentSrcIdx == NumDefs)
972 return false;
973 }
974
975 // What we track are the alternative sources of the definition.
976 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
977 TrackReg = MODef.getReg();
978 TrackSubReg = MODef.getSubReg();
979
980 CurrentSrcIdx++;
981 return true;
982 }
983
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000984 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
985 /// and create a new COPY instruction. More info about RewriteMap in
986 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
987 /// Uncoalescable copies, since they are copy like instructions that aren't
988 /// recognized by the register allocator.
989 MachineInstr *
990 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
991 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
992 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000993 "We do not rewrite physical registers");
994
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000995 // Find the new source to use in the COPY rewrite.
996 TargetInstrInfo::RegSubRegPair NewSrc =
997 getNewSource(&MRI, &TII, Def, RewriteMap);
998
999 // Insert the COPY.
1000 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001001 unsigned NewVR = MRI.createVirtualRegister(DefRC);
1002
1003 MachineInstr *NewCopy =
1004 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1005 TII.get(TargetOpcode::COPY), NewVR)
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001006 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001007
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001008 NewCopy->getOperand(0).setSubReg(Def.SubReg);
1009 if (Def.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001010 NewCopy->getOperand(0).setIsUndef();
1011
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001012 DEBUG(dbgs() << "-- RewriteSource\n");
1013 DEBUG(dbgs() << " Replacing: " << CopyLike);
1014 DEBUG(dbgs() << " With: " << *NewCopy);
1015 MRI.replaceRegWith(Def.Reg, NewVR);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001016 MRI.clearKillFlags(NewVR);
1017
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001018 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1019 // account for that.
1020 MRI.clearKillFlags(NewSrc.Reg);
1021
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001022 return NewCopy;
1023 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001024};
1025
1026/// \brief Specialized rewriter for INSERT_SUBREG instruction.
1027class InsertSubregRewriter : public CopyRewriter {
1028public:
1029 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1030 assert(MI.isInsertSubreg() && "Invalid instruction");
1031 }
1032
1033 /// \brief See CopyRewriter::getNextRewritableSource.
1034 /// Here CopyLike has the following form:
1035 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
1036 /// Src1 has the same register class has dst, hence, there is
1037 /// nothing to rewrite.
1038 /// Src2.src2SubIdx, may not be register coalescer friendly.
1039 /// Therefore, the first call to this method returns:
1040 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1041 /// (TrackReg, TrackSubReg) = (dst, subIdx).
1042 ///
1043 /// Subsequence calls will return false.
1044 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1045 unsigned &TrackReg,
1046 unsigned &TrackSubReg) override {
1047 // If we already get the only source we can rewrite, return false.
1048 if (CurrentSrcIdx == 2)
1049 return false;
1050 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
1051 CurrentSrcIdx = 2;
1052 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
1053 SrcReg = MOInsertedReg.getReg();
1054 SrcSubReg = MOInsertedReg.getSubReg();
1055 const MachineOperand &MODef = CopyLike.getOperand(0);
1056
1057 // We want to track something that is compatible with the
1058 // partial definition.
1059 TrackReg = MODef.getReg();
1060 if (MODef.getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001061 // Bail if we have to compose sub-register indices.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001062 return false;
1063 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
1064 return true;
1065 }
Eugene Zelenko1804a772016-08-25 00:45:04 +00001066
Quentin Colombet03e43f82014-08-20 17:41:48 +00001067 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1068 if (CurrentSrcIdx != 2)
1069 return false;
1070 // We are rewriting the inserted reg.
1071 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1072 MO.setReg(NewReg);
1073 MO.setSubReg(NewSubReg);
1074 return true;
1075 }
1076};
1077
1078/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1079class ExtractSubregRewriter : public CopyRewriter {
1080 const TargetInstrInfo &TII;
1081
1082public:
1083 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1084 : CopyRewriter(MI), TII(TII) {
1085 assert(MI.isExtractSubreg() && "Invalid instruction");
1086 }
1087
1088 /// \brief See CopyRewriter::getNextRewritableSource.
1089 /// Here CopyLike has the following form:
1090 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1091 /// There is only one rewritable source: Src.subIdx,
1092 /// which defines dst.dstSubIdx.
1093 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1094 unsigned &TrackReg,
1095 unsigned &TrackSubReg) override {
1096 // If we already get the only source we can rewrite, return false.
1097 if (CurrentSrcIdx == 1)
1098 return false;
1099 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1100 CurrentSrcIdx = 1;
1101 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1102 SrcReg = MOExtractedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001103 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001104 if (MOExtractedReg.getSubReg())
1105 return false;
1106
1107 SrcSubReg = CopyLike.getOperand(2).getImm();
1108
1109 // We want to track something that is compatible with the definition.
1110 const MachineOperand &MODef = CopyLike.getOperand(0);
1111 TrackReg = MODef.getReg();
1112 TrackSubReg = MODef.getSubReg();
1113 return true;
1114 }
1115
1116 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1117 // The only source we can rewrite is the input register.
1118 if (CurrentSrcIdx != 1)
1119 return false;
1120
1121 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1122
1123 // If we find a source that does not require to extract something,
1124 // rewrite the operation with a copy.
1125 if (!NewSubReg) {
1126 // Move the current index to an invalid position.
1127 // We do not want another call to this method to be able
1128 // to do any change.
1129 CurrentSrcIdx = -1;
1130 // Rewrite the operation as a COPY.
1131 // Get rid of the sub-register index.
1132 CopyLike.RemoveOperand(2);
1133 // Morph the operation into a COPY.
1134 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1135 return true;
1136 }
1137 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1138 return true;
1139 }
1140};
1141
1142/// \brief Specialized rewriter for REG_SEQUENCE instruction.
1143class RegSequenceRewriter : public CopyRewriter {
1144public:
1145 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1146 assert(MI.isRegSequence() && "Invalid instruction");
1147 }
1148
1149 /// \brief See CopyRewriter::getNextRewritableSource.
1150 /// Here CopyLike has the following form:
1151 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1152 /// Each call will return a different source, walking all the available
1153 /// source.
1154 ///
1155 /// The first call returns:
1156 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1157 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1158 ///
1159 /// The second call returns:
1160 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1161 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1162 ///
1163 /// And so on, until all the sources have been traversed, then
1164 /// it returns false.
1165 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1166 unsigned &TrackReg,
1167 unsigned &TrackSubReg) override {
1168 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1169
1170 // If this is the first call, move to the first argument.
1171 if (CurrentSrcIdx == 0) {
1172 CurrentSrcIdx = 1;
1173 } else {
1174 // Otherwise, move to the next argument and check that it is valid.
1175 CurrentSrcIdx += 2;
1176 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1177 return false;
1178 }
1179 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1180 SrcReg = MOInsertedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001181 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001182 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1183 return false;
1184
1185 // We want to track something that is compatible with the related
1186 // partial definition.
1187 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1188
1189 const MachineOperand &MODef = CopyLike.getOperand(0);
1190 TrackReg = MODef.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001191 // If we have to compose sub-registers, bail.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001192 return MODef.getSubReg() == 0;
1193 }
1194
1195 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1196 // We cannot rewrite out of bound operands.
1197 // Moreover, rewritable sources are at odd positions.
1198 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1199 return false;
1200
1201 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1202 MO.setReg(NewReg);
1203 MO.setSubReg(NewSubReg);
1204 return true;
1205 }
1206};
Eugene Zelenko1804a772016-08-25 00:45:04 +00001207
1208} // end anonymous namespace
Quentin Colombet03e43f82014-08-20 17:41:48 +00001209
1210/// \brief Get the appropriated CopyRewriter for \p MI.
1211/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1212/// if no rewriter works for \p MI.
1213static CopyRewriter *getCopyRewriter(MachineInstr &MI,
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001214 const TargetInstrInfo &TII,
1215 MachineRegisterInfo &MRI) {
1216 // Handle uncoalescable copy-like instructions.
1217 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1218 MI.isExtractSubregLike()))
1219 return new UncoalescableRewriter(MI, TII, MRI);
1220
Quentin Colombet03e43f82014-08-20 17:41:48 +00001221 switch (MI.getOpcode()) {
1222 default:
1223 return nullptr;
1224 case TargetOpcode::COPY:
1225 return new CopyRewriter(MI);
1226 case TargetOpcode::INSERT_SUBREG:
1227 return new InsertSubregRewriter(MI);
1228 case TargetOpcode::EXTRACT_SUBREG:
1229 return new ExtractSubregRewriter(MI, TII);
1230 case TargetOpcode::REG_SEQUENCE:
1231 return new RegSequenceRewriter(MI);
1232 }
1233 llvm_unreachable(nullptr);
1234}
1235
1236/// \brief Optimize generic copy instructions to avoid cross
1237/// register bank copy. The optimization looks through a chain of
1238/// copies and tries to find a source that has a compatible register
1239/// class.
1240/// Two register classes are considered to be compatible if they share
1241/// the same register bank.
1242/// New copies issued by this optimization are register allocator
1243/// friendly. This optimization does not remove any copy as it may
Matt Arsenault30991562015-09-09 00:38:33 +00001244/// overconstrain the register allocator, but replaces some operands
Quentin Colombet03e43f82014-08-20 17:41:48 +00001245/// when possible.
1246/// \pre isCoalescableCopy(*MI) is true.
1247/// \return True, when \p MI has been rewritten. False otherwise.
1248bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1249 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1250 assert(MI->getDesc().getNumDefs() == 1 &&
1251 "Coalescer can understand multiple defs?!");
1252 const MachineOperand &MODef = MI->getOperand(0);
1253 // Do not rewrite physical definitions.
1254 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1255 return false;
1256
1257 bool Changed = false;
1258 // Get the right rewriter for the current copy.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001259 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001260 // If none exists, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001261 if (!CpyRewriter)
1262 return false;
1263 // Rewrite each rewritable source.
1264 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1265 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1266 TrackSubReg)) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001267 // Keep track of PHI nodes and its incoming edges when looking for sources.
1268 RewriteMapTy RewriteMap;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001269 // Try to find a more suitable source. If we failed to do so, or get the
1270 // actual source, move to the next source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001271 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001272 continue;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001273
1274 // Get the new source to rewrite. TODO: Only enable handling of multiple
1275 // sources (PHIs) once we have a motivating example and testcases for it.
1276 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1277 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1278 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1279 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1280 continue;
1281
Quentin Colombet03e43f82014-08-20 17:41:48 +00001282 // Rewrite source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001283 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +00001284 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001285 MRI->clearKillFlags(NewSrc.Reg);
Quentin Colombet6b363372014-08-21 21:34:06 +00001286 Changed = true;
1287 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001288 }
1289 // TODO: We could have a clean-up method to tidy the instruction.
1290 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1291 // => v0 = COPY v1
1292 // Currently we haven't seen motivating example for that and we
1293 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +00001294 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001295 return Changed;
1296}
1297
1298/// \brief Optimize copy-like instructions to create
1299/// register coalescer friendly instruction.
1300/// The optimization tries to kill-off the \p MI by looking
1301/// through a chain of copies to find a source that has a compatible
1302/// register class.
1303/// If such a source is found, it replace \p MI by a generic COPY
1304/// operation.
1305/// \pre isUncoalescableCopy(*MI) is true.
1306/// \return True, when \p MI has been optimized. In that case, \p MI has
1307/// been removed from its parent.
1308/// All COPY instructions created, are inserted in \p LocalMIs.
1309bool PeepholeOptimizer::optimizeUncoalescableCopy(
1310 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1311 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1312
1313 // Check if we can rewrite all the values defined by this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001314 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001315 // Get the right rewriter for the current copy.
1316 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001317 // If none exists, bail out.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001318 if (!CpyRewriter)
1319 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001320
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001321 // Rewrite each rewritable source by generating new COPYs. This works
1322 // differently from optimizeCoalescableCopy since it first makes sure that all
1323 // definitions can be rewritten.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001324 RewriteMapTy RewriteMap;
1325 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1326 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1327 CopyDefSubReg)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001328 // If a physical register is here, this is probably for a good reason.
1329 // Do not rewrite that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001330 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001331 return false;
1332
1333 // If we do not know how to rewrite this definition, there is no point
1334 // in trying to kill this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001335 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1336 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001337 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001338
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001339 RewritePairs.push_back(Def);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001340 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001341
Quentin Colombet03e43f82014-08-20 17:41:48 +00001342 // The change is possible for all defs, do it.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001343 for (const auto &Def : RewritePairs) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001344 // Rewrite the "copy" in a way the register coalescer understands.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001345 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001346 assert(NewCopy && "Should be able to always generate a new copy");
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001347 LocalMIs.insert(NewCopy);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001348 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001349
Quentin Colombet03e43f82014-08-20 17:41:48 +00001350 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +00001351 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001352 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +00001353 return true;
1354}
1355
Sanjay Patel59309cc2015-12-29 18:14:06 +00001356/// Check whether MI is a candidate for folding into a later instruction.
1357/// We only fold loads to virtual registers and the virtual register defined
1358/// has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001359bool PeepholeOptimizer::isLoadFoldable(
Sanjay Patelb120ae92015-12-29 19:34:53 +00001360 MachineInstr *MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +00001361 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1362 return false;
1363 const MCInstrDesc &MCID = MI->getDesc();
1364 if (MCID.getNumDefs() != 1)
1365 return false;
1366
1367 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001368 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001369 // loads. It should be checked when processing uses of the load, since
1370 // uses can be removed during peephole.
1371 if (!MI->getOperand(0).getSubReg() &&
1372 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001373 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001374 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001375 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001376 }
1377 return false;
1378}
1379
Sanjay Patelb120ae92015-12-29 19:34:53 +00001380bool PeepholeOptimizer::isMoveImmediate(
1381 MachineInstr *MI, SmallSet<unsigned, 4> &ImmDefRegs,
1382 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001383 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001384 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001385 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001386 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001387 return false;
1388 unsigned Reg = MI->getOperand(0).getReg();
1389 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1390 ImmDefMIs.insert(std::make_pair(Reg, MI));
1391 ImmDefRegs.insert(Reg);
1392 return true;
1393 }
Andrew Trick9e761992012-02-08 21:22:43 +00001394
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001395 return false;
1396}
1397
Sanjay Patel59309cc2015-12-29 18:14:06 +00001398/// Try folding register operands that are defined by move immediate
1399/// instructions, i.e. a trivial constant folding optimization, if
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001400/// and only if the def and use are in the same BB.
Sanjay Patelb120ae92015-12-29 19:34:53 +00001401bool PeepholeOptimizer::foldImmediate(
1402 MachineInstr *MI, MachineBasicBlock *MBB, SmallSet<unsigned, 4> &ImmDefRegs,
1403 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001404 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1405 MachineOperand &MO = MI->getOperand(i);
1406 if (!MO.isReg() || MO.isDef())
1407 continue;
Dan Gohmandab313e2015-12-10 00:37:51 +00001408 // Ignore dead implicit defs.
1409 if (MO.isImplicit() && MO.isDead())
1410 continue;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001411 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001412 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001413 continue;
1414 if (ImmDefRegs.count(Reg) == 0)
1415 continue;
1416 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
JF Bastien1ac69942015-12-03 23:43:56 +00001417 assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001418 if (TII->FoldImmediate(*MI, *II->second, Reg, MRI)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001419 ++NumImmFold;
1420 return true;
1421 }
1422 }
1423 return false;
1424}
1425
Matt Arsenault10aa8072015-09-25 20:22:12 +00001426// FIXME: This is very simple and misses some cases which should be handled when
1427// motivating examples are found.
1428//
1429// The copy rewriting logic should look at uses as well as defs and be able to
1430// eliminate copies across blocks.
1431//
1432// Later copies that are subregister extracts will also not be eliminated since
1433// only the first copy is considered.
1434//
1435// e.g.
1436// %vreg1 = COPY %vreg0
1437// %vreg2 = COPY %vreg0:sub1
1438//
1439// Should replace %vreg2 uses with %vreg1:sub1
1440bool PeepholeOptimizer::foldRedundantCopy(
Sanjay Patelb120ae92015-12-29 19:34:53 +00001441 MachineInstr *MI, SmallSet<unsigned, 4> &CopySrcRegs,
JF Bastien1ac69942015-12-03 23:43:56 +00001442 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1443 assert(MI->isCopy() && "expected a COPY machine instruction");
Matt Arsenault10aa8072015-09-25 20:22:12 +00001444
1445 unsigned SrcReg = MI->getOperand(1).getReg();
1446 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1447 return false;
1448
1449 unsigned DstReg = MI->getOperand(0).getReg();
1450 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1451 return false;
1452
1453 if (CopySrcRegs.insert(SrcReg).second) {
1454 // First copy of this reg seen.
1455 CopyMIs.insert(std::make_pair(SrcReg, MI));
1456 return false;
1457 }
1458
1459 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1460
1461 unsigned SrcSubReg = MI->getOperand(1).getSubReg();
1462 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1463
1464 // Can't replace different subregister extracts.
1465 if (SrcSubReg != PrevSrcSubReg)
1466 return false;
1467
1468 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1469
1470 // Only replace if the copy register class is the same.
1471 //
1472 // TODO: If we have multiple copies to different register classes, we may want
1473 // to track multiple copies of the same source register.
1474 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1475 return false;
1476
1477 MRI->replaceRegWith(DstReg, PrevDstReg);
1478
1479 // Lifetime of the previous copy has been extended.
1480 MRI->clearKillFlags(PrevDstReg);
1481 return true;
1482}
1483
JF Bastien1ac69942015-12-03 23:43:56 +00001484bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1485 return TargetRegisterInfo::isPhysicalRegister(Reg) &&
1486 !MRI->isAllocatable(Reg);
1487}
1488
1489bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1490 MachineInstr *MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1491 assert(MI->isCopy() && "expected a COPY machine instruction");
1492
1493 if (DisableNAPhysCopyOpt)
1494 return false;
1495
1496 unsigned DstReg = MI->getOperand(0).getReg();
1497 unsigned SrcReg = MI->getOperand(1).getReg();
1498 if (isNAPhysCopy(SrcReg) && TargetRegisterInfo::isVirtualRegister(DstReg)) {
1499 // %vreg = COPY %PHYSREG
1500 // Avoid using a datastructure which can track multiple live non-allocatable
1501 // phys->virt copies since LLVM doesn't seem to do this.
1502 NAPhysToVirtMIs.insert({SrcReg, MI});
1503 return false;
1504 }
1505
1506 if (!(TargetRegisterInfo::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1507 return false;
1508
1509 // %PHYSREG = COPY %vreg
1510 auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1511 if (PrevCopy == NAPhysToVirtMIs.end()) {
1512 // We can't remove the copy: there was an intervening clobber of the
1513 // non-allocatable physical register after the copy to virtual.
1514 DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing " << *MI
1515 << '\n');
1516 return false;
1517 }
1518
1519 unsigned PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1520 if (PrevDstReg == SrcReg) {
1521 // Remove the virt->phys copy: we saw the virtual register definition, and
1522 // the non-allocatable physical register's state hasn't changed since then.
1523 DEBUG(dbgs() << "NAPhysCopy: erasing " << *MI << '\n');
1524 ++NumNAPhysCopies;
1525 return true;
1526 }
1527
1528 // Potential missed optimization opportunity: we saw a different virtual
1529 // register get a copy of the non-allocatable physical register, and we only
1530 // track one such copy. Avoid getting confused by this new non-allocatable
1531 // physical register definition, and remove it from the tracked copies.
1532 DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << *MI << '\n');
1533 NAPhysToVirtMIs.erase(PrevCopy);
1534 return false;
1535}
1536
Taewook Oh0e35ea32017-06-29 23:11:24 +00001537/// \bried Returns true if \p MO is a virtual register operand.
1538static bool isVirtualRegisterOperand(MachineOperand &MO) {
1539 if (!MO.isReg())
1540 return false;
1541 return TargetRegisterInfo::isVirtualRegister(MO.getReg());
1542}
1543
1544bool PeepholeOptimizer::findTargetRecurrence(
1545 unsigned Reg, const SmallSet<unsigned, 2> &TargetRegs,
1546 RecurrenceCycle &RC) {
1547 // Recurrence found if Reg is in TargetRegs.
1548 if (TargetRegs.count(Reg))
1549 return true;
1550
1551 // TODO: Curerntly, we only allow the last instruction of the recurrence
1552 // cycle (the instruction that feeds the PHI instruction) to have more than
1553 // one uses to guarantee that commuting operands does not tie registers
1554 // with overlapping live range. Once we have actual live range info of
1555 // each register, this constraint can be relaxed.
1556 if (!MRI->hasOneNonDBGUse(Reg))
1557 return false;
1558
1559 // Give up if the reccurrence chain length is longer than the limit.
1560 if (RC.size() >= MaxRecurrenceChain)
1561 return false;
1562
1563 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
1564 unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
1565
1566 // Only interested in recurrences whose instructions have only one def, which
1567 // is a virtual register.
1568 if (MI.getDesc().getNumDefs() != 1)
1569 return false;
1570
1571 MachineOperand &DefOp = MI.getOperand(0);
1572 if (!isVirtualRegisterOperand(DefOp))
1573 return false;
1574
1575 // Check if def operand of MI is tied to any use operand. We are only
1576 // interested in the case that all the instructions in the recurrence chain
1577 // have there def operand tied with one of the use operand.
1578 unsigned TiedUseIdx;
1579 if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
1580 return false;
1581
1582 if (Idx == TiedUseIdx) {
1583 RC.push_back(RecurrenceInstr(&MI));
1584 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1585 } else {
1586 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1587 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1588 if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
1589 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1590 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1591 }
1592 }
1593
1594 return false;
1595}
1596
1597/// \brief Phi instructions will eventually be lowered to copy instructions. If
1598/// phi is in a loop header, a recurrence may formulated around the source and
1599/// destination of the phi. For such case commuting operands of the instructions
1600/// in the recurrence may enable coalescing of the copy instruction generated
1601/// from the phi. For example, if there is a recurrence of
1602///
1603/// LoopHeader:
1604/// %vreg1 = phi(%vreg0, %vreg100)
1605/// LoopLatch:
1606/// %vreg0<def, tied1> = ADD %vreg2<def, tied0>, %vreg1
1607///
1608/// , the fact that vreg0 and vreg2 are in the same tied operands set makes
1609/// the coalescing of copy instruction generated from the phi in
1610/// LoopHeader(i.e. %vreg1 = COPY %vreg0) impossible, because %vreg1 and
1611/// %vreg2 have overlapping live range. This introduces additional move
1612/// instruction to the final assembly. However, if we commute %vreg2 and
1613/// %vreg1 of ADD instruction, the redundant move instruction can be
1614/// avoided.
1615bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1616 SmallSet<unsigned, 2> TargetRegs;
1617 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1618 MachineOperand &MO = PHI.getOperand(Idx);
1619 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
1620 TargetRegs.insert(MO.getReg());
1621 }
1622
1623 bool Changed = false;
1624 RecurrenceCycle RC;
1625 if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
1626 // Commutes operands of instructions in RC if necessary so that the copy to
1627 // be generated from PHI can be coalesced.
1628 DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
1629 for (auto &RI : RC) {
1630 DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
1631 auto CP = RI.getCommutePair();
1632 if (CP) {
1633 Changed = true;
1634 TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
1635 (*CP).second);
1636 DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
1637 }
1638 }
1639 }
1640
1641 return Changed;
1642}
1643
Eric Christopher2181fb22014-10-15 21:06:25 +00001644bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001645 if (skipFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001646 return false;
1647
Craig Topper588ceec2012-12-17 03:56:00 +00001648 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001649 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001650
Evan Cheng2ce016c2010-11-15 21:20:45 +00001651 if (DisablePeephole)
1652 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001653
Eric Christopher2181fb22014-10-15 21:06:25 +00001654 TII = MF.getSubtarget().getInstrInfo();
1655 TRI = MF.getSubtarget().getRegisterInfo();
1656 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001657 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Taewook Oh0e35ea32017-06-29 23:11:24 +00001658 MLI = &getAnalysis<MachineLoopInfo>();
Bill Wendlingca678352010-08-09 23:59:04 +00001659
1660 bool Changed = false;
1661
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001662 for (MachineBasicBlock &MBB : MF) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001663 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001664
1665 // During this forward scan, at some point it needs to answer the question
1666 // "given a pointer to an MI in the current BB, is it located before or
1667 // after the current instruction".
1668 // To perform this, the following set keeps track of the MIs already seen
1669 // during the scan, if a MI is not in the set, it is assumed to be located
1670 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001671 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001672 SmallSet<unsigned, 4> ImmDefRegs;
1673 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1674 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001675
JF Bastien1ac69942015-12-03 23:43:56 +00001676 // Track when a non-allocatable physical register is copied to a virtual
1677 // register so that useless moves can be removed.
1678 //
1679 // %PHYSREG is the map index; MI is the last valid `%vreg = COPY %PHYSREG`
1680 // without any intervening re-definition of %PHYSREG.
1681 DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1682
Matt Arsenault10aa8072015-09-25 20:22:12 +00001683 // Set of virtual registers that are copied from.
1684 SmallSet<unsigned, 4> CopySrcRegs;
1685 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1686
Taewook Oh0e35ea32017-06-29 23:11:24 +00001687 bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1688
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001689 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1690 MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001691 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001692 // We may be erasing MI below, increment MII now.
1693 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001694 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001695
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001696 // Skip debug values. They should not affect this peephole optimization.
1697 if (MI->isDebugValue())
1698 continue;
1699
Taewook Oh0e35ea32017-06-29 23:11:24 +00001700 if (MI->isPosition())
Evan Cheng2ce016c2010-11-15 21:20:45 +00001701 continue;
1702
Taewook Oh0e35ea32017-06-29 23:11:24 +00001703 if (IsLoopHeader && MI->isPHI()) {
1704 if (optimizeRecurrence(*MI)) {
1705 Changed = true;
1706 continue;
1707 }
1708 }
1709
JF Bastien1ac69942015-12-03 23:43:56 +00001710 if (!MI->isCopy()) {
1711 for (const auto &Op : MI->operands()) {
1712 // Visit all operands: definitions can be implicit or explicit.
1713 if (Op.isReg()) {
1714 unsigned Reg = Op.getReg();
1715 if (Op.isDef() && isNAPhysCopy(Reg)) {
1716 const auto &Def = NAPhysToVirtMIs.find(Reg);
1717 if (Def != NAPhysToVirtMIs.end()) {
1718 // A new definition of the non-allocatable physical register
1719 // invalidates previous copies.
1720 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1721 << '\n');
1722 NAPhysToVirtMIs.erase(Def);
1723 }
1724 }
1725 } else if (Op.isRegMask()) {
1726 const uint32_t *RegMask = Op.getRegMask();
1727 for (auto &RegMI : NAPhysToVirtMIs) {
1728 unsigned Def = RegMI.first;
1729 if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
1730 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1731 << '\n');
1732 NAPhysToVirtMIs.erase(Def);
1733 }
1734 }
1735 }
1736 }
1737 }
1738
1739 if (MI->isImplicitDef() || MI->isKill())
1740 continue;
1741
1742 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1743 // Blow away all non-allocatable physical registers knowledge since we
1744 // don't know what's correct anymore.
1745 //
1746 // FIXME: handle explicit asm clobbers.
1747 DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to " << *MI
1748 << '\n');
1749 NAPhysToVirtMIs.clear();
JF Bastien1ac69942015-12-03 23:43:56 +00001750 }
1751
Quentin Colombet03e43f82014-08-20 17:41:48 +00001752 if ((isUncoalescableCopy(*MI) &&
1753 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001754 (MI->isCompare() && optimizeCmpInstr(MI, &MBB)) ||
Mehdi Amini22e59742015-01-13 07:07:13 +00001755 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001756 // MI is deleted.
1757 LocalMIs.erase(MI);
1758 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001759 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001760 }
1761
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001762 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1763 Changed = true;
1764 continue;
1765 }
1766
Quentin Colombet03e43f82014-08-20 17:41:48 +00001767 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1768 // MI is just rewritten.
1769 Changed = true;
1770 continue;
1771 }
1772
JF Bastien1ac69942015-12-03 23:43:56 +00001773 if (MI->isCopy() &&
1774 (foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs) ||
1775 foldRedundantNAPhysCopy(MI, NAPhysToVirtMIs))) {
Matt Arsenault10aa8072015-09-25 20:22:12 +00001776 LocalMIs.erase(MI);
1777 MI->eraseFromParent();
1778 Changed = true;
1779 continue;
1780 }
1781
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001782 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001783 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001784 } else {
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001785 Changed |= optimizeExtInstr(MI, &MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001786 // optimizeExtInstr might have created new instructions after MI
1787 // and before the already incremented MII. Adjust MII so that the
1788 // next iteration sees the new instructions.
1789 MII = MI;
1790 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001791 if (SeenMoveImm)
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001792 Changed |= foldImmediate(MI, &MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001793 }
Evan Cheng98196b42011-02-15 05:00:24 +00001794
Manman Ren5759d012012-08-02 00:56:42 +00001795 // Check whether MI is a load candidate for folding into a later
1796 // instruction. If MI is not a candidate, check whether we can fold an
1797 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001798 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1799 !FoldAsLoadDefCandidates.empty()) {
Philip Reames1f1bbac2016-12-13 01:38:41 +00001800
1801 // We visit each operand even after successfully folding a previous
1802 // one. This allows us to fold multiple loads into a single
1803 // instruction. We do assume that optimizeLoadInstr doesn't insert
1804 // foldable uses earlier in the argument list. Since we don't restart
1805 // iteration, we'd miss such cases.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001806 const MCInstrDesc &MIDesc = MI->getDesc();
Philip Reames1f1bbac2016-12-13 01:38:41 +00001807 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
Lang Hames5dc14bd2014-04-02 22:59:58 +00001808 ++i) {
1809 const MachineOperand &MOp = MI->getOperand(i);
1810 if (!MOp.isReg())
1811 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001812 unsigned FoldAsLoadDefReg = MOp.getReg();
1813 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1814 // We need to fold load after optimizeCmpInstr, since
1815 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1816 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1817 // we need it for markUsesInDebugValueAsUndef().
1818 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001819 MachineInstr *DefMI = nullptr;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001820 if (MachineInstr *FoldMI =
1821 TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001822 // Update LocalMIs since we replaced MI with FoldMI and deleted
1823 // DefMI.
1824 DEBUG(dbgs() << "Replacing: " << *MI);
1825 DEBUG(dbgs() << " With: " << *FoldMI);
1826 LocalMIs.erase(MI);
1827 LocalMIs.erase(DefMI);
1828 LocalMIs.insert(FoldMI);
1829 MI->eraseFromParent();
1830 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001831 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1832 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001833 ++NumLoadFold;
Taewook Oh0e35ea32017-06-29 23:11:24 +00001834
Philip Reames1f1bbac2016-12-13 01:38:41 +00001835 // MI is replaced with FoldMI so we can continue trying to fold
Lang Hames5dc14bd2014-04-02 22:59:58 +00001836 Changed = true;
Philip Reames1f1bbac2016-12-13 01:38:41 +00001837 MI = FoldMI;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001838 }
1839 }
Manman Ren5759d012012-08-02 00:56:42 +00001840 }
1841 }
Taewook Oh0e35ea32017-06-29 23:11:24 +00001842
Philip Reames1f1bbac2016-12-13 01:38:41 +00001843 // If we run into an instruction we can't fold across, discard
1844 // the load candidates. Note: We might be able to fold *into* this
1845 // instruction, so this needs to be after the folding logic.
1846 if (MI->isLoadFoldBarrier()) {
1847 DEBUG(dbgs() << "Encountered load fold barrier on " << *MI << "\n");
1848 FoldAsLoadDefCandidates.clear();
1849 }
1850
Bill Wendlingca678352010-08-09 23:59:04 +00001851 }
1852 }
1853
1854 return Changed;
1855}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001856
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001857ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001858 assert(Def->isCopy() && "Invalid definition");
1859 // Copy instruction are supposed to be: Def = Src.
1860 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001861 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001862
1863 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1864 // If we look for a different subreg, it means we want a subreg of src.
Matt Arsenault30991562015-09-09 00:38:33 +00001865 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001866 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001867 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001868 const MachineOperand &Src = Def->getOperand(1);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001869 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001870}
1871
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001872ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001873 assert(Def->isBitcast() && "Invalid definition");
1874
1875 // Bail if there are effects that a plain copy will not expose.
1876 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001877 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001878
1879 // Bitcasts with more than one def are not supported.
1880 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001881 return ValueTrackerResult();
Matthias Braunba7d95d2017-01-09 21:38:17 +00001882 const MachineOperand DefOp = Def->getOperand(DefIdx);
1883 if (DefOp.getSubReg() != DefSubReg)
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001884 // If we look for a different subreg, it means we want a subreg of the src.
Matt Arsenault30991562015-09-09 00:38:33 +00001885 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001886 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001887
Quentin Colombet03e43f82014-08-20 17:41:48 +00001888 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001889 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1890 ++OpIdx) {
1891 const MachineOperand &MO = Def->getOperand(OpIdx);
1892 if (!MO.isReg() || !MO.getReg())
1893 continue;
Dan Gohmandab313e2015-12-10 00:37:51 +00001894 // Ignore dead implicit defs.
1895 if (MO.isImplicit() && MO.isDead())
1896 continue;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001897 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1898 if (SrcIdx != EndOpIdx)
1899 // Multiple sources?
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001900 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001901 SrcIdx = OpIdx;
1902 }
Matthias Braunba7d95d2017-01-09 21:38:17 +00001903
1904 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
1905 // will break the assumed guarantees for the upper bits.
1906 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
1907 if (UseMI.isSubregToReg())
1908 return ValueTrackerResult();
1909 }
1910
Quentin Colombet03e43f82014-08-20 17:41:48 +00001911 const MachineOperand &Src = Def->getOperand(SrcIdx);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001912 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001913}
1914
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001915ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001916 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1917 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001918
1919 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001920 // If we are composing subregs, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001921 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1922 // This should almost never happen as the SSA property is tracked at
1923 // the register level (as opposed to the subreg level).
1924 // I.e.,
1925 // Def.sub0 =
1926 // Def.sub1 =
1927 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1928 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001929 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001930 // Def.sub0 (i.e, not defining the other subregs) and we would
1931 // have this case.
1932 // If we can ascertain (or force) that this never happens, we could
1933 // turn that into an assertion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001934 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001935
Quentin Colombet03e43f82014-08-20 17:41:48 +00001936 if (!TII)
1937 // We could handle the REG_SEQUENCE here, but we do not want to
1938 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001939 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001940
1941 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1942 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001943 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001944
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001945 // We are looking at:
1946 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1947 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001948 for (auto &RegSeqInput : RegSeqInputRegs) {
1949 if (RegSeqInput.SubIdx == DefSubReg) {
1950 if (RegSeqInput.SubReg)
Matt Arsenault30991562015-09-09 00:38:33 +00001951 // Bail if we have to compose sub registers.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001952 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001953
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001954 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001955 }
1956 }
1957
1958 // If the subreg we are tracking is super-defined by another subreg,
1959 // we could follow this value. However, this would require to compose
1960 // the subreg and we do not do that for now.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001961 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001962}
1963
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001964ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
Quentin Colombet68962302014-08-21 00:19:16 +00001965 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1966 "Invalid definition");
1967
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001968 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001969 // If we are composing subreg, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001970 // Same remark as getNextSourceFromRegSequence.
1971 // I.e., this may be turned into an assert.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001972 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001973
Quentin Colombet68962302014-08-21 00:19:16 +00001974 if (!TII)
1975 // We could handle the REG_SEQUENCE here, but we do not want to
1976 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001977 return ValueTrackerResult();
Quentin Colombet68962302014-08-21 00:19:16 +00001978
Quentin Colombet03e43f82014-08-20 17:41:48 +00001979 TargetInstrInfo::RegSubRegPair BaseReg;
1980 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001981 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001982 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001983
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001984 // We are looking at:
1985 // Def = INSERT_SUBREG v0, v1, sub1
1986 // There are two cases:
1987 // 1. DefSubReg == sub1, get v1.
1988 // 2. DefSubReg != sub1, the value may be available through v0.
1989
Quentin Colombet03e43f82014-08-20 17:41:48 +00001990 // #1 Check if the inserted register matches the required sub index.
1991 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001992 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001993 }
1994 // #2 Otherwise, if the sub register we are looking for is not partial
1995 // defined by the inserted element, we can look through the main
1996 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001997 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001998 // If the result register (Def) and the base register (v0) do not
1999 // have the same register class or if we have to compose
Matt Arsenault30991562015-09-09 00:38:33 +00002000 // subregisters, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00002001 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
2002 BaseReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002003 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002004
Quentin Colombet03e43f82014-08-20 17:41:48 +00002005 // Get the TRI and check if the inserted sub-register overlaps with the
2006 // sub-register we are tracking.
2007 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002008 if (!TRI ||
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00002009 !(TRI->getSubRegIndexLaneMask(DefSubReg) &
2010 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002011 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002012 // At this point, the value is available in v0 via the same subreg
2013 // we used for Def.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002014 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002015}
2016
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002017ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
Quentin Colombet67639df2014-08-20 23:13:02 +00002018 assert((Def->isExtractSubreg() ||
2019 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002020 // We are looking at:
2021 // Def = EXTRACT_SUBREG v0, sub0
2022
Matt Arsenault30991562015-09-09 00:38:33 +00002023 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002024 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
2025 if (DefSubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002026 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002027
Quentin Colombet67639df2014-08-20 23:13:02 +00002028 if (!TII)
2029 // We could handle the EXTRACT_SUBREG here, but we do not want to
2030 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002031 return ValueTrackerResult();
Quentin Colombet67639df2014-08-20 23:13:02 +00002032
Quentin Colombet03e43f82014-08-20 17:41:48 +00002033 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00002034 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002035 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00002036
Matt Arsenault30991562015-09-09 00:38:33 +00002037 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002038 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00002039 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002040 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002041 // Otherwise, the value is available in the v0.sub0.
Sanjay Patelb120ae92015-12-29 19:34:53 +00002042 return ValueTrackerResult(ExtractSubregInputReg.Reg,
2043 ExtractSubregInputReg.SubIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002044}
2045
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002046ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002047 assert(Def->isSubregToReg() && "Invalid definition");
2048 // We are looking at:
2049 // Def = SUBREG_TO_REG Imm, v0, sub0
2050
Matt Arsenault30991562015-09-09 00:38:33 +00002051 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002052 // If DefSubReg != sub0, we would have to check that all the bits
2053 // we track are included in sub0 and if yes, we would have to
2054 // determine the right subreg in v0.
2055 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002056 return ValueTrackerResult();
Matt Arsenault30991562015-09-09 00:38:33 +00002057 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002058 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2059 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002060 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002061
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002062 return ValueTrackerResult(Def->getOperand(2).getReg(),
2063 Def->getOperand(3).getImm());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002064}
2065
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00002066/// \brief Explore each PHI incoming operand and return its sources
2067ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2068 assert(Def->isPHI() && "Invalid definition");
2069 ValueTrackerResult Res;
2070
Matt Arsenault30991562015-09-09 00:38:33 +00002071 // If we look for a different subreg, bail as we do not support composing
2072 // subregs yet.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00002073 if (Def->getOperand(0).getSubReg() != DefSubReg)
2074 return ValueTrackerResult();
2075
2076 // Return all register sources for PHI instructions.
2077 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2078 auto &MO = Def->getOperand(i);
2079 assert(MO.isReg() && "Invalid PHI instruction");
2080 Res.addSource(MO.getReg(), MO.getSubReg());
2081 }
2082
2083 return Res;
2084}
2085
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002086ValueTrackerResult ValueTracker::getNextSourceImpl() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002087 assert(Def && "This method needs a valid definition");
2088
Eric Liue617ade2016-07-04 12:10:08 +00002089 assert(((Def->getOperand(DefIdx).isDef() &&
2090 (DefIdx < Def->getDesc().getNumDefs() ||
2091 Def->getDesc().isVariadic())) ||
2092 Def->getOperand(DefIdx).isImplicit()) &&
2093 "Invalid DefIdx");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002094 if (Def->isCopy())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002095 return getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002096 if (Def->isBitcast())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002097 return getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002098 // All the remaining cases involve "complex" instructions.
Matt Arsenault30991562015-09-09 00:38:33 +00002099 // Bail if we did not ask for the advanced tracking.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002100 if (!UseAdvancedTracking)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002101 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00002102 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002103 return getNextSourceFromRegSequence();
Quentin Colombet68962302014-08-21 00:19:16 +00002104 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002105 return getNextSourceFromInsertSubreg();
Quentin Colombet67639df2014-08-20 23:13:02 +00002106 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002107 return getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002108 if (Def->isSubregToReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002109 return getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00002110 if (Def->isPHI())
2111 return getNextSourceFromPHI();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002112 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002113}
2114
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002115ValueTrackerResult ValueTracker::getNextSource() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002116 // If we reach a point where we cannot move up in the use-def chain,
2117 // there is nothing we can get.
2118 if (!Def)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002119 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002120
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002121 ValueTrackerResult Res = getNextSourceImpl();
2122 if (Res.isValid()) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002123 // Update definition, definition index, and subregister for the
2124 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002125 // Update the current register.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002126 bool OneRegSrc = Res.getNumSources() == 1;
2127 if (OneRegSrc)
2128 Reg = Res.getSrcReg(0);
2129 // Update the result before moving up in the use-def chain
2130 // with the instruction containing the last found sources.
2131 Res.setInst(Def);
2132
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002133 // If we can still move up in the use-def chain, move to the next
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002134 // definition.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002135 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00002136 Def = MRI.getVRegDef(Reg);
2137 DefIdx = MRI.def_begin(Reg).getOperandNo();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002138 DefSubReg = Res.getSrcSubReg(0);
2139 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002140 }
2141 }
2142 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002143 // for the next iteration. Make sure any new call to getNextSource bails out
2144 // early by cutting the use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002145 Def = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002146 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002147}