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