LLVM 24.0.0git
PeepholeOptimizer.cpp
Go to the documentation of this file.
1//===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Perform peephole optimizations on the machine code:
10//
11// - Optimize Extensions
12//
13// Optimization of sign / zero extension instructions. It may be extended to
14// handle other instructions with similar properties.
15//
16// On some targets, some instructions, e.g. X86 sign / zero extension, may
17// leave the source value in the lower part of the result. This optimization
18// will replace some uses of the pre-extension value with uses of the
19// sub-register of the results.
20//
21// - Optimize Comparisons
22//
23// Optimization of comparison instructions. For instance, in this code:
24//
25// sub r1, 1
26// cmp r1, 0
27// bz L1
28//
29// If the "sub" instruction all ready sets (or could be modified to set) the
30// same flag that the "cmp" instruction sets and that "bz" uses, then we can
31// eliminate the "cmp" instruction.
32//
33// Another instance, in this code:
34//
35// sub r1, r3 | sub r1, imm
36// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
37// bge L1
38//
39// If the branch instruction can use flag from "sub", then we can replace
40// "sub" with "subs" and eliminate the "cmp" instruction.
41//
42// - Optimize Loads:
43//
44// Loads that can be folded into a later instruction. A load is foldable
45// if it loads to virtual registers and the virtual register defined has
46// a single use.
47//
48// - Optimize Copies and Bitcast (more generally, target specific copies):
49//
50// Rewrite copies and bitcasts to avoid cross register bank copies
51// when possible.
52// E.g., Consider the following example, where capital and lower
53// letters denote different register file:
54// b = copy A <-- cross-bank copy
55// C = copy b <-- cross-bank copy
56// =>
57// b = copy A <-- cross-bank copy
58// C = copy A <-- same-bank copy
59//
60// E.g., for bitcast:
61// b = bitcast A <-- cross-bank copy
62// C = bitcast b <-- cross-bank copy
63// =>
64// b = bitcast A <-- cross-bank copy
65// C = copy A <-- same-bank copy
66//===----------------------------------------------------------------------===//
67
69#include "llvm/ADT/DenseMap.h"
71#include "llvm/ADT/SmallSet.h"
73#include "llvm/ADT/Statistic.h"
89#include "llvm/MC/LaneBitmask.h"
90#include "llvm/MC/MCInstrDesc.h"
91#include "llvm/Pass.h"
93#include "llvm/Support/Debug.h"
95#include <cassert>
96#include <cstdint>
97#include <utility>
98
99using namespace llvm;
102
103#define DEBUG_TYPE "peephole-opt"
104
105// Optimize Extensions
106static cl::opt<bool> Aggressive("aggressive-ext-opt", cl::Hidden,
107 cl::desc("Aggressive extension optimization"));
108
109static cl::opt<bool>
110 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
111 cl::desc("Disable the peephole optimizer"));
112
113/// Specifiy whether or not the value tracking looks through
114/// complex instructions. When this is true, the value tracker
115/// bails on everything that is not a copy or a bitcast.
116static cl::opt<bool>
117 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
118 cl::desc("Disable advanced copy optimization"));
119
121 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
122 cl::desc("Disable non-allocatable physical register copy optimization"));
123
124// Limit the number of PHI instructions to process
125// in PeepholeOptimizer::getNextSource.
127 RewritePHILimit("rewrite-phi-limit", cl::Hidden, cl::init(10),
128 cl::desc("Limit the length of PHI chains to lookup"));
129
130// Limit the length of recurrence chain when evaluating the benefit of
131// commuting operands.
133 "recurrence-chain-limit", cl::Hidden, cl::init(3),
134 cl::desc("Maximum length of recurrence chain when evaluating the benefit "
135 "of commuting operands"));
136
137STATISTIC(NumReuse, "Number of extension results reused");
138STATISTIC(NumCmps, "Number of compares eliminated");
139STATISTIC(NumImmFold, "Number of move immediate folded");
140STATISTIC(NumLoadFold, "Number of loads folded");
141STATISTIC(NumSelects, "Number of selects optimized");
142STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
143STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
144STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
145
146namespace {
147
148class ValueTrackerResult;
149class RecurrenceInstr;
150
151/// Interface to query instructions amenable to copy rewriting.
152class Rewriter {
153protected:
154 MachineInstr &CopyLike;
155 int CurrentSrcIdx = 0; ///< The index of the source being rewritten.
156public:
157 Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
158 virtual ~Rewriter() = default;
159
160 /// Get the next rewritable source (SrcReg, SrcSubReg) and
161 /// the related value that it affects (DstReg, DstSubReg).
162 /// A source is considered rewritable if its register class and the
163 /// register class of the related DstReg may not be register
164 /// coalescer friendly. In other words, given a copy-like instruction
165 /// not all the arguments may be returned at rewritable source, since
166 /// some arguments are none to be register coalescer friendly.
167 ///
168 /// Each call of this method moves the current source to the next
169 /// rewritable source.
170 /// For instance, let CopyLike be the instruction to rewrite.
171 /// CopyLike has one definition and one source:
172 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
173 ///
174 /// The first call will give the first rewritable source, i.e.,
175 /// the only source this instruction has:
176 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
177 /// This source defines the whole definition, i.e.,
178 /// (DstReg, DstSubReg) = (dst, dstSubIdx).
179 ///
180 /// The second and subsequent calls will return false, as there is only one
181 /// rewritable source.
182 ///
183 /// \return True if a rewritable source has been found, false otherwise.
184 /// The output arguments are valid if and only if true is returned.
185 virtual bool getNextRewritableSource(RegSubRegPair &Src,
186 RegSubRegPair &Dst) = 0;
187
188 /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
189 /// \return True if the rewriting was possible, false otherwise.
190 virtual bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) = 0;
191};
192
193/// Rewriter for COPY instructions.
194class CopyRewriter : public Rewriter {
195public:
196 CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
197 assert(MI.isCopy() && "Expected copy instruction");
198 }
199 ~CopyRewriter() override = default;
200
201 bool getNextRewritableSource(RegSubRegPair &Src,
202 RegSubRegPair &Dst) override {
203 if (++CurrentSrcIdx > 1)
204 return false;
205
206 // The rewritable source is the argument.
207 const MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
208 Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
209 // What we track are the alternative sources of the definition.
210 const MachineOperand &MODef = CopyLike.getOperand(0);
211 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
212 return true;
213 }
214
215 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
216 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
217 MOSrc.setReg(NewReg);
218 MOSrc.setSubReg(NewSubReg);
219 return true;
220 }
221};
222
223/// Helper class to rewrite uncoalescable copy like instructions
224/// into new COPY (coalescable friendly) instructions.
225class UncoalescableRewriter : public Rewriter {
226 int NumDefs; ///< Number of defs in the bitcast.
227
228public:
229 UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
230 NumDefs = MI.getDesc().getNumDefs();
231 }
232
233 /// \see See Rewriter::getNextRewritableSource()
234 /// All such sources need to be considered rewritable in order to
235 /// rewrite a uncoalescable copy-like instruction. This method return
236 /// each definition that must be checked if rewritable.
237 bool getNextRewritableSource(RegSubRegPair &Src,
238 RegSubRegPair &Dst) override {
239 // Find the next non-dead definition and continue from there.
240 if (CurrentSrcIdx == NumDefs)
241 return false;
242
243 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
244 ++CurrentSrcIdx;
245 if (CurrentSrcIdx == NumDefs)
246 return false;
247 }
248
249 // What we track are the alternative sources of the definition.
250 Src = RegSubRegPair(0, 0);
251 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
252 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
253
254 CurrentSrcIdx++;
255 return true;
256 }
257
258 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
259 return false;
260 }
261};
262
263/// Specialized rewriter for INSERT_SUBREG instruction.
264class InsertSubregRewriter : public Rewriter {
265public:
266 InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
267 assert(MI.isInsertSubreg() && "Invalid instruction");
268 }
269
270 /// \see See Rewriter::getNextRewritableSource()
271 /// Here CopyLike has the following form:
272 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
273 /// Src1 has the same register class has dst, hence, there is
274 /// nothing to rewrite.
275 /// Src2.src2SubIdx, may not be register coalescer friendly.
276 /// Therefore, the first call to this method returns:
277 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
278 /// (DstReg, DstSubReg) = (dst, subIdx).
279 ///
280 /// Subsequence calls will return false.
281 bool getNextRewritableSource(RegSubRegPair &Src,
282 RegSubRegPair &Dst) override {
283 // If we already get the only source we can rewrite, return false.
284 if (CurrentSrcIdx == 2)
285 return false;
286 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
287 CurrentSrcIdx = 2;
288 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
289 Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
290 const MachineOperand &MODef = CopyLike.getOperand(0);
291
292 // We want to track something that is compatible with the
293 // partial definition.
294 if (MODef.getSubReg())
295 // Bail if we have to compose sub-register indices.
296 return false;
297 Dst = RegSubRegPair(MODef.getReg(),
298 (unsigned)CopyLike.getOperand(3).getImm());
299 return true;
300 }
301
302 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
303 if (CurrentSrcIdx != 2)
304 return false;
305 // We are rewriting the inserted reg.
306 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
307 MO.setReg(NewReg);
308 MO.setSubReg(NewSubReg);
309 return true;
310 }
311};
312
313/// Specialized rewriter for EXTRACT_SUBREG instruction.
314class ExtractSubregRewriter : public Rewriter {
315 const TargetInstrInfo &TII;
316
317public:
318 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
319 : Rewriter(MI), TII(TII) {
320 assert(MI.isExtractSubreg() && "Invalid instruction");
321 }
322
323 /// \see Rewriter::getNextRewritableSource()
324 /// Here CopyLike has the following form:
325 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
326 /// There is only one rewritable source: Src.subIdx,
327 /// which defines dst.dstSubIdx.
328 bool getNextRewritableSource(RegSubRegPair &Src,
329 RegSubRegPair &Dst) override {
330 // If we already get the only source we can rewrite, return false.
331 if (CurrentSrcIdx == 1)
332 return false;
333 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
334 CurrentSrcIdx = 1;
335 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
336 // If we have to compose sub-register indices, bail out.
337 if (MOExtractedReg.getSubReg())
338 return false;
339
340 Src =
341 RegSubRegPair(MOExtractedReg.getReg(), CopyLike.getOperand(2).getImm());
342
343 // We want to track something that is compatible with the definition.
344 const MachineOperand &MODef = CopyLike.getOperand(0);
345 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
346 return true;
347 }
348
349 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
350 // The only source we can rewrite is the input register.
351 if (CurrentSrcIdx != 1)
352 return false;
353
354 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
355
356 // If we find a source that does not require to extract something,
357 // rewrite the operation with a copy.
358 if (!NewSubReg) {
359 // Move the current index to an invalid position.
360 // We do not want another call to this method to be able
361 // to do any change.
362 CurrentSrcIdx = -1;
363 // Rewrite the operation as a COPY.
364 // Get rid of the sub-register index.
365 CopyLike.removeOperand(2);
366 // Morph the operation into a COPY.
367 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
368 return true;
369 }
370 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
371 return true;
372 }
373};
374
375/// Specialized rewriter for REG_SEQUENCE instruction.
376class RegSequenceRewriter : public Rewriter {
377public:
378 RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
379 assert(MI.isRegSequence() && "Invalid instruction");
380 CurrentSrcIdx = -1;
381 }
382
383 /// \see Rewriter::getNextRewritableSource()
384 /// Here CopyLike has the following form:
385 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
386 /// Each call will return a different source, walking all the available
387 /// source.
388 ///
389 /// The first call returns:
390 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
391 /// (DstReg, DstSubReg) = (dst, subIdx1).
392 ///
393 /// The second call returns:
394 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
395 /// (DstReg, DstSubReg) = (dst, subIdx2).
396 ///
397 /// And so on, until all the sources have been traversed, then
398 /// it returns false.
399 bool getNextRewritableSource(RegSubRegPair &Src,
400 RegSubRegPair &Dst) override {
401 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
402 CurrentSrcIdx += 2;
403 if (static_cast<unsigned>(CurrentSrcIdx) >= CopyLike.getNumOperands())
404 return false;
405
406 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
407 Src.Reg = MOInsertedReg.getReg();
408 Src.SubReg = MOInsertedReg.getSubReg();
409
410 // We want to track something that is compatible with the related
411 // partial definition.
412 Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
413
414 const MachineOperand &MODef = CopyLike.getOperand(0);
415 Dst.Reg = MODef.getReg();
416 assert(MODef.getSubReg() == 0 && "cannot have subregister def in SSA");
417 return true;
418 }
419
420 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
421 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
422 MO.setReg(NewReg);
423 MO.setSubReg(NewSubReg);
424 return true;
425 }
426};
427
428class PeepholeOptimizer : private MachineFunction::Delegate {
429 const TargetInstrInfo *TII = nullptr;
430 const TargetRegisterInfo *TRI = nullptr;
431 MachineRegisterInfo *MRI = nullptr;
432 MachineDominatorTree *DT = nullptr; // Machine dominator tree
433 MachineLoopInfo *MLI = nullptr;
434
435public:
436 PeepholeOptimizer(MachineDominatorTree *DT, MachineLoopInfo *MLI)
437 : DT(DT), MLI(MLI) {}
438
439 bool run(MachineFunction &MF);
440 /// Track Def -> Use info used for rewriting copies.
441 using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
442
443 /// Sequence of instructions that formulate recurrence cycle.
444 using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
445
446private:
447 bool optimizeCmpInstr(MachineInstr &MI, MachineFunction &MF,
448 SmallPtrSet<MachineInstr *, 16> &LocalMIs);
449 bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
450 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
451 bool optimizeSelect(MachineInstr &MI,
452 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
453 bool optimizeCondBranch(MachineInstr &MI);
454
455 bool optimizeCoalescableCopyImpl(Rewriter &&CpyRewriter);
456 bool optimizeCoalescableCopy(MachineInstr &MI);
457 bool optimizeUncoalescableCopy(MachineInstr &MI,
458 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
459 bool optimizeRecurrence(MachineInstr &PHI);
460 bool findNextSource(const TargetRegisterClass *DefRC, unsigned DefSubReg,
461 RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
462 bool isMoveImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
463 DenseMap<Register, MachineInstr *> &ImmDefMIs);
464 bool foldImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
465 DenseMap<Register, MachineInstr *> &ImmDefMIs,
466 bool &Deleted);
467
468 /// Finds recurrence cycles, but only ones that formulated around
469 /// a def operand and a use operand that are tied. If there is a use
470 /// operand commutable with the tied use operand, find recurrence cycle
471 /// along that operand as well.
472 bool findTargetRecurrence(Register Reg,
473 const SmallSet<Register, 2> &TargetReg,
474 RecurrenceCycle &RC);
475
476 /// If copy instruction \p MI is a virtual register copy or a copy of a
477 /// constant physical register to a virtual register, track it in the
478 /// set CopySrcMIs. If this virtual register was previously seen as a
479 /// copy, replace the uses of this copy with the previously seen copy's
480 /// destination register.
481 bool foldRedundantCopy(MachineInstr &MI);
482
483 /// Is the register \p Reg a non-allocatable physical register?
484 bool isNAPhysCopy(Register Reg);
485
486 /// If copy instruction \p MI is a non-allocatable virtual<->physical
487 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
488 /// non-allocatable physical register was previously copied to a virtual
489 /// registered and hasn't been clobbered, the virt->phys copy can be
490 /// deleted.
491 bool
492 foldRedundantNAPhysCopy(MachineInstr &MI,
493 DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs);
494
495 bool isLoadFoldable(MachineInstr &MI,
496 SmallSet<Register, 16> &FoldAsLoadDefCandidates);
497
498 /// Try to fold the load defined by \p FoldReg into \p MI using
499 /// TII->optimizeLoadInstr. On success, updates \p LocalMIs, erases the old
500 /// instructions, and returns the replacement; returns nullptr otherwise.
501 MachineInstr *foldLoadInto(MachineFunction &MF, MachineInstr &MI,
502 Register FoldReg,
503 SmallPtrSet<MachineInstr *, 16> &LocalMIs);
504
505 /// Check whether \p MI is understood by the register coalescer
506 /// but may require some rewriting.
507 static bool isCoalescableCopy(const MachineInstr &MI) {
508 // SubregToRegs are not interesting, because they are already register
509 // coalescer friendly.
510 return MI.isCopy() ||
511 (!DisableAdvCopyOpt && (MI.isRegSequence() || MI.isInsertSubreg() ||
512 MI.isExtractSubreg()));
513 }
514
515 /// Check whether \p MI is a copy like instruction that is
516 /// not recognized by the register coalescer.
517 static bool isUncoalescableCopy(const MachineInstr &MI) {
518 return MI.isBitcast() || (!DisableAdvCopyOpt && (MI.isRegSequenceLike() ||
519 MI.isInsertSubregLike() ||
520 MI.isExtractSubregLike()));
521 }
522
523 MachineInstr &rewriteSource(MachineInstr &CopyLike, RegSubRegPair Def,
524 RewriteMapTy &RewriteMap);
525
526 // Set of copies to virtual registers keyed by source register. Never
527 // holds any physreg which requires def tracking.
528 DenseMap<RegSubRegPair, MachineInstr *> CopySrcMIs;
529
530 // MachineFunction::Delegate implementation. Used to maintain CopySrcMIs.
531 void MF_HandleInsertion(MachineInstr &MI) override {}
532
533 bool getCopySrc(MachineInstr &MI, RegSubRegPair &SrcPair) {
534 if (!MI.isCopy())
535 return false;
536
537 Register SrcReg = MI.getOperand(1).getReg();
538 unsigned SrcSubReg = MI.getOperand(1).getSubReg();
539 if (!SrcReg.isVirtual() && !MRI->isConstantPhysReg(SrcReg))
540 return false;
541
542 SrcPair = RegSubRegPair(SrcReg, SrcSubReg);
543 return true;
544 }
545
546 // If a COPY instruction is to be deleted or changed, we should also remove
547 // it from CopySrcMIs.
548 void deleteChangedCopy(MachineInstr &MI) {
549 RegSubRegPair SrcPair;
550 if (!getCopySrc(MI, SrcPair))
551 return;
552
553 auto It = CopySrcMIs.find(SrcPair);
554 if (It != CopySrcMIs.end() && It->second == &MI)
555 CopySrcMIs.erase(It);
556 }
557
558 void MF_HandleRemoval(MachineInstr &MI) override { deleteChangedCopy(MI); }
559
560 void MF_HandleChangeDesc(MachineInstr &MI, const MCInstrDesc &TID) override {
561 deleteChangedCopy(MI);
562 }
563};
564
565class PeepholeOptimizerLegacy : public MachineFunctionPass {
566public:
567 static char ID; // Pass identification
568
569 PeepholeOptimizerLegacy() : MachineFunctionPass(ID) {}
570
571 bool runOnMachineFunction(MachineFunction &MF) override;
572
573 void getAnalysisUsage(AnalysisUsage &AU) const override {
574 AU.setPreservesCFG();
576 AU.addRequired<MachineLoopInfoWrapperPass>();
577 if (Aggressive) {
578 AU.addRequired<MachineDominatorTreeWrapperPass>();
579 }
580 }
581
582 MachineFunctionProperties getRequiredProperties() const override {
583 return MachineFunctionProperties().setIsSSA();
584 }
585};
586
587/// Helper class to hold instructions that are inside recurrence cycles.
588/// The recurrence cycle is formulated around 1) a def operand and its
589/// tied use operand, or 2) a def operand and a use operand that is commutable
590/// with another use operand which is tied to the def operand. In the latter
591/// case, index of the tied use operand and the commutable use operand are
592/// maintained with CommutePair.
593class RecurrenceInstr {
594public:
595 using IndexPair = std::pair<unsigned, unsigned>;
596
597 RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
598 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
599 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
600
601 MachineInstr *getMI() const { return MI; }
602 std::optional<IndexPair> getCommutePair() const { return CommutePair; }
603
604private:
605 MachineInstr *MI;
606 std::optional<IndexPair> CommutePair;
607};
608
609/// Helper class to hold a reply for ValueTracker queries.
610/// Contains the returned sources for a given search and the instructions
611/// where the sources were tracked from.
612class ValueTrackerResult {
613private:
614 /// Track all sources found by one ValueTracker query.
616
617 /// Instruction using the sources in 'RegSrcs'.
618 const MachineInstr *Inst = nullptr;
619
620public:
621 ValueTrackerResult() = default;
622
623 ValueTrackerResult(Register Reg, unsigned SubReg) { addSource(Reg, SubReg); }
624
625 bool isValid() const { return getNumSources() > 0; }
626
627 void setInst(const MachineInstr *I) { Inst = I; }
628 const MachineInstr *getInst() const { return Inst; }
629
630 void clear() {
631 RegSrcs.clear();
632 Inst = nullptr;
633 }
634
635 void addSource(Register SrcReg, unsigned SrcSubReg) {
636 RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
637 }
638
639 void setSource(int Idx, Register SrcReg, unsigned SrcSubReg) {
640 assert(Idx < getNumSources() && "Reg pair source out of index");
641 RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
642 }
643
644 int getNumSources() const { return RegSrcs.size(); }
645
646 RegSubRegPair getSrc(int Idx) const { return RegSrcs[Idx]; }
647
648 Register getSrcReg(int Idx) const {
649 assert(Idx < getNumSources() && "Reg source out of index");
650 return RegSrcs[Idx].Reg;
651 }
652
653 unsigned getSrcSubReg(int Idx) const {
654 assert(Idx < getNumSources() && "SubReg source out of index");
655 return RegSrcs[Idx].SubReg;
656 }
657
658 bool operator==(const ValueTrackerResult &Other) const {
659 if (Other.getInst() != getInst())
660 return false;
661
662 if (Other.getNumSources() != getNumSources())
663 return false;
664
665 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
666 if (Other.getSrcReg(i) != getSrcReg(i) ||
667 Other.getSrcSubReg(i) != getSrcSubReg(i))
668 return false;
669 return true;
670 }
671};
672
673/// Helper class to track the possible sources of a value defined by
674/// a (chain of) copy related instructions.
675/// Given a definition (instruction and definition index), this class
676/// follows the use-def chain to find successive suitable sources.
677/// The given source can be used to rewrite the definition into
678/// def = COPY src.
679///
680/// For instance, let us consider the following snippet:
681/// v0 =
682/// v2 = INSERT_SUBREG v1, v0, sub0
683/// def = COPY v2.sub0
684///
685/// Using a ValueTracker for def = COPY v2.sub0 will give the following
686/// suitable sources:
687/// v2.sub0 and v0.
688/// Then, def can be rewritten into def = COPY v0.
689class ValueTracker {
690private:
691 /// The current point into the use-def chain.
692 const MachineInstr *Def = nullptr;
693
694 /// The index of the definition in Def.
695 unsigned DefIdx = 0;
696
697 /// The sub register index of the definition.
698 unsigned DefSubReg;
699
700 /// The register where the value can be found.
701 Register Reg;
702
703 /// MachineRegisterInfo used to perform tracking.
704 const MachineRegisterInfo &MRI;
705
706 /// Optional TargetInstrInfo used to perform some complex tracking.
707 const TargetInstrInfo *TII;
708
709 /// Dispatcher to the right underlying implementation of getNextSource.
710 ValueTrackerResult getNextSourceImpl();
711
712 /// Specialized version of getNextSource for Copy instructions.
713 ValueTrackerResult getNextSourceFromCopy();
714
715 /// Specialized version of getNextSource for Bitcast instructions.
716 ValueTrackerResult getNextSourceFromBitcast();
717
718 /// Specialized version of getNextSource for RegSequence instructions.
719 ValueTrackerResult getNextSourceFromRegSequence();
720
721 /// Specialized version of getNextSource for InsertSubreg instructions.
722 ValueTrackerResult getNextSourceFromInsertSubreg();
723
724 /// Specialized version of getNextSource for ExtractSubreg instructions.
725 ValueTrackerResult getNextSourceFromExtractSubreg();
726
727 /// Specialized version of getNextSource for SubregToReg instructions.
728 ValueTrackerResult getNextSourceFromSubregToReg();
729
730 /// Specialized version of getNextSource for PHI instructions.
731 ValueTrackerResult getNextSourceFromPHI();
732
733public:
734 /// Create a ValueTracker instance for the value defined by \p Reg.
735 /// \p DefSubReg represents the sub register index the value tracker will
736 /// track. It does not need to match the sub register index used in the
737 /// definition of \p Reg.
738 /// If \p Reg is a physical register, a value tracker constructed with
739 /// this constructor will not find any alternative source.
740 /// Indeed, when \p Reg is a physical register that constructor does not
741 /// know which definition of \p Reg it should track.
742 /// Use the next constructor to track a physical register.
743 ValueTracker(Register Reg, unsigned DefSubReg, const MachineRegisterInfo &MRI,
744 const TargetInstrInfo *TII = nullptr)
745 : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
746 if (!Reg.isPhysical()) {
747 MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg);
748 if (DI != MRI.def_end()) {
749 Def = DI->getParent();
750 DefIdx = DI.getOperandNo();
751 }
752 }
753 }
754
755 /// Following the use-def chain, get the next available source
756 /// for the tracked value.
757 /// \return A ValueTrackerResult containing a set of registers
758 /// and sub registers with tracked values. A ValueTrackerResult with
759 /// an empty set of registers means no source was found.
760 ValueTrackerResult getNextSource();
761};
762
763} // end anonymous namespace
764
765char PeepholeOptimizerLegacy::ID = 0;
766
767char &llvm::PeepholeOptimizerLegacyID = PeepholeOptimizerLegacy::ID;
768
769INITIALIZE_PASS_BEGIN(PeepholeOptimizerLegacy, DEBUG_TYPE,
770 "Peephole Optimizations", false, false)
773INITIALIZE_PASS_END(PeepholeOptimizerLegacy, DEBUG_TYPE,
774 "Peephole Optimizations", false, false)
775
776/// If instruction is a copy-like instruction, i.e. it reads a single register
777/// and writes a single register and it does not modify the source, and if the
778/// source value is preserved as a sub-register of the result, then replace all
779/// reachable uses of the source with the subreg of the result.
780///
781/// Do not generate an EXTRACT that is used only in a debug use, as this changes
782/// the code. Since this code does not currently share EXTRACTs, just ignore all
783/// debug uses.
784bool PeepholeOptimizer::optimizeExtInstr(
786 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
787 Register SrcReg, DstReg;
788 unsigned SubIdx;
789 if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
790 return false;
791
792 if (DstReg.isPhysical() || SrcReg.isPhysical())
793 return false;
794
795 if (MRI->hasOneNonDBGUse(SrcReg))
796 // No other uses.
797 return false;
798
799 // Ensure DstReg can get a register class that actually supports
800 // sub-registers. Don't change the class until we commit.
801 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
802 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
803 if (!DstRC)
804 return false;
805
806 // The ext instr may be operating on a sub-register of SrcReg as well.
807 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
808 // register.
809 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
810 // SrcReg:SubIdx should be replaced.
811 bool UseSrcSubIdx =
812 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
813
814 // The source has other uses. See if we can replace the other uses with use of
815 // the result of the extension.
817 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
818 ReachedBBs.insert(UI.getParent());
819
820 // Uses that are in the same BB of uses of the result of the instruction.
822
823 // Uses that the result of the instruction can reach.
825
826 bool ExtendLife = true;
827 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
828 MachineInstr *UseMI = UseMO.getParent();
829 if (UseMI == &MI)
830 continue;
831
832 if (UseMI->isPHI()) {
833 ExtendLife = false;
834 continue;
835 }
836
837 // Only accept uses of SrcReg:SubIdx.
838 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
839 continue;
840
841 // It's an error to translate this:
842 //
843 // %reg1025 = <sext> %reg1024
844 // ...
845 // %reg1026 = SUBREG_TO_REG %reg1024, 4
846 //
847 // into this:
848 //
849 // %reg1025 = <sext> %reg1024
850 // ...
851 // %reg1027 = COPY %reg1025:4
852 // %reg1026 = SUBREG_TO_REG %reg1027, 4
853 //
854 // The problem here is that SUBREG_TO_REG is there to assert that an
855 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
856 // the COPY here, it will give us the value after the <sext>, not the
857 // original value of %reg1024 before <sext>.
858 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
859 continue;
860
861 MachineBasicBlock *UseMBB = UseMI->getParent();
862 if (UseMBB == &MBB) {
863 // Local uses that come after the extension.
864 if (!LocalMIs.count(UseMI))
865 Uses.push_back(&UseMO);
866 } else if (ReachedBBs.count(UseMBB)) {
867 // Non-local uses where the result of the extension is used. Always
868 // replace these unless it's a PHI.
869 Uses.push_back(&UseMO);
870 } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
871 // We may want to extend the live range of the extension result in order
872 // to replace these uses.
873 ExtendedUses.push_back(&UseMO);
874 } else {
875 // Both will be live out of the def MBB anyway. Don't extend live range of
876 // the extension result.
877 ExtendLife = false;
878 break;
879 }
880 }
881
882 if (ExtendLife && !ExtendedUses.empty())
883 // Extend the liveness of the extension result.
884 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
885
886 // Now replace all uses.
887 bool Changed = false;
888 if (!Uses.empty()) {
889 SmallPtrSet<MachineBasicBlock *, 4> PHIBBs;
890
891 // Look for PHI uses of the extended result, we don't want to extend the
892 // liveness of a PHI input. It breaks all kinds of assumptions down
893 // stream. A PHI use is expected to be the kill of its source values.
894 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
895 if (UI.isPHI())
896 PHIBBs.insert(UI.getParent());
897
898 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
899 for (MachineOperand *UseMO : Uses) {
900 MachineInstr *UseMI = UseMO->getParent();
901 MachineBasicBlock *UseMBB = UseMI->getParent();
902 if (PHIBBs.count(UseMBB))
903 continue;
904
905 if (!Changed)
906 MRI->constrainRegClass(DstReg, DstRC);
907
908 // SubReg defs are illegal in machine SSA phase,
909 // we should not generate SubReg defs.
910 //
911 // For example, for the instructions:
912 //
913 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
914 // %3:gprc_and_gprc_nor0 = COPY %0.sub_32:g8rc
915 //
916 // We should generate:
917 //
918 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
919 // %6:gprc_and_gprc_nor0 = COPY %1.sub_32:g8rc_and_g8rc_nox0
920 // %3:gprc_and_gprc_nor0 = COPY %6:gprc_and_gprc_nor0
921 //
922 if (UseSrcSubIdx) {
923 RC = MRI->getRegClass(UseMO->getReg());
924 if (UseMO->getSubReg())
925 RC = TRI->getSubRegisterClass(RC, UseMO->getSubReg());
926 }
927
928 Register NewVR = MRI->createVirtualRegister(RC);
929 [[maybe_unused]] auto Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
930 TII->get(TargetOpcode::COPY), NewVR)
931 .addReg(DstReg, {}, SubIdx);
932 LLVM_DEBUG(dbgs() << " Build new copy: " << *Copy
933 << " Changing: " << *UseMI);
934 if (UseSrcSubIdx)
935 UseMO->setSubReg(0);
936
937 UseMO->setReg(NewVR);
938 LLVM_DEBUG(dbgs() << " to: " << *UseMI);
939 ++NumReuse;
940 Changed = true;
941 }
942 }
943
944 return Changed;
945}
946
947/// If the instruction is a compare and the previous instruction it's comparing
948/// against already sets (or could be modified to set) the same flag as the
949/// compare, then we can remove the comparison and use the flag from the
950/// previous instruction.
951bool PeepholeOptimizer::optimizeCmpInstr(
954 // If this instruction is a comparison against zero and isn't comparing a
955 // physical register, we can try to optimize it.
956 Register SrcReg, SrcReg2;
957 int64_t CmpMask, CmpValue;
958 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
959 SrcReg.isPhysical() || SrcReg2.isPhysical())
960 return false;
961
962 // Attempt to optimize the comparison instruction.
963 LLVM_DEBUG(dbgs() << "Attempting to optimize compare: " << MI);
964 if (!TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI))
965 return false;
966
967 LLVM_DEBUG(dbgs() << " -> Successfully optimized compare!\n");
968 LocalMIs.erase(&MI);
969 ++NumCmps;
970
971 // The eliminated compare may have been the extra use preventing a
972 // load from being folded into the flag-setting instruction.
973 if (MachineInstr *FlagProducer =
974 SrcReg.isVirtual() ? MRI->getOneNonDBGUser(SrcReg) : nullptr) {
975 MachineInstr *LoadMI = MRI->getVRegDef(SrcReg);
976 // No store between LoadMI and FlagProducer that could change the value.
977 if (LocalMIs.count(FlagProducer) && LoadMI && LoadMI->canFoldAsLoad() &&
978 LoadMI->mayLoad() && LocalMIs.count(LoadMI) &&
980 make_range(std::next(LoadMI->getIterator()),
981 FlagProducer->getIterator()),
982 [](const MachineInstr &I) { return I.isLoadFoldBarrier(); }))
983 foldLoadInto(MF, *FlagProducer, SrcReg, LocalMIs);
984 }
985
986 return true;
987}
988
989/// Optimize a select instruction.
990bool PeepholeOptimizer::optimizeSelect(
991 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
992 assert(MI.isSelect() && "Should only be called when MI->isSelect() is true");
993 if (!TII->optimizeSelect(MI, LocalMIs))
994 return false;
995 LLVM_DEBUG(dbgs() << "Deleting select: " << MI);
996 MI.eraseFromParent();
997 ++NumSelects;
998 return true;
999}
1000
1001/// Check if a simpler conditional branch can be generated.
1002bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
1003 return TII->optimizeCondBranch(MI);
1004}
1005
1006/// Try to find a better source value that shares the same register file to
1007/// replace \p RegSubReg in an instruction like
1008/// `DefRC.DefSubReg = COPY RegSubReg`
1009///
1010/// When true is returned, the \p RewriteMap can be used by the client to
1011/// retrieve all Def -> Use along the way up to the next source. Any found
1012/// Use that is not itself a key for another entry, is the next source to
1013/// use. During the search for the next source, multiple sources can be found
1014/// given multiple incoming sources of a PHI instruction. In this case, we
1015/// look in each PHI source for the next source; all found next sources must
1016/// share the same register file as \p Reg and \p SubReg. The client should
1017/// then be capable to rewrite all intermediate PHIs to get the next source.
1018/// \return False if no alternative sources are available. True otherwise.
1019bool PeepholeOptimizer::findNextSource(const TargetRegisterClass *DefRC,
1020 unsigned DefSubReg,
1021 RegSubRegPair RegSubReg,
1022 RewriteMapTy &RewriteMap) {
1023 // Do not try to find a new source for a physical register.
1024 // So far we do not have any motivating example for doing that.
1025 // Thus, instead of maintaining untested code, we will revisit that if
1026 // that changes at some point.
1027 Register Reg = RegSubReg.Reg;
1028 RegSubRegPair CurSrcPair = RegSubReg;
1029 SmallVector<RegSubRegPair, 4> SrcToLook = {CurSrcPair};
1030
1031 unsigned PHICount = 0;
1032
1033 // Remember the last suitable source in case the search meets an invalid
1034 // source.
1035 bool FoundSuitable = false;
1036 RegSubRegPair SuitablePair = RegSubReg;
1037 bool Aborted = false;
1038 do {
1039 CurSrcPair = SrcToLook.pop_back_val();
1040 // As explained above, do not handle physical registers
1041 if (CurSrcPair.Reg.isPhysical()) {
1042 Aborted = true;
1043 break;
1044 }
1045
1046 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
1047
1048 // Follow the chain of copies until we find a more suitable source, a phi
1049 // or have to abort.
1050 while (true) {
1051 ValueTrackerResult Res = ValTracker.getNextSource();
1052 // Abort at the end of a chain (without finding a suitable source).
1053 if (!Res.isValid()) {
1054 Aborted = true;
1055 break;
1056 }
1057
1058 // Insert the Def -> Use entry for the recently found source.
1059 auto [InsertPt, WasInserted] = RewriteMap.try_emplace(CurSrcPair, Res);
1060
1061 if (!WasInserted) {
1062 const ValueTrackerResult &CurSrcRes = InsertPt->second;
1063
1064 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
1065 // An existent entry with multiple sources is a PHI cycle we must avoid.
1066 // Otherwise it's an entry with a valid next source we already found.
1067 if (CurSrcRes.getNumSources() > 1) {
1069 << "findNextSource: found PHI cycle, aborting...\n");
1070 Aborted = true;
1071 }
1072 break;
1073 }
1074
1075 // ValueTrackerResult usually have one source unless it's the result from
1076 // a PHI instruction. Add the found PHI edges to be looked up further.
1077 unsigned NumSrcs = Res.getNumSources();
1078 if (NumSrcs > 1) {
1079 PHICount++;
1080 if (PHICount >= RewritePHILimit) {
1081 LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
1082 Aborted = true;
1083 break;
1084 }
1085
1086 for (unsigned i = 0; i < NumSrcs; ++i)
1087 SrcToLook.push_back(Res.getSrc(i));
1088 break;
1089 }
1090
1091 CurSrcPair = Res.getSrc(0);
1092 // Do not extend the live-ranges of physical registers as they add
1093 // constraints to the register allocator. Moreover, if we want to extend
1094 // the live-range of a physical register, unlike SSA virtual register,
1095 // we will have to check that they aren't redefine before the related use.
1096 if (CurSrcPair.Reg.isPhysical()) {
1097 Aborted = true;
1098 break;
1099 }
1100
1101 // Keep following the chain if the value isn't any better yet.
1102 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
1103 if (!TRI->shouldRewriteCopySrc(DefRC, DefSubReg, SrcRC,
1104 CurSrcPair.SubReg))
1105 continue;
1106
1107 // We currently cannot deal with subreg operands on PHI instructions
1108 // (see insertPHI()).
1109 if (PHICount > 0 && CurSrcPair.SubReg != 0)
1110 continue;
1111
1112 // Don't stop at the first suitable source if it is still a subregister;
1113 // keep tracing to try to reach a deeper source. Remember it.
1114 if (CurSrcPair.SubReg != 0) {
1115 SuitablePair = CurSrcPair;
1116 FoundSuitable = true;
1117 continue;
1118 }
1119
1120 // We found a suitable source, and are done with this chain.
1121 break;
1122 }
1123
1124 // A dead-ended chain ends all exploration
1125 if (Aborted)
1126 break;
1127 } while (!SrcToLook.empty());
1128
1129 if (Aborted) {
1130 // If aborted with an invalid source, restore the suitable so far, if any.
1131 if (!FoundSuitable)
1132 return false;
1133
1134 CurSrcPair = SuitablePair;
1135 RewriteMap.erase(SuitablePair);
1136 }
1137
1138 // If we did not find a more suitable source, there is nothing to optimize.
1139 return CurSrcPair.Reg != Reg;
1140}
1141
1142/// Insert a PHI instruction with incoming edges \p SrcRegs that are
1143/// guaranteed to have the same register class. This is necessary whenever we
1144/// successfully traverse a PHI instruction and find suitable sources coming
1145/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
1146/// suitable to be used in a new COPY instruction.
1148 const TargetInstrInfo &TII,
1149 const SmallVectorImpl<RegSubRegPair> &SrcRegs,
1150 MachineInstr &OrigPHI) {
1151 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
1152
1153 const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
1154 // NewRC is only correct if no subregisters are involved. findNextSource()
1155 // should have rejected those cases already.
1156 assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
1157 Register NewVR = MRI.createVirtualRegister(NewRC);
1158 MachineBasicBlock *MBB = OrigPHI.getParent();
1159 MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
1160 TII.get(TargetOpcode::PHI), NewVR);
1161
1162 unsigned MBBOpIdx = 2;
1163 for (const RegSubRegPair &RegPair : SrcRegs) {
1164 MIB.addReg(RegPair.Reg, {}, RegPair.SubReg);
1165 MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
1166 MBBOpIdx += 2;
1167 }
1168
1169 return *MIB;
1170}
1171
1172/// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
1173/// the new source to use for rewrite. If \p HandleMultipleSources is true and
1174/// multiple sources for a given \p Def are found along the way, we found a
1175/// PHI instructions that needs to be rewritten.
1176/// TODO: HandleMultipleSources should be removed once we test PHI handling
1177/// with coalescable copies.
1178static RegSubRegPair
1180 RegSubRegPair Def,
1181 const PeepholeOptimizer::RewriteMapTy &RewriteMap,
1182 bool HandleMultipleSources = true) {
1183 RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
1184 while (true) {
1185 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
1186 // If there are no entries on the map, LookupSrc is the new source.
1187 if (!Res.isValid())
1188 return LookupSrc;
1189
1190 // There's only one source for this definition, keep searching...
1191 unsigned NumSrcs = Res.getNumSources();
1192 if (NumSrcs == 1) {
1193 LookupSrc.Reg = Res.getSrcReg(0);
1194 LookupSrc.SubReg = Res.getSrcSubReg(0);
1195 continue;
1196 }
1197
1198 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
1199 if (!HandleMultipleSources)
1200 break;
1201
1202 // Multiple sources, recurse into each source to find a new source
1203 // for it. Then, rewrite the PHI accordingly to its new edges.
1205 for (unsigned i = 0; i < NumSrcs; ++i) {
1206 RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
1207 NewPHISrcs.push_back(
1208 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
1209 }
1210
1211 // Build the new PHI node and return its def register as the new source.
1212 MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
1213 MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
1214 LLVM_DEBUG(dbgs() << "-- getNewSource\n");
1215 LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI);
1216 LLVM_DEBUG(dbgs() << " With: " << NewPHI);
1217 const MachineOperand &MODef = NewPHI.getOperand(0);
1218 return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
1219 }
1220
1221 return RegSubRegPair(0, 0);
1222}
1223
1224bool PeepholeOptimizer::optimizeCoalescableCopyImpl(Rewriter &&CpyRewriter) {
1225 bool Changed = false;
1226 // Get the right rewriter for the current copy.
1227 // Rewrite each rewritable source.
1228 RegSubRegPair Dst;
1229 RegSubRegPair TrackPair;
1230 while (CpyRewriter.getNextRewritableSource(TrackPair, Dst)) {
1231 if (Dst.Reg.isPhysical()) {
1232 // Do not try to find a new source for a physical register.
1233 // So far we do not have any motivating example for doing that.
1234 // Thus, instead of maintaining untested code, we will revisit that if
1235 // that changes at some point.
1236 continue;
1237 }
1238
1239 const TargetRegisterClass *DefRC = MRI->getRegClass(Dst.Reg);
1240
1241 // Keep track of PHI nodes and its incoming edges when looking for sources.
1242 RewriteMapTy RewriteMap;
1243 // Try to find a more suitable source. If we failed to do so, or get the
1244 // actual source, move to the next source.
1245 if (!findNextSource(DefRC, Dst.SubReg, TrackPair, RewriteMap))
1246 continue;
1247
1248 // Get the new source to rewrite. TODO: Only enable handling of multiple
1249 // sources (PHIs) once we have a motivating example and testcases for it.
1250 RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
1251 /*HandleMultipleSources=*/false);
1252 assert(TrackPair.Reg != NewSrc.Reg &&
1253 "should not rewrite source to original value");
1254 if (!NewSrc.Reg)
1255 continue;
1256
1257 if (NewSrc.SubReg) {
1258 // Verify the register class supports the subregister index. ARM's
1259 // copy-like queries return register:subreg pairs where the register's
1260 // current class does not directly support the subregister index.
1261 const TargetRegisterClass *RC = MRI->getRegClass(NewSrc.Reg);
1262 const TargetRegisterClass *WithSubRC =
1263 TRI->getSubClassWithSubReg(RC, NewSrc.SubReg);
1264 if (!MRI->constrainRegClass(NewSrc.Reg, WithSubRC))
1265 continue;
1266 Changed = true;
1267 }
1268
1269 // Rewrite source.
1270 if (CpyRewriter.RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg))
1271 Changed = true;
1272 }
1273
1274 // TODO: We could have a clean-up method to tidy the instruction.
1275 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1276 // => v0 = COPY v1
1277 // Currently we haven't seen motivating example for that and we
1278 // want to avoid untested code.
1279 NumRewrittenCopies += Changed;
1280 return Changed;
1281}
1282
1283/// Optimize generic copy instructions to avoid cross register bank copy.
1284/// The optimization looks through a chain of copies and tries to find a source
1285/// that has a compatible register class.
1286/// Two register classes are considered to be compatible if they share the same
1287/// register bank.
1288/// New copies issued by this optimization are register allocator
1289/// friendly. This optimization does not remove any copy as it may
1290/// overconstrain the register allocator, but replaces some operands
1291/// when possible.
1292/// \pre isCoalescableCopy(*MI) is true.
1293/// \return True, when \p MI has been rewritten. False otherwise.
1294bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
1295 assert(isCoalescableCopy(MI) && "Invalid argument");
1296 assert(MI.getDesc().getNumDefs() == 1 &&
1297 "Coalescer can understand multiple defs?!");
1298 const MachineOperand &MODef = MI.getOperand(0);
1299 // Do not rewrite physical definitions.
1300 if (MODef.getReg().isPhysical())
1301 return false;
1302
1303 switch (MI.getOpcode()) {
1304 case TargetOpcode::COPY:
1305 return optimizeCoalescableCopyImpl(CopyRewriter(MI));
1306 case TargetOpcode::INSERT_SUBREG:
1307 return optimizeCoalescableCopyImpl(InsertSubregRewriter(MI));
1308 case TargetOpcode::EXTRACT_SUBREG:
1309 return optimizeCoalescableCopyImpl(ExtractSubregRewriter(MI, *TII));
1310 case TargetOpcode::REG_SEQUENCE:
1311 return optimizeCoalescableCopyImpl(RegSequenceRewriter(MI));
1312 default:
1313 // Handle uncoalescable copy-like instructions.
1314 if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1315 MI.isExtractSubregLike())
1316 return optimizeCoalescableCopyImpl(UncoalescableRewriter(MI));
1317 return false;
1318 }
1319}
1320
1321/// Rewrite the source found through \p Def, by using the \p RewriteMap
1322/// and create a new COPY instruction. More info about RewriteMap in
1323/// PeepholeOptimizer::findNextSource. Right now this is only used to handle
1324/// Uncoalescable copies, since they are copy like instructions that aren't
1325/// recognized by the register allocator.
1326MachineInstr &PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
1327 RegSubRegPair Def,
1328 RewriteMapTy &RewriteMap) {
1329 assert(!Def.Reg.isPhysical() && "We do not rewrite physical registers");
1330
1331 // Find the new source to use in the COPY rewrite.
1332 RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
1333
1334 // Insert the COPY.
1335 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
1336 Register NewVReg = MRI->createVirtualRegister(DefRC);
1337
1338 if (NewSrc.SubReg) {
1339 const TargetRegisterClass *NewSrcRC = MRI->getRegClass(NewSrc.Reg);
1340 const TargetRegisterClass *WithSubRC =
1341 TRI->getSubClassWithSubReg(NewSrcRC, NewSrc.SubReg);
1342
1343 // The new source may not directly support the subregister, but we should be
1344 // able to assume it is constrainable to support the subregister (otherwise
1345 // ValueTracker was lying and reported a useless value).
1346 if (!MRI->constrainRegClass(NewSrc.Reg, WithSubRC))
1347 llvm_unreachable("replacement register cannot support subregister");
1348 }
1349
1350 MachineInstr *NewCopy =
1351 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1352 TII->get(TargetOpcode::COPY), NewVReg)
1353 .addReg(NewSrc.Reg, {}, NewSrc.SubReg);
1354
1355 if (Def.SubReg) {
1356 NewCopy->getOperand(0).setSubReg(Def.SubReg);
1357 NewCopy->getOperand(0).setIsUndef();
1358 }
1359
1360 LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
1361 LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike);
1362 LLVM_DEBUG(dbgs() << " With: " << *NewCopy);
1363 MRI->replaceRegWith(Def.Reg, NewVReg);
1364
1365 return *NewCopy;
1366}
1367
1368/// Optimize copy-like instructions to create
1369/// register coalescer friendly instruction.
1370/// The optimization tries to kill-off the \p MI by looking
1371/// through a chain of copies to find a source that has a compatible
1372/// register class.
1373/// If such a source is found, it replace \p MI by a generic COPY
1374/// operation.
1375/// \pre isUncoalescableCopy(*MI) is true.
1376/// \return True, when \p MI has been optimized. In that case, \p MI has
1377/// been removed from its parent.
1378/// All COPY instructions created, are inserted in \p LocalMIs.
1379bool PeepholeOptimizer::optimizeUncoalescableCopy(
1380 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1381 assert(isUncoalescableCopy(MI) && "Invalid argument");
1382 UncoalescableRewriter CpyRewriter(MI);
1383
1384 // Rewrite each rewritable source by generating new COPYs. This works
1385 // differently from optimizeCoalescableCopy since it first makes sure that all
1386 // definitions can be rewritten.
1387 RewriteMapTy RewriteMap;
1388 RegSubRegPair Src;
1390 SmallVector<RegSubRegPair, 4> RewritePairs;
1391 while (CpyRewriter.getNextRewritableSource(Src, Def)) {
1392 // If a physical register is here, this is probably for a good reason.
1393 // Do not rewrite that.
1394 if (Def.Reg.isPhysical())
1395 return false;
1396
1397 // FIXME: Uncoalescable copies are treated differently by
1398 // UncoalescableRewriter, and this probably should not share
1399 // API. getNextRewritableSource really finds rewritable defs.
1400 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
1401
1402 // If we do not know how to rewrite this definition, there is no point
1403 // in trying to kill this instruction.
1404 if (!findNextSource(DefRC, Def.SubReg, Def, RewriteMap))
1405 return false;
1406
1407 RewritePairs.push_back(Def);
1408 }
1409
1410 // The change is possible for all defs, do it.
1411 for (const RegSubRegPair &Def : RewritePairs) {
1412 // Rewrite the "copy" in a way the register coalescer understands.
1413 MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
1414 LocalMIs.insert(&NewCopy);
1415 }
1416
1417 // MI is now dead.
1418 LLVM_DEBUG(dbgs() << "Deleting uncoalescable copy: " << MI);
1419 MI.eraseFromParent();
1420 ++NumUncoalescableCopies;
1421 return true;
1422}
1423
1424/// Check whether MI is a candidate for folding into a later instruction.
1425/// We only fold loads to virtual registers and the virtual register defined
1426/// has a single user.
1427bool PeepholeOptimizer::isLoadFoldable(
1428 MachineInstr &MI, SmallSet<Register, 16> &FoldAsLoadDefCandidates) {
1429 if (!MI.canFoldAsLoad() || !MI.mayLoad())
1430 return false;
1431 const MCInstrDesc &MCID = MI.getDesc();
1432 if (MCID.getNumDefs() != 1)
1433 return false;
1434
1435 Register Reg = MI.getOperand(0).getReg();
1436 // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
1437 // loads. It should be checked when processing uses of the load, since
1438 // uses can be removed during peephole.
1439 if (Reg.isVirtual() && !MI.getOperand(0).getSubReg() &&
1441 FoldAsLoadDefCandidates.insert(Reg);
1442 return true;
1443 }
1444 return false;
1445}
1446
1447MachineInstr *
1448PeepholeOptimizer::foldLoadInto(MachineFunction &MF, MachineInstr &MI,
1449 Register FoldReg,
1450 SmallPtrSet<MachineInstr *, 16> &LocalMIs) {
1451 Register Reg = FoldReg;
1452 MachineInstr *DefMI = nullptr;
1453 MachineInstr *CopyMI = nullptr;
1454 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI, Reg, DefMI, CopyMI);
1455 if (!FoldMI)
1456 return nullptr;
1457 LLVM_DEBUG(dbgs() << "Replacing: " << MI << " With: " << *FoldMI);
1458 LocalMIs.erase(&MI);
1459 LocalMIs.erase(DefMI);
1460 LocalMIs.insert(FoldMI);
1461 if (CopyMI)
1462 LocalMIs.insert(CopyMI);
1463 if (MI.shouldUpdateAdditionalCallInfo())
1464 MF.moveAdditionalCallInfo(&MI, FoldMI);
1465 MI.eraseFromParent();
1468 ++NumLoadFold;
1469 return FoldMI;
1470}
1471
1472bool PeepholeOptimizer::isMoveImmediate(
1473 MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
1474 DenseMap<Register, MachineInstr *> &ImmDefMIs) {
1475 const MCInstrDesc &MCID = MI.getDesc();
1476 if (MCID.getNumDefs() != 1 || !MI.getOperand(0).isReg())
1477 return false;
1478 Register Reg = MI.getOperand(0).getReg();
1479 if (!Reg.isVirtual())
1480 return false;
1481
1482 int64_t ImmVal;
1483 if (!MI.isMoveImmediate() && !TII->getConstValDefinedInReg(MI, Reg, ImmVal))
1484 return false;
1485
1486 ImmDefMIs.insert(std::make_pair(Reg, &MI));
1487 ImmDefRegs.insert(Reg);
1488 return true;
1489}
1490
1491/// Try folding register operands that are defined by move immediate
1492/// instructions, i.e. a trivial constant folding optimization, if
1493/// and only if the def and use are in the same BB.
1494bool PeepholeOptimizer::foldImmediate(
1495 MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
1496 DenseMap<Register, MachineInstr *> &ImmDefMIs, bool &Deleted) {
1497 Deleted = false;
1498 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1499 MachineOperand &MO = MI.getOperand(i);
1500 if (!MO.isReg() || MO.isDef())
1501 continue;
1502 Register Reg = MO.getReg();
1503 if (!Reg.isVirtual())
1504 continue;
1505 if (ImmDefRegs.count(Reg) == 0)
1506 continue;
1507 auto II = ImmDefMIs.find(Reg);
1508 assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
1509 if (TII->foldImmediate(MI, *II->second, Reg, MRI)) {
1510 ++NumImmFold;
1511 // foldImmediate can delete ImmDefMI if MI was its only user. If ImmDefMI
1512 // is not deleted, and we happened to get a same MI, we can delete MI and
1513 // replace its users.
1514 if (MRI->getVRegDef(Reg) &&
1516 Register DstReg = MI.getOperand(0).getReg();
1517 if (DstReg.isVirtual() &&
1518 MRI->getRegClass(DstReg) == MRI->getRegClass(Reg)) {
1519 MRI->replaceRegWith(DstReg, Reg);
1520 MI.eraseFromParent();
1521 Deleted = true;
1522 }
1523 }
1524 return true;
1525 }
1526 }
1527 return false;
1528}
1529
1530// FIXME: This is very simple and misses some cases which should be handled when
1531// motivating examples are found.
1532//
1533// The copy rewriting logic should look at uses as well as defs and be able to
1534// eliminate copies across blocks.
1535//
1536// Later copies that are subregister extracts will also not be eliminated since
1537// only the first copy is considered.
1538//
1539// e.g.
1540// %1 = COPY %0
1541// %2 = COPY %0:sub1
1542//
1543// Should replace %2 uses with %1:sub1
1544bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI) {
1545 assert(MI.isCopy() && "expected a COPY machine instruction");
1546
1547 RegSubRegPair SrcPair;
1548 if (!getCopySrc(MI, SrcPair))
1549 return false;
1550
1551 Register DstReg = MI.getOperand(0).getReg();
1552 if (!DstReg.isVirtual())
1553 return false;
1554
1555 if (CopySrcMIs.insert(std::make_pair(SrcPair, &MI)).second) {
1556 // First copy of this reg seen.
1557 return false;
1558 }
1559
1560 MachineInstr *PrevCopy = CopySrcMIs.find(SrcPair)->second;
1561
1562 assert(SrcPair.SubReg == PrevCopy->getOperand(1).getSubReg() &&
1563 "Unexpected mismatching subreg!");
1564
1565 Register PrevDstReg = PrevCopy->getOperand(0).getReg();
1566
1567 // Only replace if the copy register class is the same.
1568 //
1569 // TODO: If we have multiple copies to different register classes, we may want
1570 // to track multiple copies of the same source register.
1571 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1572 return false;
1573
1574 MRI->replaceRegWith(DstReg, PrevDstReg);
1575 return true;
1576}
1577
1578bool PeepholeOptimizer::isNAPhysCopy(Register Reg) {
1579 return Reg.isPhysical() && !MRI->isAllocatable(Reg);
1580}
1581
1582bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1583 MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs) {
1584 assert(MI.isCopy() && "expected a COPY machine instruction");
1585
1587 return false;
1588
1589 Register DstReg = MI.getOperand(0).getReg();
1590 Register SrcReg = MI.getOperand(1).getReg();
1591 if (isNAPhysCopy(SrcReg) && DstReg.isVirtual()) {
1592 // %vreg = COPY $physreg
1593 // Avoid using a datastructure which can track multiple live non-allocatable
1594 // phys->virt copies since LLVM doesn't seem to do this.
1595 NAPhysToVirtMIs.insert({SrcReg, &MI});
1596 return false;
1597 }
1598
1599 if (!(SrcReg.isVirtual() && isNAPhysCopy(DstReg)))
1600 return false;
1601
1602 // $physreg = COPY %vreg
1603 auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1604 if (PrevCopy == NAPhysToVirtMIs.end()) {
1605 // We can't remove the copy: there was an intervening clobber of the
1606 // non-allocatable physical register after the copy to virtual.
1607 LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
1608 << MI);
1609 return false;
1610 }
1611
1612 Register PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1613 if (PrevDstReg == SrcReg) {
1614 // Remove the virt->phys copy: we saw the virtual register definition, and
1615 // the non-allocatable physical register's state hasn't changed since then.
1616 LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
1617 ++NumNAPhysCopies;
1618 return true;
1619 }
1620
1621 // Potential missed optimization opportunity: we saw a different virtual
1622 // register get a copy of the non-allocatable physical register, and we only
1623 // track one such copy. Avoid getting confused by this new non-allocatable
1624 // physical register definition, and remove it from the tracked copies.
1625 LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
1626 NAPhysToVirtMIs.erase(PrevCopy);
1627 return false;
1628}
1629
1630/// \bried Returns true if \p MO is a virtual register operand.
1632 return MO.isReg() && MO.getReg().isVirtual();
1633}
1634
1635bool PeepholeOptimizer::findTargetRecurrence(
1636 Register Reg, const SmallSet<Register, 2> &TargetRegs,
1637 RecurrenceCycle &RC) {
1638 // Recurrence found if Reg is in TargetRegs.
1639 if (TargetRegs.count(Reg))
1640 return true;
1641
1642 // TODO: Curerntly, we only allow the last instruction of the recurrence
1643 // cycle (the instruction that feeds the PHI instruction) to have more than
1644 // one uses to guarantee that commuting operands does not tie registers
1645 // with overlapping live range. Once we have actual live range info of
1646 // each register, this constraint can be relaxed.
1647 if (!MRI->hasOneNonDBGUse(Reg))
1648 return false;
1649
1650 // Give up if the reccurrence chain length is longer than the limit.
1651 if (RC.size() >= MaxRecurrenceChain)
1652 return false;
1653
1654 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
1655 unsigned Idx = MI.findRegisterUseOperandIdx(Reg, /*TRI=*/nullptr);
1656
1657 // Only interested in recurrences whose instructions have only one def, which
1658 // is a virtual register.
1659 if (MI.getDesc().getNumDefs() != 1)
1660 return false;
1661
1662 MachineOperand &DefOp = MI.getOperand(0);
1663 if (!isVirtualRegisterOperand(DefOp))
1664 return false;
1665
1666 // Check if def operand of MI is tied to any use operand. We are only
1667 // interested in the case that all the instructions in the recurrence chain
1668 // have there def operand tied with one of the use operand.
1669 unsigned TiedUseIdx;
1670 if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
1671 return false;
1672
1673 if (Idx == TiedUseIdx) {
1674 RC.push_back(RecurrenceInstr(&MI));
1675 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1676 } else {
1677 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1678 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1679 if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
1680 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1681 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1682 }
1683 }
1684
1685 return false;
1686}
1687
1688/// Phi instructions will eventually be lowered to copy instructions.
1689/// If phi is in a loop header, a recurrence may formulated around the source
1690/// and destination of the phi. For such case commuting operands of the
1691/// instructions in the recurrence may enable coalescing of the copy instruction
1692/// generated from the phi. For example, if there is a recurrence of
1693///
1694/// LoopHeader:
1695/// %1 = phi(%0, %100)
1696/// LoopLatch:
1697/// %0<def, tied1> = ADD %2<def, tied0>, %1
1698///
1699/// , the fact that %0 and %2 are in the same tied operands set makes
1700/// the coalescing of copy instruction generated from the phi in
1701/// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
1702/// %2 have overlapping live range. This introduces additional move
1703/// instruction to the final assembly. However, if we commute %2 and
1704/// %1 of ADD instruction, the redundant move instruction can be
1705/// avoided.
1706bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1707 SmallSet<Register, 2> TargetRegs;
1708 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1709 MachineOperand &MO = PHI.getOperand(Idx);
1710 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
1711 TargetRegs.insert(MO.getReg());
1712 }
1713
1714 bool Changed = false;
1715 RecurrenceCycle RC;
1716 if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
1717 // Commutes operands of instructions in RC if necessary so that the copy to
1718 // be generated from PHI can be coalesced.
1719 LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
1720 for (auto &RI : RC) {
1721 LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
1722 auto CP = RI.getCommutePair();
1723 if (CP) {
1724 Changed = true;
1725 TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
1726 (*CP).second);
1727 LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
1728 }
1729 }
1730 }
1731
1732 return Changed;
1733}
1734
1735PreservedAnalyses
1738 MFPropsModifier _(*this, MF);
1739 auto *DT =
1740 Aggressive ? &MFAM.getResult<MachineDominatorTreeAnalysis>(MF) : nullptr;
1741 auto *MLI = &MFAM.getResult<MachineLoopAnalysis>(MF);
1742 PeepholeOptimizer Impl(DT, MLI);
1743 bool Changed = Impl.run(MF);
1744 if (!Changed)
1745 return PreservedAnalyses::all();
1746
1748 PA.preserveSet<CFGAnalyses>();
1749 return PA;
1750}
1751
1752bool PeepholeOptimizerLegacy::runOnMachineFunction(MachineFunction &MF) {
1753 if (skipFunction(MF.getFunction()))
1754 return false;
1755 auto *DT = Aggressive
1756 ? &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree()
1757 : nullptr;
1758 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1759 PeepholeOptimizer Impl(DT, MLI);
1760 return Impl.run(MF);
1761}
1762
1763bool PeepholeOptimizer::run(MachineFunction &MF) {
1764
1765 LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1766 LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1767
1768 if (DisablePeephole)
1769 return false;
1770
1771 TII = MF.getSubtarget().getInstrInfo();
1773 MRI = &MF.getRegInfo();
1774 MF.setDelegate(this);
1775
1776 bool Changed = false;
1777
1778 for (MachineBasicBlock &MBB : MF) {
1779 bool SeenMoveImm = false;
1780
1781 // During this forward scan, at some point it needs to answer the question
1782 // "given a pointer to an MI in the current BB, is it located before or
1783 // after the current instruction".
1784 // To perform this, the following set keeps track of the MIs already seen
1785 // during the scan, if a MI is not in the set, it is assumed to be located
1786 // after. Newly created MIs have to be inserted in the set as well.
1788 SmallSet<Register, 4> ImmDefRegs;
1790 SmallSet<Register, 16> FoldAsLoadDefCandidates;
1791
1792 // Track when a non-allocatable physical register is copied to a virtual
1793 // register so that useless moves can be removed.
1794 //
1795 // $physreg is the map index; MI is the last valid `%vreg = COPY $physreg`
1796 // without any intervening re-definition of $physreg.
1797 DenseMap<Register, MachineInstr *> NAPhysToVirtMIs;
1798
1799 CopySrcMIs.clear();
1800
1801 bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1802
1803 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1804 MII != MIE;) {
1805 MachineInstr *MI = &*MII;
1806 // We may be erasing MI below, increment MII now.
1807 ++MII;
1808 LocalMIs.insert(MI);
1809
1810 // Skip debug instructions. They should not affect this peephole
1811 // optimization.
1812 if (MI->isDebugInstr())
1813 continue;
1814
1815 if (MI->isPosition())
1816 continue;
1817
1818 if (IsLoopHeader && MI->isPHI()) {
1819 if (optimizeRecurrence(*MI)) {
1820 Changed = true;
1821 continue;
1822 }
1823 }
1824
1825 if (!MI->isCopy()) {
1826 for (const MachineOperand &MO : MI->operands()) {
1827 // Visit all operands: definitions can be implicit or explicit.
1828 if (MO.isReg()) {
1829 Register Reg = MO.getReg();
1830 if (MO.isDef() && isNAPhysCopy(Reg)) {
1831 const auto &Def = NAPhysToVirtMIs.find(Reg);
1832 if (Def != NAPhysToVirtMIs.end()) {
1833 // A new definition of the non-allocatable physical register
1834 // invalidates previous copies.
1836 << "NAPhysCopy: invalidating because of " << *MI);
1837 NAPhysToVirtMIs.erase(Def);
1838 }
1839 }
1840 } else if (MO.isRegMask()) {
1841 const uint32_t *RegMask = MO.getRegMask();
1842 NAPhysToVirtMIs.remove_if([&](const auto &RegMI) {
1843 if (!MachineOperand::clobbersPhysReg(RegMask, RegMI.first))
1844 return false;
1846 << "NAPhysCopy: invalidating because of " << *MI);
1847 return true;
1848 });
1849 }
1850 }
1851 }
1852
1853 if (MI->isImplicitDef() || MI->isKill())
1854 continue;
1855
1856 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1857 // Blow away all non-allocatable physical registers knowledge since we
1858 // don't know what's correct anymore.
1859 //
1860 // FIXME: handle explicit asm clobbers.
1861 LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
1862 << *MI);
1863 NAPhysToVirtMIs.clear();
1864 }
1865
1866 if (MI->isCompare() && optimizeCmpInstr(*MI, MF, LocalMIs)) {
1867 Changed = true;
1868 continue;
1869 }
1870
1871 if ((isUncoalescableCopy(*MI) &&
1872 optimizeUncoalescableCopy(*MI, LocalMIs)) ||
1873 (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
1874 // MI is deleted.
1875 LocalMIs.erase(MI);
1876 Changed = true;
1877 continue;
1878 }
1879
1880 if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
1881 Changed = true;
1882 continue;
1883 }
1884
1885 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
1886 // MI is just rewritten.
1887 Changed = true;
1888 continue;
1889 }
1890
1891 if (MI->isCopy() && (foldRedundantCopy(*MI) ||
1892 foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
1893 LocalMIs.erase(MI);
1894 LLVM_DEBUG(dbgs() << "Deleting redundant copy: " << *MI << "\n");
1895 MI->eraseFromParent();
1896 Changed = true;
1897 continue;
1898 }
1899
1900 if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
1901 SeenMoveImm = true;
1902 } else {
1903 Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
1904 // optimizeExtInstr might have created new instructions after MI
1905 // and before the already incremented MII. Adjust MII so that the
1906 // next iteration sees the new instructions.
1907 MII = MI;
1908 ++MII;
1909 if (SeenMoveImm) {
1910 bool Deleted;
1911 Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs, Deleted);
1912 if (Deleted) {
1913 LocalMIs.erase(MI);
1914 continue;
1915 }
1916 }
1917 }
1918
1919 // Check whether MI is a load candidate for folding into a later
1920 // instruction. If MI is not a candidate, check whether we can fold an
1921 // earlier load into MI.
1922 if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
1923 !FoldAsLoadDefCandidates.empty()) {
1924
1925 // We visit each operand even after successfully folding a previous
1926 // one. This allows us to fold multiple loads into a single
1927 // instruction. We do assume that optimizeLoadInstr doesn't insert
1928 // foldable uses earlier in the argument list. Since we don't restart
1929 // iteration, we'd miss such cases.
1930 const MCInstrDesc &MIDesc = MI->getDesc();
1931 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands(); ++i) {
1932 const MachineOperand &MOp = MI->getOperand(i);
1933 if (!MOp.isReg())
1934 continue;
1935 Register FoldAsLoadDefReg = MOp.getReg();
1936 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1937 // We need to fold load after optimizeCmpInstr, since
1938 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1939 Register FoldedReg = FoldAsLoadDefReg;
1940 if (MachineInstr *FoldMI =
1941 foldLoadInto(MF, *MI, FoldAsLoadDefReg, LocalMIs)) {
1942 FoldAsLoadDefCandidates.erase(FoldedReg);
1943 // MI is replaced with FoldMI so we can continue trying to fold
1944 Changed = true;
1945 MI = FoldMI;
1946 }
1947 }
1948 }
1949 }
1950
1951 // If we run into an instruction we can't fold across, discard
1952 // the load candidates. Note: We might be able to fold *into* this
1953 // instruction, so this needs to be after the folding logic.
1954 if (MI->isLoadFoldBarrier()) {
1955 LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
1956 FoldAsLoadDefCandidates.clear();
1957 }
1958 }
1959 }
1960
1961 MF.resetDelegate(this);
1962 return Changed;
1963}
1964
1965ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1966 assert(Def->isCopy() && "Invalid definition");
1967 // Copy instruction are supposed to be: Def = Src.
1968 // If someone breaks this assumption, bad things will happen everywhere.
1969 // There may be implicit uses preventing the copy to be moved across
1970 // some target specific register definitions
1971 assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 &&
1972 "Invalid number of operands");
1973 assert(!Def->hasImplicitDef() && "Only implicit uses are allowed");
1974 assert(!Def->getOperand(DefIdx).getSubReg() && "no subregister defs in SSA");
1975
1976 // Otherwise, we want the whole source.
1977 const MachineOperand &Src = Def->getOperand(1);
1978 if (Src.isUndef())
1979 return ValueTrackerResult();
1980
1981 Register SrcReg = Src.getReg();
1982 unsigned SubReg = Src.getSubReg();
1983 if (DefSubReg) {
1984 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1985 SubReg = TRI->composeSubRegIndices(SubReg, DefSubReg);
1986
1987 if (SrcReg.isVirtual()) {
1988 // TODO: Try constraining on rewrite if we can
1989 const TargetRegisterClass *RegRC = MRI.getRegClass(SrcReg);
1990 if (!TRI->isSubRegValidForRegClass(RegRC, SubReg))
1991 return ValueTrackerResult();
1992 } else {
1993 if (!TRI->getSubReg(SrcReg, SubReg))
1994 return ValueTrackerResult();
1995 }
1996 }
1997
1998 return ValueTrackerResult(SrcReg, SubReg);
1999}
2000
2001ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
2002 assert(Def->isBitcast() && "Invalid definition");
2003
2004 // Bail if there are effects that a plain copy will not expose.
2005 if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects())
2006 return ValueTrackerResult();
2007
2008 // Bitcasts with more than one def are not supported.
2009 if (Def->getDesc().getNumDefs() != 1)
2010 return ValueTrackerResult();
2011
2012 assert(!Def->getOperand(DefIdx).getSubReg() && "no subregister defs in SSA");
2013
2014 unsigned SrcIdx = Def->getNumOperands();
2015 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
2016 ++OpIdx) {
2017 const MachineOperand &MO = Def->getOperand(OpIdx);
2018 if (!MO.isReg() || !MO.getReg())
2019 continue;
2020 // Ignore dead implicit defs.
2021 if (MO.isImplicit() && MO.isDead())
2022 continue;
2023 assert(!MO.isDef() && "We should have skipped all the definitions by now");
2024 if (SrcIdx != EndOpIdx)
2025 // Multiple sources?
2026 return ValueTrackerResult();
2027 SrcIdx = OpIdx;
2028 }
2029
2030 // In some rare case, Def has no input, SrcIdx is out of bound,
2031 // getOperand(SrcIdx) will fail below.
2032 if (SrcIdx >= Def->getNumOperands())
2033 return ValueTrackerResult();
2034
2035 const MachineOperand &DefOp = Def->getOperand(DefIdx);
2036
2037 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
2038 // will break the assumed guarantees for the upper bits.
2039 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
2040 if (UseMI.isSubregToReg())
2041 return ValueTrackerResult();
2042 }
2043
2044 const MachineOperand &Src = Def->getOperand(SrcIdx);
2045 if (Src.isUndef())
2046 return ValueTrackerResult();
2047 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
2048}
2049
2050ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
2051 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
2052 "Invalid definition");
2053
2054 assert(!Def->getOperand(DefIdx).getSubReg() && "illegal subregister def");
2055
2057 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
2058 return ValueTrackerResult();
2059
2060 // We are looking at:
2061 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
2062 //
2063 // Check if one of the operands exactly defines the subreg we are interested
2064 // in.
2065 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
2066 if (RegSeqInput.SubIdx == DefSubReg)
2067 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
2068 }
2069
2070 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
2071
2072 // If we did not find an exact match, see if we can do a composition to
2073 // extract a sub-subregister.
2074 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
2075 LaneBitmask DefMask = TRI->getSubRegIndexLaneMask(DefSubReg);
2076 LaneBitmask ThisOpRegMask = TRI->getSubRegIndexLaneMask(RegSeqInput.SubIdx);
2077
2078 // Check that this extract reads a subset of this single reg_sequence input.
2079 //
2080 // FIXME: We should be able to filter this in terms of the indexes directly
2081 // without checking the lanemasks.
2082 if ((DefMask & ThisOpRegMask) != DefMask)
2083 continue;
2084
2085 unsigned ReverseDefCompose =
2086 TRI->reverseComposeSubRegIndices(RegSeqInput.SubIdx, DefSubReg);
2087 if (!ReverseDefCompose)
2088 continue;
2089
2090 unsigned ComposedDefInSrcReg1 =
2091 TRI->composeSubRegIndices(RegSeqInput.SubReg, ReverseDefCompose);
2092
2093 // TODO: We should be able to defer checking if the result register class
2094 // supports the index to continue looking for a rewritable source.
2095 //
2096 // TODO: Should we modify the register class to support the index?
2097 const TargetRegisterClass *SrcRC = MRI.getRegClass(RegSeqInput.Reg);
2098 if (!TRI->isSubRegValidForRegClass(SrcRC, ComposedDefInSrcReg1))
2099 return ValueTrackerResult();
2100
2101 return ValueTrackerResult(RegSeqInput.Reg, ComposedDefInSrcReg1);
2102 }
2103
2104 // If the subreg we are tracking is super-defined by another subreg,
2105 // we could follow this value. However, this would require to compose
2106 // the subreg and we do not do that for now.
2107 return ValueTrackerResult();
2108}
2109
2110ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
2111 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
2112 "Invalid definition");
2113 assert(!Def->getOperand(DefIdx).getSubReg() && "no subreg defs in SSA");
2114
2116 RegSubRegPairAndIdx InsertedReg;
2117 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
2118 return ValueTrackerResult();
2119
2120 // We are looking at:
2121 // Def = INSERT_SUBREG v0, v1, sub1
2122 // There are two cases:
2123 // 1. DefSubReg == sub1, get v1.
2124 // 2. DefSubReg != sub1, the value may be available through v0.
2125
2126 // #1 Check if the inserted register matches the required sub index.
2127 if (InsertedReg.SubIdx == DefSubReg) {
2128 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
2129 }
2130 // #2 Otherwise, if the sub register we are looking for is not partial
2131 // defined by the inserted element, we can look through the main
2132 // register (v0).
2133 const MachineOperand &MODef = Def->getOperand(DefIdx);
2134 // If the result register (Def) and the base register (v0) do not
2135 // have the same register class or if we have to compose
2136 // subregisters, bail out.
2137 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
2138 BaseReg.SubReg)
2139 return ValueTrackerResult();
2140
2141 // Get the TRI and check if the inserted sub-register overlaps with the
2142 // sub-register we are tracking.
2143 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
2144 if ((TRI->getSubRegIndexLaneMask(DefSubReg) &
2145 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx))
2146 .any())
2147 return ValueTrackerResult();
2148 // At this point, the value is available in v0 via the same subreg
2149 // we used for Def.
2150 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
2151}
2152
2153ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
2154 assert((Def->isExtractSubreg() || Def->isExtractSubregLike()) &&
2155 "Invalid definition");
2156 // We are looking at:
2157 // Def = EXTRACT_SUBREG v0, sub0
2158
2159 // Bail if we have to compose sub registers.
2160 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
2161 if (DefSubReg)
2162 return ValueTrackerResult();
2163
2164 RegSubRegPairAndIdx ExtractSubregInputReg;
2165 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
2166 return ValueTrackerResult();
2167
2168 // Bail if we have to compose sub registers.
2169 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
2170 if (ExtractSubregInputReg.SubReg)
2171 return ValueTrackerResult();
2172 // Otherwise, the value is available in the v0.sub0.
2173 return ValueTrackerResult(ExtractSubregInputReg.Reg,
2174 ExtractSubregInputReg.SubIdx);
2175}
2176
2177ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
2178 assert(Def->isSubregToReg() && "Invalid definition");
2179 // We are looking at:
2180 // Def = SUBREG_TO_REG v0, sub0
2181
2182 // Bail if we have to compose sub registers.
2183 // If DefSubReg != sub0, we would have to check that all the bits
2184 // we track are included in sub0 and if yes, we would have to
2185 // determine the right subreg in v0.
2186 if (DefSubReg != Def->getOperand(2).getImm())
2187 return ValueTrackerResult();
2188 // Bail if we have to compose sub registers.
2189 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2190 if (Def->getOperand(1).getSubReg())
2191 return ValueTrackerResult();
2192
2193 return ValueTrackerResult(Def->getOperand(1).getReg(),
2194 Def->getOperand(2).getImm());
2195}
2196
2197/// Explore each PHI incoming operand and return its sources.
2198ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2199 assert(Def->isPHI() && "Invalid definition");
2200 ValueTrackerResult Res;
2201
2202 // Return all register sources for PHI instructions.
2203 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2204 const MachineOperand &MO = Def->getOperand(i);
2205 assert(MO.isReg() && "Invalid PHI instruction");
2206 // We have no code to deal with undef operands. They shouldn't happen in
2207 // normal programs anyway.
2208 if (MO.isUndef())
2209 return ValueTrackerResult();
2210 Res.addSource(MO.getReg(), MO.getSubReg());
2211 }
2212
2213 return Res;
2214}
2215
2216ValueTrackerResult ValueTracker::getNextSourceImpl() {
2217 assert(Def && "This method needs a valid definition");
2218
2219 assert(((Def->getOperand(DefIdx).isDef() &&
2220 (DefIdx < Def->getDesc().getNumDefs() ||
2221 Def->getDesc().isVariadic())) ||
2222 Def->getOperand(DefIdx).isImplicit()) &&
2223 "Invalid DefIdx");
2224 if (Def->isCopy())
2225 return getNextSourceFromCopy();
2226 if (Def->isBitcast())
2227 return getNextSourceFromBitcast();
2228 // All the remaining cases involve "complex" instructions.
2229 // Bail if we did not ask for the advanced tracking.
2231 return ValueTrackerResult();
2232 if (Def->isRegSequence() || Def->isRegSequenceLike())
2233 return getNextSourceFromRegSequence();
2234 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
2235 return getNextSourceFromInsertSubreg();
2236 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
2237 return getNextSourceFromExtractSubreg();
2238 if (Def->isSubregToReg())
2239 return getNextSourceFromSubregToReg();
2240 if (Def->isPHI())
2241 return getNextSourceFromPHI();
2242 return ValueTrackerResult();
2243}
2244
2245ValueTrackerResult ValueTracker::getNextSource() {
2246 // If we reach a point where we cannot move up in the use-def chain,
2247 // there is nothing we can get.
2248 if (!Def)
2249 return ValueTrackerResult();
2250
2251 ValueTrackerResult Res = getNextSourceImpl();
2252 if (Res.isValid()) {
2253 // Update definition, definition index, and subregister for the
2254 // next call of getNextSource.
2255 // Update the current register.
2256 bool OneRegSrc = Res.getNumSources() == 1;
2257 if (OneRegSrc)
2258 Reg = Res.getSrcReg(0);
2259 // Update the result before moving up in the use-def chain
2260 // with the instruction containing the last found sources.
2261 Res.setInst(Def);
2262
2263 // If we can still move up in the use-def chain, move to the next
2264 // definition.
2265 if (!Reg.isPhysical() && OneRegSrc) {
2267 if (DI != MRI.def_end()) {
2268 Def = DI->getParent();
2269 DefIdx = DI.getOperandNo();
2270 DefSubReg = Res.getSrcSubReg(0);
2271 } else {
2272 Def = nullptr;
2273 }
2274 return Res;
2275 }
2276 }
2277 // If we end up here, this means we will not be able to find another source
2278 // for the next iteration. Make sure any new call to getNextSource bails out
2279 // early by cutting the use-def chain.
2280 Def = nullptr;
2281 return Res;
2282}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock & MBB
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static cl::opt< unsigned > RewritePHILimit("rewrite-phi-limit", cl::Hidden, cl::init(10), cl::desc("Limit the length of PHI chains to lookup"))
static cl::opt< bool > DisablePeephole("disable-peephole", cl::Hidden, cl::init(false), cl::desc("Disable the peephole optimizer"))
static cl::opt< unsigned > MaxRecurrenceChain("recurrence-chain-limit", cl::Hidden, cl::init(3), cl::desc("Maximum length of recurrence chain when evaluating the benefit " "of commuting operands"))
static cl::opt< bool > DisableNAPhysCopyOpt("disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false), cl::desc("Disable non-allocatable physical register copy optimization"))
static bool isVirtualRegisterOperand(MachineOperand &MO)
\bried Returns true if MO is a virtual register operand.
static MachineInstr & insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const SmallVectorImpl< RegSubRegPair > &SrcRegs, MachineInstr &OrigPHI)
Insert a PHI instruction with incoming edges SrcRegs that are guaranteed to have the same register cl...
static cl::opt< bool > Aggressive("aggressive-ext-opt", cl::Hidden, cl::desc("Aggressive extension optimization"))
static cl::opt< bool > DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false), cl::desc("Disable advanced copy optimization"))
Specifiy whether or not the value tracking looks through complex instructions.
TargetInstrInfo::RegSubRegPairAndIdx RegSubRegPairAndIdx
static RegSubRegPair getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII, RegSubRegPair Def, const PeepholeOptimizer::RewriteMapTy &RewriteMap, bool HandleMultipleSources=true)
Given a Def.Reg and Def.SubReg pair, use RewriteMap to find the new source to use for rewrite.
MachineRegisterInfo & MRI
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
virt reg Virtual Register Rewriter
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
bool remove_if(Predicate Pred)
Remove entries that match the given predicate.
Definition DenseMap.h:946
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &Mask, int64_t &Value) const override
For a comparison instruction, return the source registers in SrcReg and SrcReg2 if having two registe...
bool isLoopHeader(const BlockT *BB) const
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
An RAII based helper class to modify MachineFunctionProperties when running pass.
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void moveAdditionalCallInfo(const MachineInstr *Old, const MachineInstr *New)
Move the call site info from Old to \New call site info.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
void setDelegate(Delegate *delegate)
Set the delegate.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
LLVM_ABI bool isIdenticalTo(const MachineInstr &Other, MICheckType Check=CheckDefs) const
Return true if this instruction is identical to Other.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool canFoldAsLoad(QueryType Type=IgnoreBundle) const
Return true for instructions that can be folded as memory operands in other instructions.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
unsigned getOperandNo() const
getOperandNo - Return the operand # of this MachineOperand in its MachineInstr.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI void markUsesInDebugValueAsUndef(Register Reg) const
markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the specified register as undefined wh...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
def_iterator def_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
LLVM_ABI bool hasOneNonDBGUser(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
defusechain_iterator< false, true, false, true, false > def_iterator
def_iterator/def_begin/def_end - Walk all defs of the specified register.
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
static def_iterator def_end()
const TargetRegisterInfo * getTargetRegisterInfo() const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI MachineInstr * getOneNonDBGUser(Register RegNo) const
If the register has a single non-Debug instruction using the specified register, returns it; otherwis...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
static const unsigned CommuteAnyOperandIndex
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
MCInstrDesc const & getDesc(MCInstrInfo const &MCII, MCInst const &MCI)
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI char & PeepholeOptimizerLegacyID
PeepholeOptimizer - This pass performs peephole optimizations - like extension and comparison elimina...
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
A pair composed of a pair of a register and a sub-register index, and another sub-register index.
A pair composed of a register and a sub-register index.